diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index e5908c26ac0..00000000000 --- a/.dockerignore +++ /dev/null @@ -1,16 +0,0 @@ -build -build.xml -ChangeLog -composer.json -CONTRIBUTING.md -COPYING -COPYRIGHT -dev -doc -Dockerfile -INSTALL -README-FR.md -README.md -robots.txt -scripts -test \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index bac020e13c5..8d5a54b0548 100644 --- a/.travis.yml +++ b/.travis.yml @@ -79,7 +79,7 @@ matrix: notifications: email: on_success: never # [always|never|change] default: change - on_failure: change # [always|never|change] default: always + on_failure: never # [always|never|change] default: always irc: channels: - "chat.freenode.net#dolibarr" @@ -313,30 +313,33 @@ script: php upgrade2.php 3.9.0 4.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade390400-2.log php step5.php 3.9.0 4.0.0 > $TRAVIS_BUILD_DIR/upgrade390400-3.log php upgrade.php 4.0.0 5.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade400500.log - php upgrade2.php 4.0.0 5.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade400500-2.log + php upgrade2.php 4.0.0 5.0.0 > $TRAVIS_BUILD_DIR/upgrade400500-2.log php step5.php 4.0.0 5.0.0 > $TRAVIS_BUILD_DIR/upgrade400500-3.log php upgrade.php 5.0.0 6.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade500600.log - php upgrade2.php 5.0.0 6.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade500600-2.log + php upgrade2.php 5.0.0 6.0.0 > $TRAVIS_BUILD_DIR/upgrade500600-2.log php step5.php 5.0.0 6.0.0 > $TRAVIS_BUILD_DIR/upgrade500600-3.log php upgrade.php 6.0.0 7.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade600700.log - php upgrade2.php 6.0.0 7.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade600700-2.log + php upgrade2.php 6.0.0 7.0.0 MAIN_MODULE_WEBSITE,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade600700-2.log php step5.php 6.0.0 7.0.0 > $TRAVIS_BUILD_DIR/upgrade600700-3.log cd - set +e echo #cat $TRAVIS_BUILD_DIR/upgrade400500-2.log + #cat $TRAVIS_BUILD_DIR/upgrade500600.log + #cat $TRAVIS_BUILD_DIR/upgrade500600-2.log + #cat $TRAVIS_BUILD_DIR/upgrade500600-3.log #cat /tmp/dolibarr_install.log - | echo "Unit testing" - # Ensure we catch errors. Set this to +e if you want to go to the end to see log file. + # Ensure we catch errors. Set this to +e if you want to go to the end to see dolibarr.log file. set -e phpunit -d memory_limit=-1 -c test/phpunit/phpunittest.xml test/phpunit/AllTests.php set +e - | #echo "Output dolibarr.log" - #echo cat documents/dolibarr.log + #cat documents/dolibarr.log after_script: - | diff --git a/COPYRIGHT b/COPYRIGHT index 04f0358a655..bd3565c3bd1 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -34,12 +34,11 @@ Swift Mailer 5.4.2-DEV MIT license Yes Stripe 4.7.0 MIT licence Yes Library for Stripe module JS libraries: -jQuery 1.11.3 MIT License Yes JS library -jQuery UI 1.11.4 GPL and MIT License Yes JS library plugin UI -jQuery select2 3.5.2 GPL and Apache License Yes JS library plugin for sexier multiselect +jQuery 3.1.1 MIT License Yes JS library +jQuery UI 1.12.1 GPL and MIT License Yes JS library plugin UI +jQuery select2 4.0.5 GPL and Apache License Yes JS library plugin for sexier multiselect jQuery blockUI 2.70.0 GPL and MIT License Yes JS library plugin blockUI (to use ajax popups) jQuery Colorpicker 1.1 MIT License Yes JS library for color picker for a defined list of colors -jQuery FileUpload 5.0.3 GPL and MIT License Yes JS library to upload files jQuery Flot 0.8.3 MIT License Yes JS library to build graph jQuery JCrop 0.9.8 GPL and MIT License Yes JS library plugin Crop (to crop images) jQuery Jeditable 1.7.1 GPL and MIT License Yes JS library plugin jeditable (to edit in place) @@ -49,10 +48,10 @@ jQuery jqueryFileTree 1.0.1 GPL and MIT License Yes jQuery jquerytreeview 1.4.1 MIT License Yes JS library for filetree jQuery TableDnD 0.6 GPL and MIT License Yes JS library plugin TableDnD (to reorder table rows) jQuery Timepicker 1.1.0 GPL and MIT License Yes JS library Timepicker addon for Datepicker -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) +jsGanttImproved 1.7.5.4 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 +Ace 1.2.8 BSD Yes JS library to get code syntaxique coloration in a textarea. For licenses compatibility informations: http://www.gnu.org/licenses/licenses.en.html diff --git a/ChangeLog b/ChangeLog index e5966d0eec7..aa600bdacef 100644 --- a/ChangeLog +++ b/ChangeLog @@ -3,6 +3,32 @@ English Dolibarr ChangeLog -------------------------------------------------------------- + +***** ChangeLog for 7.0.0 compared to 6.0.* ***** +For users: + +For developers: +NEW: Add hook addAdminLdapOptions and doAction in ldap admin page +NEW: complete_head_from_modules() in ldap_prepare_head() + +WARNING: + +Following changes may create regressions for some external modules, but were necessary to make Dolibarr better: +* The methode "cloture" on contract were renamed into "closeAll". +* The substitution key for reference of object is now __REF__ whatever is the object (it replaces __ORDERREF__, + __PROPALREF__, ...) +* The substition key __SIGNATURE__ was renamed into __USER_SIGNATURE__ to standardize naming conventions. +* Substitution keys with syntax %XXX% were renamed into __XXX__ to match others. +* Some REST API to access the dictionary (country, town, ...) were moved into a common API. +* Page bank/index.php and bank/bankentries.php were renamed into bank/list.php and bank/bankentries_list.php to + follow page naming conventions (so default filter/sort order features can also work). +* The trigger ORDER_SUPPLIER_STATUS_ONPROCESS was renamed into ORDER_SUPPLIER_STATUS_ORDERED +* The trigger ORDER_SUPPLIER_STATUS_RECEIVED_ALL was renamed into ORDER_SUPPLIER_STATUS_RECEIVED_COMPLETELY +* The parameter note into method cloture() is added at end of private note (previously in v6, it replaced) +* The parameter $user is now mandatory for method createFromOrder and createFromPropal. +* Remove js library fileupload that was not used by core code. + + ***** ChangeLog for 6.0.3 compared to 6.0.2 ***** FIX: #7211 Update qty dispatched on qty change FIX: #7458 @@ -102,7 +128,7 @@ FIX: View of timespent for another user FIX: ODT generation FIX: CVE-2017-9840, CVE-2017-14238, CVE-2017-14239, CVE-2017-14240, CVE-2017-14241, CVE-2017-14242 - + ***** ChangeLog for 6.0.0 compared to 5.0.* ***** NEW: Add experimental BlockeLog module (to log business events in a non reversible log file). NEW: Add a payment module for Stripe. diff --git a/README.md b/README.md index fbbbdddf665..3d9ba75f1f5 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ ![Build status](https://img.shields.io/travis/Dolibarr/dolibarr/develop.svg) ![Downloads per day](https://img.shields.io/sourceforge/dm/dolibarr.svg) -Dolibarr ERP & CRM is a modern software package to manage your organization's activity (contacts, suppliers, invoices, orders, stocks, agenda, ...). +Dolibarr ERP & CRM is a modern software package to manage your organization's activity (contacts, suppliers, invoices, orders, stocks, agenda…). -It's an Open Source software (wrote in PHP language) designed for small, medium or large companies, foundations and freelances. +It's an Open Source Software (written in PHP language) designed for small, medium or large companies, foundations and freelances. You can freely use, study, modify or distribute it according to its Free Software licence. @@ -29,18 +29,25 @@ Other licenses apply for some included dependencies. See [COPYRIGHT](https://git Releases can be downloaded from [official website](https://www.dolibarr.org/). ### Install from composer -If you do not already have Composer installed, you may do so by following the instructions at getcomposer.org. On Linux and Mac OS X, you'll run the following commands: +If you do not already have Composer installed, you may do so by following the instructions at [getcomposer.org](https://getcomposer.org/). On Linux and macOS, you may run the following commands: + +```bash curl -sS https://getcomposer.org/installer | php mv composer.phar /usr/local/bin/composer +``` -On Windows, you'll download and run https://getcomposer.org/Composer-Setup.exe +On Windows, you can download and run https://getcomposer.org/Composer-Setup.exe +You can then create a new project + +```bash composer create-project dolibarr/dolibarr erp +``` ### Simple setup -If you have low technical skills and you're looking to install Dolibarr ERP/CRM in few clicks, you can use one of the packaged versions: +If you have low technical skills and you're looking to install Dolibarr ERP/CRM in just a few clicks, you can use one of the packaged versions: - DoliWamp for Windows - DoliDeb for Debian or Ubuntu @@ -48,11 +55,11 @@ If you have low technical skills and you're looking to install Dolibarr ERP/CRM ### Advanced setup -You can use a Web server and a supported database (MariaDb, MySql or Postgresql) to install the standard version. +You can use a Web server and a supported database (MariaDB, MySQL or PostgreSQL) to install the standard version. - Uncompress the downloaded archive -- Copy directory "dolibarr" and all its files inside your web server root, or copy directory anywhere and set up your web server to use "dolibarr/htdocs" as root for a new web server virtual host (second choice need to be server administrator) -- Create an empty file "htdocs/conf/conf.php" and set permissions for your web server user (write permissions will be removed once install is finished) +- Copy the "dolibarr" directory and all its files inside your web server root or anywhere you'd like and set up your web server to use "*dolibarr/htdocs*" as root for a new web server virtual host (second choice need to be server administrator) +- Create an empty `htdocs/conf/conf.php` file and set permissions for your web server user (*write* permissions will be removed once install is finished) - From your browser, go to the dolibarr "install/" page The URL will depends on choices made in the first step: @@ -73,10 +80,10 @@ You can use a Web server and a supported database (MariaDb, MySql or Postgresql) ## UPGRADING - Overwrite all old files from 'dolibarr' directory with files provided into the new version's package. -- At first next access, Dolibarr will redirect your to the "install/" page to make the upgrade process. - If a file install.lock exists to lock any run of upgrade process, the application will ask you to remove the file manually (you should find the install.lock file into the directory used to store generated and uploaded documents, in most cases, it is the directory called "documents"). +- At first next access, Dolibarr will redirect your to the "install/" page to follow the upgrade process. +  If an `install.lock` file exists to lock any other upgrade process, the application will ask you to remove the file manually (you should find the `install.lock` file into the directory used to store generated and uploaded documents, in most cases, it is the directory called "*documents*"). -*Note: migration process can safely be done multiple times by calling the page /install/index.php* +*Note: migration process can be safely done multiple times by calling the `/install/index.php` page* ## WHAT'S NEW @@ -172,7 +179,7 @@ Administrator, user, developer and translator's documentations are available alo ## CONTRIBUTING -See file [CONTRIBUTING](https://github.com/Dolibarr/dolibarr/blob/develop/.github/CONTRIBUTING.md) +See [CONTRIBUTING](https://github.com/Dolibarr/dolibarr/blob/develop/.github/CONTRIBUTING.md) file ## CREDITS diff --git a/build/docker/.dockerignore b/build/docker/.dockerignore new file mode 100644 index 00000000000..e345920fb8c --- /dev/null +++ b/build/docker/.dockerignore @@ -0,0 +1,3 @@ +Dockerfile +README.md +docker-compose.yml diff --git a/Dockerfile b/build/docker/Dockerfile similarity index 72% rename from Dockerfile rename to build/docker/Dockerfile index 00a5d0ef567..caa7b0c436a 100644 --- a/Dockerfile +++ b/build/docker/Dockerfile @@ -1,4 +1,7 @@ -FROM php:5.6-apache +FROM php:7.0-apache + +ENV HOST_USER_ID 33 +ENV PHP_INI_DATE_TIMEZONE 'UTC' RUN apt-get update && apt-get install -y libpng12-dev libjpeg-dev libldap2-dev \ && rm -rf /var/lib/apt/lists/* \ @@ -9,11 +12,9 @@ RUN apt-get update && apt-get install -y libpng12-dev libjpeg-dev libldap2-dev \ && docker-php-ext-install mysqli \ && apt-get purge -y libpng12-dev libjpeg-dev libldap2-dev -COPY htdocs/ /var/www/html/ - -RUN chown -hR www-data:www-data /var/www/html - -VOLUME /var/www/html/conf -VOLUME /var/www/html/documents +COPY docker-run.sh /usr/local/bin/ +RUN chmod +x /usr/local/bin/docker-run.sh EXPOSE 80 + +ENTRYPOINT ["docker-run.sh"] diff --git a/build/docker/README.md b/build/docker/README.md new file mode 100644 index 00000000000..5a0997cf121 --- /dev/null +++ b/build/docker/README.md @@ -0,0 +1,25 @@ +# How to use it ? + +The docker-compose.yml file is used to build and run Dolibarr in the current workspace. + +Before build/run, define the variable HOST_USER_ID as following: + + export HOST_USER_ID=$(id -u) + +Go in repository build/docker : + + cd build/docker + +And then, you can run : + + docker-compose up + +This will run 3 container Docker : Dolibarr, MariaDB and PhpMyAdmin. + +The URL to go to the Dolibarr is : + + http://0.0.0.0 + +The URL to go to PhpMyAdmin is (login/password is root/root) : + + http://0.0.0.0:8080 diff --git a/build/docker/docker-compose.yml b/build/docker/docker-compose.yml new file mode 100644 index 00000000000..a2017335197 --- /dev/null +++ b/build/docker/docker-compose.yml @@ -0,0 +1,25 @@ +mariadb: + image: mariadb:latest + environment: + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: dolibarr + +phpmyadmin: + image: phpmyadmin/phpmyadmin + environment: + PMA_HOST: mariadb + links: + - mariadb + ports: + - "8080:80" + +web: + build: . + environment: + HOST_USER_ID: $HOST_USER_ID + volumes: + - ../../htdocs:/var/www/html + links: + - mariadb + ports: + - "80:80" diff --git a/build/docker/docker-run.sh b/build/docker/docker-run.sh new file mode 100644 index 00000000000..c151e1c3cab --- /dev/null +++ b/build/docker/docker-run.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +usermod -u $HOST_USER_ID www-data +groupmod -g $HOST_USER_ID www-data + +chown -hR www-data:www-data /var/www + +if [ ! -f /usr/local/etc/php/php.ini ]; then + cat < /usr/local/etc/php/php.ini +date.timezone = $PHP_INI_DATE_TIMEZONE +display_errors = On +EOF +fi + +exec apache2-foreground diff --git a/build/exe/doliwamp/doliwamp.iss b/build/exe/doliwamp/doliwamp.iss index 2ef8ab32f22..fbd821b367c 100644 --- a/build/exe/doliwamp/doliwamp.iss +++ b/build/exe/doliwamp/doliwamp.iss @@ -32,7 +32,7 @@ AppPublisherURL=http://www.nltechno.com AppSupportURL=http://www.dolibarr.org AppUpdatesURL=http://www.dolibarr.org AppComments=DoliWamp includes Dolibarr, Apache, PHP and Mysql softwares. -AppCopyright=Copyright (C) 2008-2016 Laurent Destailleur, NLTechno +AppCopyright=Copyright (C) 2008-2017 Laurent Destailleur (NLTechno), Fabian Rodriguez (Le Goût du Libre) DefaultDirName=c:\dolibarr DefaultGroupName=Dolibarr ;LicenseFile=COPYING @@ -351,9 +351,8 @@ begin if not FileExists ('c:/windows/system32/msvcr110.dll') and not FileExists ('c:/windows/sysWOW64/msvcr110.dll') and not FileExists ('c:/winnt/system32/msvcr110.dll') and not FileExists ('c:/winnt/sysWOW64/msvcr110.dll') then begin - // TODO Copy file or ask to install package ? - //CustomMessage('YouWillInstallDoliWamp')+#13#13 - MsgBox('The package vcredist_x86.exe must have been installed first. It seems it is not. Please install it first from http://www.microsoft.com/en-us/download/details.aspx?id=30679 then restart DoliWamp installation/upgrade.',mbInformation,MB_OK); + // TODO - offer to install the component by opening the URL in the default browser, abort installation if user doesn't accept + MsgBox('The "Visual C++ Redistributable for Visual Studio 2012" component is missing. Please install the 32-bit version (vcredit_x86.exe) first from http://www.microsoft.com/en-us/download/details.aspx?id=30679 and restart DoliWamp installation/upgrade.',mbInformation,MB_OK); end; // Pb seems similar with msvcp110.dll //vcredist_x64.exe diff --git a/dev/dolibarr_changes.txt b/dev/dolibarr_changes.txt index 3b9ef4cc447..945e7d36ca7 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -82,8 +82,14 @@ with // LDR To open in same window //var OpenWindow=window.open(pRef, "newwin", "height="+vHeight+",width="+vWidth); window.location.href=pRef -* Replace hard coded string with i18n["String"]; +* Replace +vTmpDiv=this.newNode(vTmpCell, 'div', null, null, vTaskList[i].getResource()); +with +var vTmpNode=this.newNode(vTmpCell, 'div', null, ''); +vTmpNode=this.newNode(vTmpNode, 'a', null, '', vLangs[vLang]['moreinfo']); +vTmpNode.setAttribute('href',vTaskList[i].getLink()); + JCROP: ------ diff --git a/dev/examples/code/create_user.php b/dev/examples/code/create_user.php index f745032f575..20173eb914a 100755 --- a/dev/examples/code/create_user.php +++ b/dev/examples/code/create_user.php @@ -60,14 +60,14 @@ $db->begin(); require_once(DOL_DOCUMENT_ROOT."/user/class/user.class.php"); -// Create invoice object +// Create user object $obj = new User($db); //$obj->initAsSpecimen(); $obj->login = 'ABCDEF'; $obj->nom = 'ABCDEF'; -// Create invoice +// Create user $idobject=$obj->create($user); if ($idobject > 0) { diff --git a/dev/examples/code/get_contracts.php b/dev/examples/code/get_contracts.php index 1262fe3eebd..fbe512300e8 100755 --- a/dev/examples/code/get_contracts.php +++ b/dev/examples/code/get_contracts.php @@ -67,7 +67,7 @@ $db->begin(); require_once(DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php"); -// Create invoice object +// Create contract object $obj = new Contrat($db); $obj->socid=$argv[1]; diff --git a/dev/initdata/import-thirdparties.php b/dev/initdata/import-thirdparties.php index 08ad248ecc0..0c32c7ea6a3 100755 --- a/dev/initdata/import-thirdparties.php +++ b/dev/initdata/import-thirdparties.php @@ -21,7 +21,7 @@ /** * \file dev/initdata/import-thirdparties.php - * \brief Script example to insert thirdparties from a csv file. + * \brief Script example to insert thirdparties from a csv file. * To purge data, you can have a look at purge-data.php */ @@ -123,15 +123,15 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) if ($endlinenb && $i > $endlinenb) continue; $nboflines++; - + $object = new Societe($db); $object->state = $fields[6]; $object->client = $fields[7]; $object->fournisseur = $fields[8]; - + $object->name = $fields[13]?trim($fields[13]):$fields[0]; $object->name_alias = $fields[0]!=$fields[13]?trim($fields[0]):''; - + $object->address = trim($fields[14]); $object->zip = trim($fields[15]); $object->town = trim($fields[16]); @@ -149,7 +149,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) $condpayment = trim($fields[36]); if ($condpayment == 'A la commande') $condpayment = 'A réception de commande'; if ($condpayment == 'A reception facture') $condpayment = 'Réception de facture'; - $object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid'); + $object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid', 1); if (empty($object->cond_reglement_id)) { print " - Error cant find payment mode for ".$condpayment."\n"; @@ -166,7 +166,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) // Set price level $object->price_level = 1; if ($labeltype == 'Revendeur') $object->price_level = 2; - + print "Process line nb ".$i.", name ".$object->name; @@ -182,7 +182,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) print " - Error in create result code = ".$ret." - ".$object->errorsToString(); $errorrecord++; } - else + else { print " - Creation OK with name ".$object->name." - id = ".$ret; } @@ -198,7 +198,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) if (! $errorrecord && $fields[3]) { $salesrep=new User($db); - + $tmp=explode(' ',$fields[3],2); $salesrep->firstname = trim($tmp[0]); $salesrep->lastname = trim($tmp[1]); @@ -206,7 +206,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) else $salesrep->login=strtolower($salesrep->firstname); $salesrep->login=preg_replace('/ /','',$salesrep->login); $salesrep->fetch(0,$salesrep->login); - + $result = $object->add_commercial($user, $salesrep->id); if ($result < 0) { @@ -217,14 +217,14 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) { print " - create link sale representative OK"; } - } - + } + dol_syslog("Add invoice contacts"); // Insert an invoice contact if there is an invoice email != standard email if (! $errorrecord && $fields[27] && $fields[26] != $fields[27]) { $ret1=$ret2=0; - + $contact = new Contact($db); $contact->lastname = $object->name; $contact->address=$object->address; @@ -233,7 +233,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) $contact->country_id=$object->country_id; $contact->email=$fields[27]; $contact->socid=$object->id; - + $ret1=$contact->create($user); if ($ret1 > 0) { @@ -244,18 +244,18 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); $errorrecord++; } - else + else { print " - create contact OK"; } } - + dol_syslog("Add delivery contacts"); // Insert a delivery contact if (! $errorrecord && $fields[47]) { $ret1=$ret2=0; - + $contact2 = new Contact($db); $contact2->lastname = 'Service livraison - '.$fields[47]; $contact2->address = $fields[48]; @@ -264,10 +264,10 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) $contact2->country_id=dol_getIdFromCode($db, trim($fields[52]), 'c_country', 'code', 'rowid'); $contact2->note_public=$fields[54]; $contact2->socid=$object->id; - + // Extrafields $contact2->array_options['options_anazoneliv']=price2num($fields[53]); - + $ret1=$contact2->create($user); if ($ret1 > 0) { @@ -278,16 +278,16 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); $errorrecord++; } - else + else { print " - create contact OK"; } } - + print "\n"; - - if ($errorrecord) + + if ($errorrecord) { fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n"); $error++; // $errorrecord will be reset diff --git a/dev/initdata/purge-data.php b/dev/initdata/purge-data.php index f89a3ba2698..f992dcb2dc6 100755 --- a/dev/initdata/purge-data.php +++ b/dev/initdata/purge-data.php @@ -78,15 +78,17 @@ $sqls=array( 'DELETE FROM '.MAIN_DB_PREFIX.'propaldet', 'DELETE FROM '.MAIN_DB_PREFIX.'propal', ), - 'supplier_order'=>array( + 'supplier_proposal'=>array( + 'DELETE FROM '.MAIN_DB_PREFIX.'supplier_proposaldet', + 'DELETE FROM '.MAIN_DB_PREFIX.'supplier_proposal', + ), + 'supplier_order'=>array( 'DELETE FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet', 'DELETE FROM '.MAIN_DB_PREFIX.'commande_fournisseur', ), - 'supplier_invoice'=>array( + 'supplier_invoice'=>array( 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det', 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn', - 'DELETE FROM '.MAIN_DB_PREFIX.'supplier_proposaldet', - 'DELETE FROM '.MAIN_DB_PREFIX.'supplier_proposal', ), 'delivery'=>array( 'DELETE FROM '.MAIN_DB_PREFIX.'livraisondet', @@ -114,8 +116,10 @@ $sqls=array( 'DELETE FROM '.MAIN_DB_PREFIX.'product_lang', 'DELETE FROM '.MAIN_DB_PREFIX.'product_price', 'DELETE FROM '.MAIN_DB_PREFIX.'product_fournisseur_price', - 'DELETE FROM '.MAIN_DB_PREFIX.'product_stock', - 'DELETE FROM '.MAIN_DB_PREFIX.'product', + 'DELETE FROM '.MAIN_DB_PREFIX.'product_batch', + 'DELETE FROM '.MAIN_DB_PREFIX.'product_stock', + 'DELETE FROM '.MAIN_DB_PREFIX.'product_lot', + 'DELETE FROM '.MAIN_DB_PREFIX.'product', ), 'project'=>array( 'DELETE FROM '.MAIN_DB_PREFIX.'projet_task_time', @@ -128,12 +132,13 @@ $sqls=array( ), 'thirdparty'=>array( '@contact', - 'DELETE FROM '.MAIN_DB_PREFIX.'cabinetmed_cons', + 'DELETE FROM '.MAIN_DB_PREFIX.'cabinetmed_cons', 'UPDATE '.MAIN_DB_PREFIX.'adherent SET fk_soc = NULL', 'DELETE FROM '.MAIN_DB_PREFIX.'categorie_fournisseur', 'DELETE FROM '.MAIN_DB_PREFIX.'categorie_societe', 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except', - 'DELETE FROM '.MAIN_DB_PREFIX.'societe', + 'DELETE FROM '.MAIN_DB_PREFIX.'societe_rib', + 'DELETE FROM '.MAIN_DB_PREFIX.'societe', ) ); @@ -152,27 +157,37 @@ $mode = $argv[1]; $option = $argv[2]; if (empty($mode) || ! in_array($mode,array('test','confirm'))) { - print "Usage: $script_file (test|confirm) (all|option)\n"; + print "Usage: $script_file (test|confirm) (all|option) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; print "\n"; print "option can be ".implode(',',array_keys($sqls))."\n"; exit(-1); } if (empty($option) || ! in_array($option, array_merge(array('all'),array_keys($sqls))) ) { - print "Usage: $script_file (test|confirm) (all|option)\n"; + print "Usage: $script_file (test|confirm) (all|option) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; print "\n"; print "option can be ".implode(',',array_keys($sqls))."\n"; exit(-1); } +// Replace database handler +if (! empty($argv[3])) +{ + $db->close(); + unset($db); + $db=getDoliDBInstance($argv[3], $argv[4], $argv[5], $argv[6], $argv[7], $argv[8]); + $user=new User($db); +} +//var_dump($user->db->database_name); $ret=$user->fetch('','admin'); if (! $ret > 0) { - print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; + print 'An admin user with login "admin" must exists to use this script.'."\n"; exit; } -$user->getrights(); +//$user->getrights(); + print "Purge all data for this database:\n"; print "Server = ".$db->database_host."\n"; @@ -190,14 +205,14 @@ if (! $confirmed) /** * Process sql requests of a family - * + * * @param string $family Name of family key of array $sqls * @return int -1 if KO, 1 if OK */ function processfamily($family) { global $db, $sqls; - + $error=0; foreach($sqls[$family] as $sql) { @@ -207,7 +222,7 @@ function processfamily($family) processfamily($newfamily); continue; } - + print "Run sql: ".$sql."\n"; $resql=$db->query($sql); if (! $resql) @@ -217,7 +232,7 @@ function processfamily($family) $error++; } } - + if ($error) { print $db->lasterror(); @@ -225,7 +240,7 @@ function processfamily($family) break; } } - + if ($error) return -1; else return 1; } @@ -242,7 +257,7 @@ foreach($sqls as $family => $familysql) $oldfamily = $family; $result=processfamily($family); - if ($result < 0) + if ($result < 0) { $error++; break; diff --git a/dev/resources/iso-normes/code_nace.txt b/dev/resources/iso-normes/code_nace.txt new file mode 100644 index 00000000000..0c490bd4bf1 --- /dev/null +++ b/dev/resources/iso-normes/code_nace.txt @@ -0,0 +1 @@ +http://ec.europa.eu/eurostat/ramon/nomenclatures/index.cfm?TargetUrl=LST_CLS_DLD&StrNom=NACE_REV2&StrLanguageCode=FR&StrLayoutCode=# \ No newline at end of file diff --git a/dev/resources/sepa/pain.001.001.03.xsd b/dev/resources/sepa/pain.001.001.03.xsd new file mode 100644 index 00000000000..8649779919c --- /dev/null +++ b/dev/resources/sepa/pain.001.001.03.xsd @@ -0,0 +1,921 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dev/resources/sepa/pain.008.001.02.xsd b/dev/resources/sepa/pain.008.001.02.xsd new file mode 100644 index 00000000000..63359725617 --- /dev/null +++ b/dev/resources/sepa/pain.008.001.02.xsd @@ -0,0 +1,879 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dev/resources/sepa/test.xml b/dev/resources/sepa/test.xml new file mode 100644 index 00000000000..fc969a7624c --- /dev/null +++ b/dev/resources/sepa/test.xml @@ -0,0 +1,133 @@ + + + + + PREL20171012/REF10 + 2017-10-12T00:08:30 + 2 + 734.4 + + MyBigCompany + + + + FR76AAAAA + + + + + + + PREL20171012/ID00010-T171001 + DD + 2 + 734.4 + + + SEPA + + + CORE + + RCUR + + 2017-10-12 + + MyBigCompany + + FR + Address1 + Address2 + + + + + FR76123456 + + + + + BICABCDEF + + + SLEV + + + + + FR76AAAAA + + SEPA + + + + + + + + AS-FA1710-0416-000679 + + 540 + + + RUM-CU1610-0001-3-1476058417 + 2016-10-10 + false + + + + + BICXYZ + + + + CUSTOMER A + + FR + Mr abc + + + + + FR123456 + + + + FA1710-0416 + + + + + AS-FA1710-0415-000683 + + 194.4 + + + RUM-CU1709-0011-4-1506525346 + 2017-09-27 + false + + + + + BICJKL + + + + CUSTOMER2 + + FR + + + + + FR76123456 + + + + FA1710-0415 + + + + + diff --git a/dev/resources/sepa/text.txt b/dev/resources/sepa/text.txt new file mode 100644 index 00000000000..0a5336a128e --- /dev/null +++ b/dev/resources/sepa/text.txt @@ -0,0 +1,2 @@ +To test a SEPA file: +http://www.mesfluxdepaiement.fr/testez-vos-fichiers-sepa \ No newline at end of file diff --git a/dev/setup/apache/virtualhost b/dev/setup/apache/virtualhost new file mode 100644 index 00000000000..c3a2dff3e43 --- /dev/null +++ b/dev/setup/apache/virtualhost @@ -0,0 +1,62 @@ + +#php_admin_value sendmail_path "/usr/sbin/sendmail -t -i" +#php_admin_value mail.force_extra_parameters "-f postmaster@mydomain.com" +php_admin_value sendmail_path "/usr/sbin/sendmail -t -i -f postmaster@mydomain.com" +php_admin_value open_basedir /tmp/:/home/../htdocs + +ServerName myvirtualalias +ServerAlias myvirtualalias + +UseCanonicalName On + +AddDefaultCharset UTF-8 + +DocumentRoot "/home/.../htdocs" + + + AllowOverride None + Options -Indexes -MultiViews +FollowSymLinks -ExecCGI + Require all granted + + + + Deny from all + RemoveHandler .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml + AddType application/x-httpd-php-source .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml + + + +ErrorLog /var/log/apache2/myvirtualalias_error_log +TransferLog /var/log/apache2/myvirtualalias_access_log + +# Compress returned resources of type php pages, text file export, css and javascript +AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript + +AddType text/javascript .jgz +AddEncoding gzip .jgz +ExpiresActive On +ExpiresByType image/x-icon A2592000 +ExpiresByType image/gif A2592000 +ExpiresByType image/png A2592000 +ExpiresByType image/jpeg A2592000 +ExpiresByType text/css A2592000 +ExpiresByType text/javascript A2592000 +ExpiresByType application/x-javascript A2592000 +ExpiresByType application/javascript A2592000 + +SSLEngine On + +# A self-signed (snakeoil) certificate can be created by installing +# the ssl-cert package. See +# /usr/share/doc/apache2.2-common/README.Debian.gz for more info. +# If both key and certificate are stored in the same file, only the +# SSLCertificateFile directive is needed. +SSLCertificateFile /etc/letsencrypt/live/www.mydomain.com/cert.pem +SSLCertificateKeyFile /etc/letsencrypt/live/www.mydomain.com/privkey.pem +SSLCertificateChainFile /etc/letsencrypt/live/www.mydomain.com/chain.pem + +#RewriteEngine on +#RewriteCond %{SERVER_PORT} ^80$ +#RewriteRule ^(.*)$ https://%{SERVER_NAME}$1 [L,R] + + diff --git a/dev/setup/codesniffer/ruleset.xml b/dev/setup/codesniffer/ruleset.xml index 32a938662e6..b8cb751fe9e 100644 --- a/dev/setup/codesniffer/ruleset.xml +++ b/dev/setup/codesniffer/ruleset.xml @@ -126,7 +126,7 @@ - + diff --git a/dev/translation/txpush.sh b/dev/translation/txpush.sh index 05ec107b6ff..f64b60f9d3b 100755 --- a/dev/translation/txpush.sh +++ b/dev/translation/txpush.sh @@ -15,7 +15,7 @@ then echo "This push local files to transifex for project $project." echo "Note: If you push a language file (not source), file will be skipped if transifex file is newer." echo " Using -f will overwrite translation but not memory." - echo "Usage: ./dev/translation/txpush.sh (source|xx_XX|all) [-r dolibarr.file] [-f] [--no-interactive]" + echo "Usage: ./dev/translation/txpush.sh (source|xx_XX|all) [-r ".$project.".file] [-f] [--no-interactive]" exit fi diff --git a/doc/images/dolibarr_screenshot5_1920x1080_a.jpg b/doc/images/dolibarr_screenshot5_1920x1080_a.jpg new file mode 100644 index 00000000000..1c6e2cbdbdf Binary files /dev/null and b/doc/images/dolibarr_screenshot5_1920x1080_a.jpg differ diff --git a/doc/images/dolibarr_screenshot5_1920x1080_b.jpg b/doc/images/dolibarr_screenshot5_1920x1080_b.jpg new file mode 100644 index 00000000000..5f7d8a5b573 Binary files /dev/null and b/doc/images/dolibarr_screenshot5_1920x1080_b.jpg differ diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index 905fd8b97ef..4dcc4be7b01 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2017 Alexandre Spangaro - * Copyright (C) 2016 Laurent Destailleur + * Copyright (C) 2016-2017 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -37,7 +37,7 @@ $langs->load("salaries"); $mesg = ''; $action = GETPOST('action','aZ09'); -$cancel = GETPOST('cancel'); +$cancel = GETPOST('cancel','alpha'); $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'int'); @@ -53,12 +53,10 @@ if (! $user->rights->accounting->chartofaccount) accessforbidden(); // Load variable for pagination $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; -$sortfield = GETPOST("sortfield", 'alpha'); -$sortorder = GETPOST("sortorder", 'sortorder'); -$page = GETPOST("page", 'int'); -if ($page == - 1) { - $page = 0; -} +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -69,8 +67,8 @@ $arrayfields=array( 'aa.account_number'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), 'aa.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), 'aa.account_parent'=>array('label'=>$langs->trans("Accountparent"), 'checked'=>0), - 'aa.pcg_type'=>array('label'=>$langs->trans("Pcgtype"), 'checked'=>0), - 'aa.pcg_subtype'=>array('label'=>$langs->trans("Pcgsubtype"), 'checked'=>0), + 'aa.pcg_type'=>array('label'=>$langs->trans("Pcgtype"), 'checked'=>1, 'help'=>'PcgtypeDesc'), + 'aa.pcg_subtype'=>array('label'=>$langs->trans("Pcgsubtype"), 'checked'=>1, 'help'=>'PcgtypeDesc'), 'aa.active'=>array('label'=>$langs->trans("Activated"), 'checked'=>1) ); @@ -84,8 +82,8 @@ $contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'accounting * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction')) { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha')) { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -94,9 +92,9 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { if (! empty($cancel)) $action = ''; - + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers { $search_account = ""; @@ -106,26 +104,44 @@ if (empty($reshook)) $search_pcgsubtype = ""; $search_array_options=array(); } - - if (GETPOST('change_chart')) + + if (GETPOST('change_chart','alpha')) { $chartofaccounts = GETPOST('chartofaccounts', 'int'); - - if (! empty($chartofaccounts)) { - + + if ($chartofaccounts > 0) + { + // Get language code for this $chartofaccounts + $sql ='SELECT code FROM '.MAIN_DB_PREFIX.'c_country as c, '.MAIN_DB_PREFIX.'accounting_system as a'; + $sql.=' WHERE c.rowid = a.fk_country AND a.rowid = '.(int) $chartofaccounts; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $country_code = $obj->code; + } + else dol_print_error($db); + + // Try to load sql file + if ($country_code) + { + $sqlfile = DOL_DOCUMENT_ROOT.'/install/mysql/data/llx_accounting_account_'.strtolower($country_code).'.sql'; + $result = run_sql($sqlfile, 1, 0, 1); + } + if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { - $error ++; + $error++; } } else { $error ++; } } - + if ($action == 'disable') { if ($accounting->fetch($id)) { $result = $accounting->account_desactivate($id); } - + $action = 'update'; if ($result < 0) { setEventMessages($accounting->error, $accounting->errors, 'errors'); @@ -179,7 +195,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $resql = $db->query($sql); $nbtotalofrecords = $db->num_rows($resql); -} +} $sql .= $db->plimit($limit + 1, $offset); @@ -190,13 +206,14 @@ if ($resql) { $num = $db->num_rows($resql); - $params=''; + $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($search_account) $params.= '&search_account='.urlencode($search_account); - if ($search_label) $params.= '&search_label='.urlencode($search_label); - if ($search_accountparent) $params.= '&search_accountparent='.urlencode($search_accountparent); - if ($search_pcgtype) $params.= '&search_pcgtype='.urlencode($search_pcgtype); - if ($search_pcgsubtype) $params.= '&search_pcgsubtype='.urlencode($search_pcgsubtype); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($search_account) $param.= '&search_account='.urlencode($search_account); + if ($search_label) $param.= '&search_label='.urlencode($search_label); + if ($search_accountparent) $param.= '&search_accountparent='.urlencode($search_accountparent); + if ($search_pcgtype) $param.= '&search_pcgtype='.urlencode($search_pcgtype); + if ($search_pcgsubtype) $param.= '&search_pcgsubtype='.urlencode($search_pcgsubtype); if ($optioncss != '') $param.='&optioncss='.$optioncss; @@ -209,40 +226,44 @@ if ($resql) print ''; print ''; print ''; - + $htmlbuttonadd = '' . $langs->trans("Addanaccount") . ''; - - print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $params, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $htmlbuttonadd); - + + print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $htmlbuttonadd, '', $limit); + // Box to select active chart of account print $langs->trans("Selectchartofaccounts") . " : "; print '"; + print ajax_combobox("chartofaccounts"); print ''; - print '
'; + print '
'; print '
'; - + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - + print '
'; print ''."\n"; @@ -259,13 +280,13 @@ if ($resql) print $searchpicto; print ''; print ''; - + print ''; if (! empty($arrayfields['aa.account_number']['checked'])) print_liste_field_titre($arrayfields['aa.account_number']['label'], $_SERVER["PHP_SELF"],"aa.account_number","",$param,'',$sortfield,$sortorder); if (! empty($arrayfields['aa.label']['checked'])) print_liste_field_titre($arrayfields['aa.label']['label'], $_SERVER["PHP_SELF"],"aa.label","",$param,'',$sortfield,$sortorder); if (! empty($arrayfields['aa.account_parent']['checked'])) print_liste_field_titre($arrayfields['aa.account_parent']['label'], $_SERVER["PHP_SELF"],"aa.account_parent", "", $param,'align="left"',$sortfield,$sortorder); - if (! empty($arrayfields['aa.pcg_type']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_type']['label'],$_SERVER["PHP_SELF"],'aa.pcg_type','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['aa.pcg_subtype']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_subtype']['label'],$_SERVER["PHP_SELF"],'aa.pcg_subtype','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['aa.pcg_type']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_type']['label'],$_SERVER["PHP_SELF"],'aa.pcg_type','',$param,'',$sortfield,$sortorder,'',$arrayfields['aa.pcg_type']['help']); + if (! empty($arrayfields['aa.pcg_subtype']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_subtype']['label'],$_SERVER["PHP_SELF"],'aa.pcg_subtype','',$param,'',$sortfield,$sortorder,'',$arrayfields['aa.pcg_subtype']['help']); if (! empty($arrayfields['aa.active']['checked'])) print_liste_field_titre($arrayfields['aa.active']['label'],$_SERVER["PHP_SELF"],'aa.active','',$param,'',$sortfield,$sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; @@ -274,14 +295,14 @@ if ($resql) $accountparent = new AccountingAccount($db); $i=0; - while ($i < min($num, $limit)) + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $accountstatic->id = $obj->rowid; $accountstatic->label = $obj->label; $accountstatic->account_number = $obj->account_number; - + print ''; // Account number @@ -310,7 +331,7 @@ if ($resql) $accountparent->id = $obj->rowid2; $accountparent->label = $obj->label2; $accountparent->account_number = $obj->account_number2; - + print "\n"; @@ -371,11 +392,11 @@ if ($resql) } print '' . "\n"; if (! $i) $totalarray['nbfield']++; - + print "\n"; $i++; } - + print "
"; print $accountparent->getNomUrl(1); print "
"; print "
"; print ''; diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 94e16738bf4..f3924f73a76 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -41,14 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -$langs->load("errors"); -$langs->load("admin"); -$langs->load("main"); -$langs->load("companies"); -$langs->load("resource"); -$langs->load("holiday"); -$langs->load("accountancy"); -$langs->load("hrm"); +$langs->loadLangs(array("errors","admin","companies","resource","holiday","compta","accountancy","hrm")); $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; $confirm=GETPOST('confirm','alpha'); @@ -68,7 +61,7 @@ $active = 1; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); -if ($page == -1 || $page == null) { $page = 0 ; } +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $listlimit * $page ; $pageprev = $page - 1; $pagenext = $page + 1; @@ -87,9 +80,6 @@ $hookmanager->initHooks(array('admin')); // This page is a generic page to edit dictionaries // Put here declaration of dictionaries properties -// Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this. -$taborder=array(9,0,4,3,2,0,1,8,19,16,27,0,5,11,0,33,34,0,6,0,29,0,7,17,24,28,0,10,23,12,13,0,14,0,22,20,18,21,0,15,30,0,25,0,26,0,31,32,0); - // Name of SQL tables of dictionaries $tabname=array(); @@ -103,7 +93,7 @@ $tablib[32]= "DictionaryAccountancyCategory"; // Requests to extract data $tabsql=array(); -$tabsql[31]= "SELECT s.rowid as rowid, pcg_version, s.label, s.active FROM ".MAIN_DB_PREFIX."accounting_system as s"; +$tabsql[31]= "SELECT s.rowid as rowid, pcg_version, s.label, s.fk_country as country_id, c.code as country_code, c.label as country, s.active FROM ".MAIN_DB_PREFIX."accounting_system as s, ".MAIN_DB_PREFIX."c_country as c WHERE s.fk_country=c.rowid and c.active=1"; $tabsql[32]= "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.sens, a.category_type, a.formula, a.position as position, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid and c.active=1"; // Criteria to sort dictionaries @@ -113,17 +103,17 @@ $tabsqlsort[32]="position ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire $tabfield=array(); -$tabfield[31]= "pcg_version,label"; +$tabfield[31]= "pcg_version,label,country_id,country"; $tabfield[32]= "code,label,range_account,sens,category_type,formula,position,country_id,country"; // Nom des champs d'edition pour modification d'un enregistrement $tabfieldvalue=array(); -$tabfieldvalue[31]= "pcg_version,label"; +$tabfieldvalue[31]= "pcg_version,label,country"; $tabfieldvalue[32]= "code,label,range_account,sens,category_type,formula,position,country"; // Nom des champs dans la table pour insertion d'un enregistrement $tabfieldinsert=array(); -$tabfieldinsert[31]= "pcg_version,label"; +$tabfieldinsert[31]= "pcg_version,label,fk_country"; $tabfieldinsert[32]= "code,label,range_account,sens,category_type,formula,position,fk_country"; // Nom du rowid si le champ n'est pas de type autoincrement @@ -148,75 +138,10 @@ $tabfieldcheck=array(); $tabfieldcheck[31] = array(); $tabfieldcheck[32] = array(); -// Complete all arrays with entries found into modules -complete_dictionary_with_modules($taborder,$tabname,$tablib,$tabsql,$tabsqlsort,$tabfield,$tabfieldvalue,$tabfieldinsert,$tabrowid,$tabcond,$tabhelp,$tabfieldcheck); - // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") $elementList = array(); $sourceList=array(); -if ($id == 11) -{ - $langs->load("orders"); - $langs->load("contracts"); - $langs->load("projects"); - $langs->load("propal"); - $langs->load("bills"); - $langs->load("interventions"); - $elementList = array( - '' => '', - 'societe' => $langs->trans('ThirdParty'), -// 'proposal' => $langs->trans('Proposal'), -// 'order' => $langs->trans('Order'), -// 'invoice' => $langs->trans('Bill'), - 'invoice_supplier' => $langs->trans('SupplierBill'), - 'order_supplier' => $langs->trans('SupplierOrder'), -// 'intervention' => $langs->trans('InterventionCard'), -// 'contract' => $langs->trans('Contract'), - 'project' => $langs->trans('Project'), - 'project_task' => $langs->trans('Task'), - 'agenda' => $langs->trans('Agenda'), - // old deprecated - 'contrat' => $langs->trans('Contract'), - 'propal' => $langs->trans('Proposal'), - 'commande' => $langs->trans('Order'), - 'facture' => $langs->trans('Bill'), - 'resource' => $langs->trans('Resource'), -// 'facture_fourn' => $langs->trans('SupplierBill'), - 'fichinter' => $langs->trans('InterventionCard') - ); - if (! empty($conf->global->MAIN_SUPPORT_SHARED_CONTACT_BETWEEN_THIRDPARTIES)) $elementList["societe"] = $langs->trans('ThirdParty'); - - complete_elementList_with_modules($elementList); - - asort($elementList); - $sourceList = array( - 'internal' => $langs->trans('Internal'), - 'external' => $langs->trans('External') - ); -} -if ($id == 25) -{ - // We save list of template email Dolibarr can manage. This list can found by a grep into code on "->param['models']" - $elementList = array(); - if ($conf->propal->enabled) $elementList['propal_send']=$langs->trans('MailToSendProposal'); - if ($conf->commande->enabled) $elementList['order_send']=$langs->trans('MailToSendOrder'); - if ($conf->facture->enabled) $elementList['facture_send']=$langs->trans('MailToSendInvoice'); - if ($conf->expedition->enabled) $elementList['shipping_send']=$langs->trans('MailToSendShipment'); - if ($conf->ficheinter->enabled) $elementList['fichinter_send']=$langs->trans('MailToSendIntervention'); - if ($conf->supplier_proposal->enabled) $elementList['supplier_proposal_send']=$langs->trans('MailToSendSupplierRequestForQuotation'); - if ($conf->fournisseur->enabled) $elementList['order_supplier_send']=$langs->trans('MailToSendSupplierOrder'); - if ($conf->fournisseur->enabled) $elementList['invoice_supplier_send']=$langs->trans('MailToSendSupplierInvoice'); - if ($conf->societe->enabled) $elementList['thirdparty']=$langs->trans('MailToThirdparty'); - - $parameters=array('elementList'=>$elementList); - $reshook=$hookmanager->executeHooks('emailElementlist',$parameters); // Note that $action and $object may have been modified by some hooks - if ($reshook == 0) { - foreach ($hookmanager->resArray as $item => $value) { - $elementList[$item] = $value; - } - } -} @@ -226,309 +151,311 @@ if ($id == 25) if (GETPOST('button_removefilter') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter_x')) { - $search_country_id = ''; + $search_country_id = ''; } // Actions add or modify an entry into a dictionary if (GETPOST('actionadd') || GETPOST('actionmodify')) { - $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); - $listfieldinsert=explode(',',$tabfieldinsert[$id]); - $listfieldmodify=explode(',',$tabfieldinsert[$id]); - $listfieldvalue=explode(',',$tabfieldvalue[$id]); + $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); + $listfieldinsert=explode(',',$tabfieldinsert[$id]); + $listfieldmodify=explode(',',$tabfieldinsert[$id]); + $listfieldvalue=explode(',',$tabfieldvalue[$id]); - // Check that all fields are filled - $ok=1; - foreach ($listfield as $f => $value) - { - if ($value == 'country_id' && in_array($tablib[$id],array('DictionaryVAT','DictionaryRegion','DictionaryCompanyType','DictionaryHolidayTypes','DictionaryRevenueStamp','DictionaryAccountancysystem','DictionaryAccountancyCategory'))) continue; // For some pages, country is not mandatory - if ($value == 'country' && in_array($tablib[$id],array('DictionaryCanton','DictionaryCompanyType','DictionaryRevenueStamp'))) continue; // For some pages, country is not mandatory - if ($value == 'localtax1' && empty($_POST['localtax1_type'])) continue; - if ($value == 'localtax2' && empty($_POST['localtax2_type'])) continue; - if ($value == 'color' && empty($_POST['color'])) continue; + // Check that all fields are filled + $ok=1; + foreach ($listfield as $f => $value) + { + if ($value == 'country_id' && in_array($tablib[$id],array('DictionaryVAT','DictionaryRegion','DictionaryCompanyType','DictionaryHolidayTypes','DictionaryRevenueStamp','DictionaryAccountancyCategory','Pcg_version'))) continue; // For some pages, country is not mandatory + if ($value == 'country' && in_array($tablib[$id],array('DictionaryCanton','DictionaryCompanyType','DictionaryRevenueStamp'))) continue; // For some pages, country is not mandatory + if ($value == 'localtax1' && empty($_POST['localtax1_type'])) continue; + if ($value == 'localtax2' && empty($_POST['localtax2_type'])) continue; + if ($value == 'color' && empty($_POST['color'])) continue; if ($value == 'formula' && empty($_POST['formula'])) continue; - if ((! isset($_POST[$value]) || $_POST[$value]=='') - && (! in_array($listfield[$f], array('decalage','module','accountancy_code','accountancy_code_sell','accountancy_code_buy')) // Fields that are not mandatory - && (! ($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 - ) + if ((! isset($_POST[$value]) || $_POST[$value]=='') + && (! in_array($listfield[$f], array('decalage','module','accountancy_code','accountancy_code_sell','accountancy_code_buy')) // Fields that are not mandatory + && (! ($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 + ) ) - { - $ok=0; - $fieldnamekey=$listfield[$f]; - // We take translate key of field - if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; - if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; - if ($fieldnamekey == 'nbjour') $fieldnamekey='NbOfDays'; - if ($fieldnamekey == 'decalage') $fieldnamekey='Offset'; - if ($fieldnamekey == 'module') $fieldnamekey='Module'; - if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; - if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; - if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; - if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; - if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; - if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode'; - if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible'; - if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder'; + { + $ok=0; + $fieldnamekey=$listfield[$f]; + // We take translate key of field + + if ($fieldnamekey == 'pcg_version') $fieldnamekey='Pcg_version'; + if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; + if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; + if ($fieldnamekey == 'nbjour') $fieldnamekey='NbOfDays'; + if ($fieldnamekey == 'decalage') $fieldnamekey='Offset'; + if ($fieldnamekey == 'module') $fieldnamekey='Module'; + if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; + if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; + if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; + if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; + if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; + if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode'; + if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible'; + if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder'; if ($fieldnamekey == 'category_type') $fieldnamekey = 'Calculated'; - setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); - } - } - // Other checks - if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"],array('system','systemauto'))) { - $ok=0; - setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); - } - if (isset($_POST["code"])) - { - if ($_POST["code"]=='0') - { - $ok=0; - setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); - } - /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); + } + } + // Other checks + if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"],array('system','systemauto'))) { + $ok=0; + setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); + } + if (isset($_POST["code"])) + { + if ($_POST["code"]=='0') + { + $ok=0; + setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); + } + /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base { $ok = 0; - $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; + $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ - } - if (isset($_POST["country"]) && ($_POST["country"]=='0') && ($id != 2)) - { - if (in_array($tablib[$id],array('DictionaryCompanyType','DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries - { - $_POST["country"]=''; - } - else - { - $ok=0; - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->transnoentities("Country")), null, 'errors'); - } - } - if ($id == 3 && ! is_numeric($_POST["code"])) - { - $ok=0; - setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric",$langs->transnoentities("Code")), null, 'errors'); - } + } + if (isset($_POST["country"]) && ($_POST["country"]=='0') && ($id != 2)) + { + if (in_array($tablib[$id],array('DictionaryCompanyType','DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries + { + $_POST["country"]=''; + } + else + { + $ok=0; + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->transnoentities("Country")), null, 'errors'); + } + } + if ($id == 3 && ! is_numeric($_POST["code"])) + { + $ok=0; + setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric",$langs->transnoentities("Code")), null, 'errors'); + } // Clean some parameters - if (isset($_POST["localtax1"]) && empty($_POST["localtax1"])) $_POST["localtax1"]='0'; // If empty, we force to 0 - if (isset($_POST["localtax2"]) && empty($_POST["localtax2"])) $_POST["localtax2"]='0'; // If empty, we force to 0 + if (isset($_POST["localtax1"]) && empty($_POST["localtax1"])) $_POST["localtax1"]='0'; // If empty, we force to 0 + if (isset($_POST["localtax2"]) && empty($_POST["localtax2"])) $_POST["localtax2"]='0'; // If empty, we force to 0 if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]=''; // If empty, we force to null if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]=''; // If empty, we force to null - // Si verif ok et action add, on ajoute la ligne - if ($ok && GETPOST('actionadd')) - { - if ($tabrowid[$id]) - { - // Recupere id libre pour insertion - $newid=0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); + // Si verif ok et action add, on ajoute la ligne + if ($ok && GETPOST('actionadd')) + { + if ($tabrowid[$id]) + { + // Recupere id libre pour insertion + $newid=0; + $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + $newid=($obj->newid + 1); - } else { - dol_print_error($db); - } - } + } else { + dol_print_error($db); + } + } - // Add new entry - $sql = "INSERT INTO ".$tabname[$id]." ("; - // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $tabrowid[$id].","; - $sql.= $tabfieldinsert[$id]; - $sql.=",active)"; - $sql.= " VALUES("; + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $tabrowid[$id].","; + $sql.= $tabfieldinsert[$id]; + $sql.=",active)"; + $sql.= " VALUES("; - // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $newid.","; - $i=0; - foreach ($listfieldinsert as $f => $value) - { - if ($value == 'price' || preg_match('/^amount/i',$value) || $value == 'taux') { - $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); - } - else if ($value == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql.=",1)"; + // List of values + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $newid.","; + $i=0; + foreach ($listfieldinsert as $f => $value) + { + if ($value == 'price' || preg_match('/^amount/i',$value) || $value == 'taux') { + $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); + } + else if ($value == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.=",1)"; - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST=array('id'=>$id); // Clean $_POST array, we keep only - } - else - { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } - else { - dol_print_error($db); - } - } - } + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + $_POST=array('id'=>$id); // Clean $_POST array, we keep only + } + else + { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } + else { + dol_print_error($db); + } + } + } - // Si verif ok et action modify, on modifie la ligne - if ($ok && GETPOST('actionmodify')) - { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + // Si verif ok et action modify, on modifie la ligne + if ($ok && GETPOST('actionmodify')) + { + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) - { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; - } - $i = 0; - foreach ($listfieldmodify as $field) - { - if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { - $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); - } - else if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql.=","; - $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) + { + $sql.= $tabrowid[$id]."="; + $sql.= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { + $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); + } + else if ($field == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + $sql.= $field."="; + if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if (! $resql) - { - setEventMessages($db->error(), null, 'errors'); - } - } - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if (! $resql) + { + setEventMessages($db->error(), null, 'errors'); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if (GETPOST('actioncancel')) { - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; - dol_syslog("delete", LOG_DEBUG); - $result = $db->query($sql); - if (! $result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } - else - { - dol_print_error($db); - } - } + dol_syslog("delete", LOG_DEBUG); + $result = $db->query($sql); + if (! $result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } + else + { + dol_print_error($db); + } + } } // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // favorite if ($action == 'activate_favorite') { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable favorite if ($action == 'disable_favorite') { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } @@ -548,8 +475,8 @@ print load_fiche_titre($titre,$linkback,'title_accountancy'); if (empty($id)) { - print $langs->trans("DictionaryDesc"); - print " ".$langs->trans("OnlyActiveElementsAreShown")."
\n"; + print $langs->trans("DictionaryDesc"); + print " ".$langs->trans("OnlyActiveElementsAreShown")."
\n"; } print "
\n"; @@ -557,7 +484,7 @@ print "
\n"; // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); } //var_dump($elementList); @@ -566,640 +493,557 @@ if ($action == 'delete') */ if ($id) { - // Complete requete recherche valeurs avec critere de tri - $sql=$tabsql[$id]; + // Complete requete recherche valeurs avec critere de tri + $sql=$tabsql[$id]; - if ($search_country_id > 0) - { - if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; - else $sql.=" WHERE "; - $sql.= " c.rowid = ".$search_country_id; - } + if ($search_country_id > 0) + { + if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; + else $sql.=" WHERE "; + $sql.= " c.rowid = ".$search_country_id; + } - if ($sortfield) - { - // If sort order is "country", we use country_code instead - if ($sortfield == 'country') $sortfield='country_code'; - $sql.= " ORDER BY ".$sortfield; - if ($sortorder) - { - $sql.=" ".strtoupper($sortorder); - } - $sql.=", "; - // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value - $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]); - $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]); - } - else { - $sql.=" ORDER BY "; - } - $sql.=$tabsqlsort[$id]; - $sql.=$db->plimit($listlimit+1,$offset); - //print $sql; + if ($sortfield) + { + // If sort order is "country", we use country_code instead + if ($sortfield == 'country') $sortfield='country_code'; + $sql.= " ORDER BY ".$sortfield; + if ($sortorder) + { + $sql.=" ".strtoupper($sortorder); + } + $sql.=", "; + // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]); + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]); + } + else { + $sql.=" ORDER BY "; + } + $sql.=$tabsqlsort[$id]; + $sql.=$db->plimit($listlimit+1,$offset); + //print $sql; - $fieldlist=explode(',',$tabfield[$id]); + $fieldlist=explode(',',$tabfield[$id]); - print '
'; - print ''; + print ''; + print ''; - print ''; + print '
'; + print '
'; - // Form to add a new line - if ($tabname[$id]) - { - $alabelisused=0; - $var=false; + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused=0; + $var=false; - $fieldlist=explode(',',$tabfield[$id]); + $fieldlist=explode(',',$tabfield[$id]); - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - $align="left"; - if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } - if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } - if ($fieldlist[$field]=='taux') { + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + $align="left"; + if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } + if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } + if ($fieldlist[$field]=='taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow=$langs->trans("Rate"); else $valuetoshow=$langs->trans("Amount"); $align='right'; - } - if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2";} - if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3";} - if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } - if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } - if ($fieldlist[$field]=='type') { + } + if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2";} + if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3";} + if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } + if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } + if ($fieldlist[$field]=='type') { if ($tabname[$id] == MAIN_DB_PREFIX."c_paiement") $valuetoshow=$form->textwithtooltip($langs->trans("Type"),$langs->trans("TypePaymentDesc"),2,1,img_help(1,'')); else $valuetoshow=$langs->trans("Type"); - } - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') - { - $valuetoshow=$langs->trans("Label"); - if ($id != 25) $valuetoshow.="*"; - } - if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } - if ($fieldlist[$field]=='country') { - if (in_array('region_id',$fieldlist)) { print ''; continue; } // For region page, we do not show the country input - $valuetoshow=$langs->trans("Country"); - } - if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } - if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } - if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } - if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } - if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } - if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } - if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $valuetoshow=''; } - if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } - if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); } - if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); } - if ($fieldlist[$field]=='pcg_version' || $fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } - if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountparent"); } - if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } - if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } - if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } - if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } - if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } + } + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + { + $valuetoshow=$langs->trans("Label"); + if ($id != 25) $valuetoshow.="*"; + } + if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } + if ($fieldlist[$field]=='country') { + if (in_array('region_id',$fieldlist)) { print ''; continue; } // For region page, we do not show the country input + $valuetoshow=$langs->trans("Country"); + } + if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } + if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } + if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } + if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } + if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } + if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } + if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $valuetoshow=''; } + if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } + if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); } + if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); } + if ($fieldlist[$field]=='pcg_version' || $fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } + if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountparent"); } + if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } + if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } + if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } + if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } + if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Sens"); } if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } if ($fieldlist[$field]=='formula') { $valuetoshow=$langs->trans("Formula"); } - if ($id == 2) // Special cas for state page - { - if ($fieldlist[$field]=='region_id') { $valuetoshow=' '; $showfield=1; } - if ($fieldlist[$field]=='region') { $valuetoshow=$langs->trans("Country").'/'.$langs->trans("Region"); $showfield=1; } - } + if ($id == 2) // Special cas for state page + { + if ($fieldlist[$field]=='region_id') { $valuetoshow=' '; $showfield=1; } + if ($fieldlist[$field]=='region') { $valuetoshow=$langs->trans("Country").'/'.$langs->trans("Region"); $showfield=1; } + } - if ($valuetoshow != '') - { - print ''; - } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; - } + if ($valuetoshow != '') + { + print ''; + } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; + } - if ($id == 4) print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - // Line to enter new values - print ""; + // Line to enter new values + print ""; - $obj = new stdClass(); - // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val)) - $obj->$val=GETPOST($val); - } - } + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd')) + { + foreach ($fieldlist as $key=>$val) + { + if (GETPOST($val)) + $obj->$val=GETPOST($val); + } + } - $tmpaction = 'create'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $tmpaction = 'create'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - if ($id == 3) unset($fieldlist[2]); + if ($id == 3) unset($fieldlist[2]); - if (empty($reshook)) - { - if ($tabname[$id] == MAIN_DB_PREFIX.'c_email_templates' && $action == 'edit') - { + if (empty($reshook)) + { + if ($tabname[$id] == MAIN_DB_PREFIX.'c_email_templates' && $action == 'edit') + { fieldListAccountModel($fieldlist,$obj,$tabname[$id],'hide'); - } - else - { - fieldListAccountModel($fieldlist,$obj,$tabname[$id],'add'); - } - } + } + else + { + fieldListAccountModel($fieldlist,$obj,$tabname[$id],'add'); + } + } - if ($id == 4) print ''; - print ''; - print ""; + print ''; + print ""; - if ($tabname[$id] == MAIN_DB_PREFIX.'c_email_templates') - { - print ''; - } + $colspan=count($fieldlist)+3; - $colspan=count($fieldlist)+3; - if ($id == 4) $colspan++; - - if (! empty($alabelisused) && $id != 25) // If there is one label among fields, we show legend of * - { - print ''; - } - print ''; // Keep   to have a line with enough height - } + if (! empty($alabelisused)) // If there is one label among fields, we show legend of * + { + print ''; + } + print ''; // Keep   to have a line with enough height + } - // List of available values in database - dol_syslog("htdocs/admin/dict", LOG_DEBUG); - $resql=$db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - $var=true; + // List of available values in database + dol_syslog("htdocs/admin/dict", LOG_DEBUG); + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + $var=true; - $param = '&id='.$id; - if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; - $paramwithsearch = $param; - if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; - if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; + $param = '&id='.$id; + if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; + $paramwithsearch = $param; + if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; + if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; - // There is several pages - if ($num > $listlimit) - { - print ''; - } + // There is several pages + if ($num > $listlimit) + { + print ''; + } - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $showfield=1; // By defaut - $align="left"; - $sortable=1; - $valuetoshow=''; - /* + // Title line with search boxes + print ''; + foreach ($fieldlist as $field => $value) + { + $showfield=1; // By defaut + + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + + if ($showfield) + { + if ($value == 'country') + { + print ''; + } + else + { + print ''; + } + } + } + print ''; + print ''; + print ''; + + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $showfield=1; // By defaut + $align="left"; + $sortable=1; + $valuetoshow=''; + /* $tmparray=getLabelOfField($fieldlist[$field]); $showfield=$tmp['showfield']; $valuetoshow=$tmp['valuetoshow']; $align=$tmp['align']; $sortable=$tmp['sortable']; */ - $valuetoshow=ucfirst($fieldlist[$field]); // By defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } - if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } - if ($fieldlist[$field]=='taux') { + $valuetoshow=ucfirst($fieldlist[$field]); // By defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } + if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } + if ($fieldlist[$field]=='taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow=$langs->trans("Rate"); else $valuetoshow=$langs->trans("Amount"); $align='right'; - } - if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2"; $sortable=0; } - if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3"; $sortable=0; } - if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } - if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } - if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') - { - $valuetoshow=$langs->trans("Label"); - if ($id != 25) $valuetoshow.="*"; - } - if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } - if ($fieldlist[$field]=='country') { $valuetoshow=$langs->trans("Country"); } - if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } - if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } - if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } - if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } - if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } - if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } - if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } - if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } - if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); $sortable=0; } - if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); $sortable=0; } + } + if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2"; $sortable=0; } + if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3"; $sortable=0; } + if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } + if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } + if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + { + $valuetoshow=$langs->trans("Label"); + if ($id != 25) $valuetoshow.="*"; + } + if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } + if ($fieldlist[$field]=='country') { $valuetoshow=$langs->trans("Country"); } + if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } + if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } + if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } + if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } + if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } + if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } + if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } + if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); $sortable=0; } + if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); $sortable=0; } if ($fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } - if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountsparent"); } - if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } - if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } - if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } - if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } - if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } + if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountsparent"); } + if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } + if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } + if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } + if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } + if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Sens"); } if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } if ($fieldlist[$field]=='formula') { $valuetoshow=$langs->trans("Formula"); } - // Affiche nom du champ - if ($showfield) - { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); - } - } - // Favorite - Only activated on country dictionary - if ($id == 4) print getTitleFieldOfList($langs->trans("Favorite"), 0, $_SERVER["PHP_SELF"], "favorite", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); - + // Affiche nom du champ + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); + } + } print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; - // Title line with search boxes - print ''; - foreach ($fieldlist as $field => $value) - { - $showfield=1; // By defaut + if ($num) + { + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) + { + print ''; + print ''; + print ''; + print ''; - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + $tmpaction='edit'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - if ($showfield) - { - if ($value == 'country') - { - print ''; - } - else - { - print ''; - } - } - } - if ($id == 4) print ''; - print ''; - print ''; - print ''; + if (empty($reshook)) fieldListAccountModel($fieldlist,$obj,$tabname[$id],'edit'); - if ($num) - { - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); - //print_r($obj); - print ''; - if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) - { - print ''; - print ''; - print ''; - print ''; + print ''; + } + else + { + $tmpaction = 'view'; + $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $tmpaction='edit'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $error=$hookmanager->error; $errors=$hookmanager->errors; - if (empty($reshook)) fieldListAccountModel($fieldlist,$obj,$tabname[$id],'edit'); + if (empty($reshook)) + { + foreach ($fieldlist as $field => $value) + { - print ''; - } - else - { - $tmpaction = 'view'; - $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - - $error=$hookmanager->error; $errors=$hookmanager->errors; - - if (empty($reshook)) - { - foreach ($fieldlist as $field => $value) - { - - $showfield=1; - $align="left"; - $valuetoshow=$obj->{$fieldlist[$field]}; - if ($value == 'type_template') - { - $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; - } - if ($value == 'element') - { - $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; - } - else if ($value == 'source') - { - $valuetoshow = isset($sourceList[$valuetoshow])?$sourceList[$valuetoshow]:$valuetoshow; - } - else if ($valuetoshow=='all') { - $valuetoshow=$langs->trans('All'); - } - else if ($fieldlist[$field]=='country') { - if (empty($obj->country_code)) - { - $valuetoshow='-'; - } - else - { - $key=$langs->trans("Country".strtoupper($obj->country_code)); - $valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country); - } - } - else if ($fieldlist[$field]=='recuperableonly' || $fieldlist[$field]=='type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - if(empty($valuetoshow)) $valuetoshow = $langs->trans('None'); - elseif($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); - elseif($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); - $align="center"; - } - else if ($fieldlist[$field]=='price' || preg_match('/^amount/i',$fieldlist[$field])) { - $valuetoshow=price($valuetoshow); - } - else if ($fieldlist[$field]=='libelle_facture') { - $langs->load("bills"); - $key=$langs->trans("PaymentCondition".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "PaymentCondition".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - $valuetoshow=nl2br($valuetoshow); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_country') { - $key=$langs->trans("Country".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "Country".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_availability') { - $langs->load("propal"); - $key=$langs->trans("AvailabilityType".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "AvailabilityType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_actioncomm') { - $key=$langs->trans("Action".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "Action".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if (! empty($obj->code_iso) && $fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_currencies') { - $key=$langs->trans("Currency".strtoupper($obj->code_iso)); - $valuetoshow=($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_typent') { - $key=$langs->trans(strtoupper($obj->code)); - $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_prospectlevel') { - $key=$langs->trans(strtoupper($obj->code)); - $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_civility') { - $key=$langs->trans("Civility".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "Civility".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_type_contact') { - $langs->load('agenda'); - $key=$langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_payment_term') { - $langs->load("bills"); - $key=$langs->trans("PaymentConditionShort".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paiement') { - $langs->load("bills"); - $key=$langs->trans("PaymentType".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "PaymentType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_reason') { - $key=$langs->trans("DemandReasonType".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "DemandReasonType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_method') { - $langs->load("orders"); - $key=$langs->trans($obj->code); - $valuetoshow=($obj->code && $key != $obj->code)?$key:$obj->{$fieldlist[$field]}; - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_shipment_mode') { - $langs->load("sendings"); - $key=$langs->trans("SendingMethod".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "SendingMethod".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field] == 'libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paper_format') - { - $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') - { - $langs->load('trips'); - $key = $langs->trans(strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { - $showfield=0; - } - else if ($fieldlist[$field]=='unicode') { - $valuetoshow = $langs->getCurrencySymbol($obj->code,1); - } - else if ($fieldlist[$field]=='label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow=$langs->trans($obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='short_label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); - } - else if (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) - { - $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); - $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); - } + $showfield=1; + $align="left"; + $valuetoshow=$obj->{$fieldlist[$field]}; + if ($value == 'type_template') + { + $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; + } + if ($value == 'element') + { + $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; + } + else if ($value == 'source') + { + $valuetoshow = isset($sourceList[$valuetoshow])?$sourceList[$valuetoshow]:$valuetoshow; + } + else if ($valuetoshow=='all') { + $valuetoshow=$langs->trans('All'); + } + else if ($fieldlist[$field]=='country') { + if (empty($obj->country_code)) + { + $valuetoshow='-'; + } + else + { + $key=$langs->trans("Country".strtoupper($obj->country_code)); + $valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country); + } + } + else if ($fieldlist[$field]=='recuperableonly' || $fieldlist[$field]=='type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { + if(empty($valuetoshow)) $valuetoshow = $langs->trans('None'); + elseif($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); + elseif($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); + $align="center"; + } + else if ($fieldlist[$field]=='price' || preg_match('/^amount/i',$fieldlist[$field])) { + $valuetoshow=price($valuetoshow); + } + else if ($fieldlist[$field]=='libelle_facture') { + $langs->load("bills"); + $key=$langs->trans("PaymentCondition".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "PaymentCondition".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + $valuetoshow=nl2br($valuetoshow); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_country') { + $key=$langs->trans("Country".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "Country".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_availability') { + $langs->load("propal"); + $key=$langs->trans("AvailabilityType".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "AvailabilityType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_actioncomm') { + $key=$langs->trans("Action".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "Action".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if (! empty($obj->code_iso) && $fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_currencies') { + $key=$langs->trans("Currency".strtoupper($obj->code_iso)); + $valuetoshow=($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_typent') { + $key=$langs->trans(strtoupper($obj->code)); + $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_prospectlevel') { + $key=$langs->trans(strtoupper($obj->code)); + $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_civility') { + $key=$langs->trans("Civility".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "Civility".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_type_contact') { + $langs->load('agenda'); + $key=$langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_payment_term') { + $langs->load("bills"); + $key=$langs->trans("PaymentConditionShort".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paiement') { + $langs->load("bills"); + $key=$langs->trans("PaymentType".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "PaymentType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_reason') { + $key=$langs->trans("DemandReasonType".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "DemandReasonType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_method') { + $langs->load("orders"); + $key=$langs->trans($obj->code); + $valuetoshow=($obj->code && $key != $obj->code)?$key:$obj->{$fieldlist[$field]}; + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_shipment_mode') { + $langs->load("sendings"); + $key=$langs->trans("SendingMethod".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "SendingMethod".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field] == 'libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paper_format') + { + $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') + { + $langs->load('trips'); + $key = $langs->trans(strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { + $showfield=0; + } + else if ($fieldlist[$field]=='unicode') { + $valuetoshow = $langs->getCurrencySymbol($obj->code,1); + } + else if ($fieldlist[$field]=='label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow=$langs->trans($obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='short_label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); + } + else if (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) + { + $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); + $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); + } else if ($fieldlist[$field]=='taux') { - $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); - $align="right"; + $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); + $align="right"; } else if (in_array($fieldlist[$field],array('recuperableonly'))) { $align="center"; } else if ($fieldlist[$field]=='accountancy_code' || $fieldlist[$field]=='accountancy_code_sell' || $fieldlist[$field]=='accountancy_code_buy') { - $valuetoshow = length_accountg($valuetoshow); - } + $valuetoshow = length_accountg($valuetoshow); + } - $class='tddict'; - if ($fieldlist[$field] == 'tracking') $class.=' tdoverflowauto'; + $class='tddict'; + if ($fieldlist[$field] == 'tracking') $class.=' tdoverflowauto'; // Show value for field if ($showfield) print ''; - } - } - - // Can an entry be erased or disabled ? - $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default - if (isset($obj->code) && $id != 10) - { - if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } - } - - if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable=0; } - if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled=0; $canbedisabled = 0; } - $canbemodified=$iserasable; - if ($obj->code == 'RECEP') $canbemodified=1; - - $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); - if ($param) $url .= '&'.$param; - $url.='&'; - - // Favorite - // Only activated on country dictionary - if ($id == 4) - { - print ''; + } } - // Active - print '"; + // Can an entry be erased or disabled ? + $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default + if (isset($obj->code) && $id != 10) + { + if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } + } - // Modify link - if ($canbemodified) print ''; - else print ''; + if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable=0; } + if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled=0; $canbedisabled = 0; } + $canbemodified=$iserasable; + if ($obj->code == 'RECEP') $canbemodified=1; - // Delete link - if ($iserasable) print ''; - else print ''; + $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); + if ($param) $url .= '&'.$param; + $url.='&'; - print "\n"; - } - $i++; - } - } - } - else { - dol_print_error($db); - } + // Active + print '"; - print '
  '; - if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; - else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); - else print $valuetoshow; - print ''; + if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; + else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); + else print $valuetoshow; + print ''; - print ''; - print '
'; + print ''; + print '
'; - if ($tabname[$id] != MAIN_DB_PREFIX.'c_email_templates' || $action != 'edit') - { - print ''; - } - print '
'; + if ($tabname[$id] != MAIN_DB_PREFIX.'c_email_templates' || $action != 'edit') + { + print ''; + } + print '
* '.$langs->trans("AvailableVariables").": "; - require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $tmp=FormMail::getAvailableSubstitKey('formemail'); - print implode(', ', $tmp); - print '
* '.$langs->trans("LabelUsedByDefault").'.
 
* '.$langs->trans("LabelUsedByDefault").'.
 
'; - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); - print '
'; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth200 maxwidthonsmartphone'); + print ''; + $searchpicto=$form->showFilterAndCheckAddButtons(0); + print $searchpicto; + print '
'; - print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth200 maxwidthonsmartphone'); - print ''; - $searchpicto=$form->showFilterAndCheckAddButtons(0); - print $searchpicto; - print '
 '; + print '  '; - print ' '.$valuetoshow.''; - if ($iserasable) print ''.$actl[$obj->favorite].''; - else print $langs->trans("AlwaysActive"); - print ''; - if ($canbedisabled) print ''.$actl[$obj->active].''; - else - { - if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); - else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); - else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); - else print $langs->trans("AlwaysActive"); - } - print "'.img_edit().' '.img_delete().' 
'; + if ($canbedisabled) print ''.$actl[$obj->active].''; + else + { + if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); + else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); + else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); + else print $langs->trans("AlwaysActive"); + } + print "
'; + // Modify link + if ($canbemodified) print ''.img_edit().''; + else print ' '; - print '
'; -} -else -{ - /* - * Show list of dictionary to show - */ + // Delete link + if ($iserasable) print ''.img_delete().''; + else print ' '; - $lastlineisempty=false; - print ''; - print ''; - //print ''; - print ''; - print ''; - print ''; + print "\n"; + } + $i++; + } + } + } + else { + dol_print_error($db); + } - $showemptyline=''; - foreach ($taborder as $i) - { - if (isset($tabname[$i]) && empty($tabcond[$i])) continue; + print '
'.$langs->trans("Module").''.$langs->trans("Dictionary").''.$langs->trans("Table").'
'; + print ''; - if ($i) - { - if ($showemptyline) - { - print '   '; - $showemptyline=0; - } - - - $value=$tabname[$i]; - print ''; - if (! empty($tabcond[$i])) - { - print ''.$langs->trans($tablib[$i]).''; - } - else - { - print $langs->trans($tablib[$i]); - } - print ''; - print ''; - /*if (empty($tabcond[$i])) - { - print info_admin($langs->trans("DictionaryDisabledSinceNoModuleNeedIt"),1); - }*/ - print ''; - print ''.$tabname[$i].''; - $lastlineisempty=false; - } - else - { - if (! $lastlineisempty) - { - $showemptyline=1; - $lastlineisempty=true; - } - } - } - print ''; + print ''; } print '
'; @@ -1303,8 +1147,8 @@ function fieldListAccountModel($fieldlist, $obj='', $tabname='', $context='') print ''; } elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - if ($fieldlist[$field] == 'type_cdr') print ''; - else print ''; + if ($fieldlist[$field] == 'type_cdr') print ''; + else print ''; if ($fieldlist[$field] == 'type_cdr') { print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); } else { diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php index fa3adf1301b..79a8a531ec9 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -37,10 +37,10 @@ $langs->load("accountancy"); $mesg = ''; $action = GETPOST('action','aZ09'); -$backtopage = GETPOST('backtopage'); +$backtopage = GETPOST('backtopage','alpha'); $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'int'); -$cancel = GETPOST('cancel'); +$cancel = GETPOST('cancel','alpha'); // Security check @@ -52,7 +52,7 @@ $object = new AccountingAccount($db); * Action */ -if (GETPOST('cancel')) +if (GETPOST('cancel','alpha')) { $urltogo=$backtopage?$backtopage:dol_buildpath('/accountancy/admin/account.php',1); header("Location: ".$urltogo); @@ -63,7 +63,7 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) { if (! $cancel) { $sql = 'SELECT pcg_version FROM ' . MAIN_DB_PREFIX . 'accounting_system WHERE rowid=' . $conf->global->CHARTOFACCOUNTS; - + dol_syslog('accountancy/admin/card.php:: $sql=' . $sql); $result = $db->query($sql); $obj = $db->fetch_object($result); @@ -172,16 +172,16 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) } } else if ($action == 'delete' && $user->rights->accounting->chartofaccount) { $result = $object->fetch($id); - + if (! empty($object->id)) { $result = $object->delete($user); - + if ($result > 0) { header("Location: account.php"); exit; } } - + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -270,7 +270,7 @@ if ($action == 'create') { $head = accounting_prepare_head($object); // Edit mode - if ($action == 'update') + if ($action == 'update') { dol_fiche_head($head, 'card', $langs->trans('AccountAccounting'), 0, 'billr'); @@ -327,7 +327,7 @@ if ($action == 'create') { print ''; } else { // View mode - $linkback = '' . $langs->trans("BackToChartofaccounts") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; dol_fiche_head($head, 'card', $langs->trans('AccountAccounting'), 0, 'billr'); diff --git a/htdocs/accountancy/admin/categories.php b/htdocs/accountancy/admin/categories.php index f9200a575be..b281078a6bf 100644 --- a/htdocs/accountancy/admin/categories.php +++ b/htdocs/accountancy/admin/categories.php @@ -35,7 +35,7 @@ $langs->load("accountancy"); $mesg = ''; $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'int'); -$cancel = GETPOST('cancel'); +$cancel = GETPOST('cancel','alpha'); $action = GETPOST('action','aZ09'); $cat_id = GETPOST('account_category'); $selectcpt = GETPOST('cpt_bk', 'array'); @@ -98,7 +98,7 @@ dol_fiche_head(); print ''; // Category -print ''; +print ''; print ''; + print ''; print ''; diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index 270d882eac7..488123acc70 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -1,16 +1,6 @@ - * Copyright (C) 2004-2015 Laurent Destailleur - * Copyright (C) 2004 Benoit Mortier - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2010-2016 Juanjo Menent - * Copyright (C) 2011-2015 Philippe Grand - * Copyright (C) 2011 Remy Younes - * Copyright (C) 2012-2015 Marcos García - * Copyright (C) 2012 Christophe Battarel - * Copyright (C) 2011-2016 Alexandre Spangaro - * Copyright (C) 2015 Ferran Marcet - * Copyright (C) 2016 Raphaël Doursenaud +/* Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2011-2017 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -52,7 +42,7 @@ $langs->load("hrm"); $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; $confirm=GETPOST('confirm','alpha'); -$id=GETPOST('id','int'); +$id=32; $rowid=GETPOST('rowid','alpha'); $code=GETPOST('code','alpha'); @@ -74,7 +64,7 @@ $active = 1; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); -if ($page == -1 || $page == null) { $page = 0 ; } +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $listlimit * $page ; $pageprev = $page - 1; $pagenext = $page + 1; @@ -100,7 +90,7 @@ $tablib[32]= "DictionaryAccountancyCategory"; // Requests to extract data $tabsql=array(); -$tabsql[32]= "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.sens, a.category_type, a.formula, a.position as position, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid and c.active=1"; +$tabsql[32]= "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.category_type, a.formula, a.position as position, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid and c.active=1"; // Criteria to sort dictionaries $tabsqlsort=array(); @@ -108,15 +98,15 @@ $tabsqlsort[32]="position ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire $tabfield=array(); -$tabfield[32]= "code,label,range_account,sens,category_type,formula,position,country_id,country"; +$tabfield[32]= "code,label,range_account,category_type,formula,position,country"; // Nom des champs d'edition pour modification d'un enregistrement $tabfieldvalue=array(); -$tabfieldvalue[32]= "code,label,range_account,sens,category_type,formula,position,country"; +$tabfieldvalue[32]= "code,label,range_account,category_type,formula,position,country_id"; // Nom des champs dans la table pour insertion d'un enregistrement $tabfieldinsert=array(); -$tabfieldinsert[32]= "code,label,range_account,sens,category_type,formula,position,fk_country"; +$tabfieldinsert[32]= "code,label,range_account,category_type,formula,position,fk_country"; // Nom du rowid si le champ n'est pas de type autoincrement // Example: "" if id field is "rowid" and has autoincrement on @@ -167,24 +157,17 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $ok=1; foreach ($listfield as $f => $value) { - if ($value == 'country_id' && in_array($tablib[$id],array('DictionaryVAT','DictionaryRegion','DictionaryCompanyType','DictionaryHolidayTypes','DictionaryRevenueStamp','DictionaryAccountancysystem','DictionaryAccountancyCategory'))) continue; // For some pages, country is not mandatory - if ($value == 'country' && in_array($tablib[$id],array('DictionaryCanton','DictionaryCompanyType','DictionaryRevenueStamp'))) continue; // For some pages, country is not mandatory if ($value == 'formula' && empty($_POST['formula'])) continue; - if ((! isset($_POST[$value]) || $_POST[$value]=='') - && (! in_array($listfield[$f], array('decalage','module','accountancy_code','accountancy_code_sell','accountancy_code_buy')) // Fields that are not mandatory - && (! ($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 - ) - ) + if ($value == 'range_account' && empty($_POST['range_account'])) continue; + if ($value == 'country') continue; // country_id required but not country + if (! isset($_POST[$value]) || $_POST[$value]=='') { $ok=0; $fieldnamekey=$listfield[$f]; // We take translate key of field if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; - if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; - if ($fieldnamekey == 'module') $fieldnamekey='Module'; if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; - if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; if ($fieldnamekey == 'category_type') $fieldnamekey = 'Calculated'; @@ -192,11 +175,6 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); } } - // Other checks - if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"],array('system','systemauto'))) { - $ok=0; - setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); - } if (isset($_POST["code"])) { if ($_POST["code"]=='0') @@ -207,20 +185,13 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base { $ok = 0; - $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; + $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ } - if (isset($_POST["country"]) && ($_POST["country"]=='0')) + if (isset($_POST["country"]) && ($_POST["country"] <= 0)) { - if (in_array($tablib[$id],array('DictionaryCompanyType','DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries - { - $_POST["country"]=''; - } - else - { - $ok=0; - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->transnoentities("Country")), null, 'errors'); - } + $ok=0; + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->transnoentities("Country")), null, 'errors'); } // Clean some parameters @@ -262,14 +233,11 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $i=0; foreach ($listfieldinsert as $f => $value) { - if ($value == 'price' || preg_match('/^amount/i',$value) || $value == 'taux') { - $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); - } - else if ($value == 'entity') { + if ($value == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' + if ($_POST[$listfieldvalue[$i]] == '' && ! $listfieldvalue[$i] == 'formula') $sql.="null"; // For vat, we want/accept code = '' else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } @@ -310,15 +278,15 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $i = 0; foreach ($listfieldmodify as $field) { - if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { - $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); + if ($field == 'fk_country' && $_POST['country'] > 0) { + $_POST[$listfieldvalue[$i]] = $_POST['country']; } else if ($field == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } if ($i) $sql.=","; $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' + if ($_POST[$listfieldvalue[$i]] == '' && ! $listfieldvalue[$i] == 'range_account') $sql.="null"; // For range_account, we want/accept code = '' else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } @@ -458,11 +426,15 @@ $titlepicto='title_setup'; print load_fiche_titre($titre,$linkback,$titlepicto); +if ($id == 32) +{ + print $langs->trans("AccountingAccountGroupsDesc", $langs->transnoentitiesnoconv("ByPersonalizedAccountGroups")).'

'; +} // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id.($search_country_id>0?'&search_country_id='.$search_country_id:''), $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); } //var_dump($elementList); @@ -508,6 +480,7 @@ if ($id) print ''; print ''; + print '
'; print '
' . $langs->trans("AccountingCategory") . '
' . $langs->trans("AccountingCategory") . ''; $formaccounting->select_accounting_category($cat_id, 'account_category', 1, 0, 0, 1); print ''; @@ -110,14 +110,26 @@ if (! empty($cat_id)) if ($return < 0) { setEventMessages(null, $accountingcategory->errors, 'errors'); } - print '
' . $langs->trans("AddAccountFromBookKeepingWithNoCategories") . '
' . $langs->trans("AddAccountFromBookKeepingWithNoCategories") . ''; + + $arraykeyvalue=array(); + foreach($accountingcategory->lines_cptbk as $key => $val) + { + $arraykeyvalue[length_accountg($val->numero_compte)] = length_accountg($val->numero_compte) . ' (' . $val->label_compte . ($val->doc_ref?' '.$val->doc_ref:'').')'; + } + if (is_array($accountingcategory->lines_cptbk) && count($accountingcategory->lines_cptbk) > 0) { - print ''; foreach ( $accountingcategory->lines_cptbk as $cpt ) { print ''; } print '
'; + print ajax_combobox('cpt_bk'); + */ print ' '; } print '
'; // Form to add a new line @@ -536,18 +509,15 @@ if ($id) { $valuetoshow=$langs->trans("Label"); } - if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } + if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments"); } if ($fieldlist[$field]=='country') { - if (in_array('region_id',$fieldlist)) { print ''; continue; } // For region page, we do not show the country input $valuetoshow=$langs->trans("Country"); } - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $valuetoshow=''; } if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); } if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); } if ($fieldlist[$field]=='pcg_version' || $fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } - if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } - if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Direction"); } + if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Comment"); } if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } if ($valuetoshow != '') @@ -599,6 +569,7 @@ if ($id) print ""; $colspan=count($fieldlist)+3; + if ($id == 32) $colspan++; print ''; // Keep   to have a line with enough height } @@ -617,8 +588,7 @@ if ($id) $paramwithsearch = $param; if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; - if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha'); - + if (GETPOST('from','alpha')) $paramwithsearch.= '&from='.GETPOST('from','alpha'); // There is several pages if ($num > $listlimit) { @@ -700,8 +670,7 @@ if ($id) if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } - if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } - if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Direction"); } + if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Comment"); } if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } // Affiche nom du champ if ($showfield) @@ -742,6 +711,7 @@ if ($id) print '
'; print ''; print ''; + print ''; } else { @@ -759,17 +729,9 @@ if ($id) $showfield=1; $align="left"; $valuetoshow=$obj->{$fieldlist[$field]}; - if ($value == 'type_template') + if ($value == 'category_type') { - $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; - } - if ($value == 'element') - { - $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; - } - else if ($value == 'source') - { - $valuetoshow = isset($sourceList[$valuetoshow])?$sourceList[$valuetoshow]:$valuetoshow; + $valuetoshow = yn($valuetoshow); } else if ($valuetoshow=='all') { $valuetoshow=$langs->trans('All'); @@ -785,12 +747,6 @@ if ($id) $valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country); } } - else if ($fieldlist[$field]=='libelle_facture') { - $langs->load("bills"); - $key=$langs->trans("PaymentCondition".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "PaymentCondition".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - $valuetoshow=nl2br($valuetoshow); - } else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_country') { $key=$langs->trans("Country".strtoupper($obj->code)); $valuetoshow=($obj->code && $key != "Country".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); @@ -804,83 +760,11 @@ if ($id) $key=$langs->trans("Action".strtoupper($obj->code)); $valuetoshow=($obj->code && $key != "Action".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); } - else if (! empty($obj->code_iso) && $fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_currencies') { - $key=$langs->trans("Currency".strtoupper($obj->code_iso)); - $valuetoshow=($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_typent') { - $key=$langs->trans(strtoupper($obj->code)); - $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_prospectlevel') { - $key=$langs->trans(strtoupper($obj->code)); - $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_civility') { - $key=$langs->trans("Civility".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "Civility".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_type_contact') { - $langs->load('agenda'); - $key=$langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_payment_term') { - $langs->load("bills"); - $key=$langs->trans("PaymentConditionShort".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paiement') { - $langs->load("bills"); - $key=$langs->trans("PaymentType".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "PaymentType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_reason') { - $key=$langs->trans("DemandReasonType".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "DemandReasonType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_method') { - $langs->load("orders"); - $key=$langs->trans($obj->code); - $valuetoshow=($obj->code && $key != $obj->code)?$key:$obj->{$fieldlist[$field]}; - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_shipment_mode') { - $langs->load("sendings"); - $key=$langs->trans("SendingMethod".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "SendingMethod".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field] == 'libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paper_format') - { - $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') - { - $langs->load('trips'); - $key = $langs->trans(strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } else if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } - else if ($fieldlist[$field]=='label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow=$langs->trans($obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='short_label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); - } - else if (in_array($fieldlist[$field],array('recuperableonly'))) - { - $align="center"; - } - else if ($fieldlist[$field]=='accountancy_code' || $fieldlist[$field]=='accountancy_code_sell' || $fieldlist[$field]=='accountancy_code_buy') { - $valuetoshow = length_accountg($valuetoshow); - } $class='tddict'; - if ($fieldlist[$field] == 'tracking') $class.=' tdoverflowauto'; // Show value for field if ($showfield) print ''; } @@ -891,14 +775,9 @@ if ($id) if (isset($obj->code)) { if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } } - if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable=0; } - if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled=0; $canbedisabled = 0; } $canbemodified=$iserasable; - if ($obj->code == 'RECEP') $canbemodified=1; $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); if ($param) $url .= '&'.$param; @@ -909,10 +788,7 @@ if ($id) if ($canbedisabled) print ''.$actl[$obj->active].''; else { - if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); - else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); - else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); - else print $langs->trans("AlwaysActive"); + print $langs->trans("AlwaysActive"); } print ""; @@ -937,8 +813,8 @@ if ($id) print ''.$langs->trans("Setup").''; } print ''; - print "\n"; } + print "\n"; $i++; } } @@ -948,6 +824,7 @@ if ($id) } print '
 
 
'.$valuetoshow.'
'; + print ''; print ''; } @@ -984,16 +861,17 @@ function fieldListAccountingCategories($fieldlist, $obj='', $tabname='', $contex { if ($fieldlist[$field] == 'country') { - if (in_array('region_id',$fieldlist)) - { - print ''; - //print join(',',$fieldlist); - print ''; - continue; - } // For state page, we do not show the country input (we link to region, not country) print ''; $fieldname='country'; - print $form->select_country((! empty($obj->country_code)?$obj->country_code:(! empty($obj->country)?$obj->country:$mysoc->country_code)), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); + if ($context == 'add') + { + $fieldname='country_id'; + print $form->select_country(GETPOST('country_id','int'), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); + } + else + { + print $form->select_country((! empty($obj->country_code)?$obj->country_code:(! empty($obj->country)?$obj->country:$mysoc->country_code)), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); + } print ''; } elseif ($fieldlist[$field] == 'country_id') @@ -1006,130 +884,14 @@ function fieldListAccountingCategories($fieldlist, $obj='', $tabname='', $contex print ''; } } - elseif ($fieldlist[$field] == 'region') - { - print ''; - $formcompany->select_region($region_id,'region'); + elseif ($fieldlist[$field] == 'category_type') { + print ''; + print $form->selectyesno($fieldlist[$field],(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''),1); print ''; } - elseif ($fieldlist[$field] == 'region_id') - { - $region_id = (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:0); - print ''; - print ''; - print ''; - } - elseif ($fieldlist[$field] == 'lang') - { - print ''; - print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT,'lang'); - print ''; - } - // Le type de template - elseif ($fieldlist[$field] == 'type_template') - { - print ''; - print $form->selectarray('type_template', $elementList,(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); - print ''; - } - // Le type de l'element (pour les type de contact) - elseif ($fieldlist[$field] == 'element') - { - print ''; - print $form->selectarray('element', $elementList,(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); - print ''; - } - // La source de l'element (pour les type de contact) - elseif ($fieldlist[$field] == 'source') - { - print ''; - print $form->selectarray('source', $sourceList,(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); - print ''; - } - elseif ($fieldlist[$field] == 'type' && $tabname == MAIN_DB_PREFIX."c_actioncomm") - { - print ''; - print 'user'; - print ''; - } - elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - if ($fieldlist[$field] == 'type_cdr') print ''; - else print ''; - if ($fieldlist[$field] == 'type_cdr') { - print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); - } else { - print $form->selectyesno($fieldlist[$field],(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''),1); - } - print ''; - } - elseif (in_array($fieldlist[$field],array('nbjour','decalage','taux','localtax1','localtax2'))) { - $align="left"; - if (in_array($fieldlist[$field],array('taux','localtax1','localtax2'))) $align="center"; // Fields aligned on right - print ''; - print ''; - print ''; - } - elseif (in_array($fieldlist[$field], array('libelle_facture'))) { - print ''; - } - elseif (in_array($fieldlist[$field], array('content'))) - { - if ($tabname == MAIN_DB_PREFIX.'c_email_templates') - { - print ''; // To create an artificial CR for the current tr we are on - } - else print ''; - if ($context != 'hide') - { - //print ''; - $okforextended=true; - if ($tabname == MAIN_DB_PREFIX.'c_email_templates' && empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended=false; - $doleditor = new DolEditor($fieldlist[$field], (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_5, '90%'); - print $doleditor->Create(1); - } - else print ' '; - print ''; - } - elseif ($fieldlist[$field] == 'price' || preg_match('/^amount/i',$fieldlist[$field])) { - print ''; - } elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) { print ''; } - elseif ($fieldlist[$field]=='unit') { - print ''; - $units = array( - 'mm' => $langs->trans('SizeUnitmm'), - 'cm' => $langs->trans('SizeUnitcm'), - 'point' => $langs->trans('SizeUnitpoint'), - 'inch' => $langs->trans('SizeUnitinch') - ); - print $form->selectarray('unit', $units, (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 0, 0, 0); - print ''; - } - // Le type de taxe locale - elseif ($fieldlist[$field] == 'localtax1_type' || $fieldlist[$field] == 'localtax2_type') - { - print ''; - print $form->selectarray($fieldlist[$field], $localtax_typeList, (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); - print ''; - } - elseif ($fieldlist[$field] == 'accountancy_code' || $fieldlist[$field] == 'accountancy_code_sell' || $fieldlist[$field] == 'accountancy_code_buy') - { - print ''; - if (! empty($conf->accounting->enabled)) - { - $fieldname = $fieldlist[$field]; - $accountancy_account = (! empty($obj->$fieldname) ? $obj->$fieldname : 0); - print $formaccounting->select_account($accountancy_account, $fieldlist[$field], 1, '', 1, 1, 'maxwidth200 maxwidthonsmartphone'); - } - else - { - $fieldname = $fieldlist[$field]; - print ''; - } - print ''; - } else { print ''; @@ -1137,8 +899,7 @@ function fieldListAccountingCategories($fieldlist, $obj='', $tabname='', $contex if ($fieldlist[$field]=='code') $class='maxwidth100'; if ($fieldlist[$field]=='position') $class='maxwidth50'; if ($fieldlist[$field]=='libelle') $class='quatrevingtpercent'; - if ($fieldlist[$field]=='tracking') $class='quatrevingtpercent'; - if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" '; + if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='category_type') $size='size="2" '; print ''; print ''; } diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index ce99bd6296c..c4b31c0f169 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -77,7 +77,7 @@ $list_account = array ( * Actions */ -$accounting_mode = defined('ACCOUNTING_MODE') ? ACCOUNTING_MODE : 'RECETTES-DEPENSES'; +$accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' : $conf->global->ACCOUNTING_MODE; if (GETPOST('change_chart')) diff --git a/htdocs/accountancy/admin/export.php b/htdocs/accountancy/admin/export.php index a30ca0d7443..af11824e91a 100644 --- a/htdocs/accountancy/admin/export.php +++ b/htdocs/accountancy/admin/export.php @@ -1,6 +1,6 @@ - * Copyright (C) 2013-2015 Alexandre Spangaro + * Copyright (C) 2013-2017 Alexandre Spangaro * Copyright (C) 2014 Florian Henry * Copyright (C) 2014 Marcos García * Copyright (C) 2014 Juanjo Menent @@ -38,10 +38,10 @@ $langs->load("bills"); $langs->load("admin"); $langs->load("accountancy"); -// Security check -if (empty($user->admin) && empty($user->rights->accounting->chartofaccount)) +// Security access +if (empty($user->rights->accounting->chartofaccount)) { - accessforbidden(); + accessforbidden(); } $action = GETPOST('action', 'alpha'); @@ -140,7 +140,7 @@ llxHeader(); $form = new Form($db); -$linkback = '' . $langs->trans("BackToModuleList") . ''; +// $linkback = '' . $langs->trans("BackToModuleList") . ''; print load_fiche_titre($langs->trans('ConfigAccountingExpert'), $linkback, 'title_setup'); $head = admin_accounting_prepare_head(); @@ -195,7 +195,6 @@ print ''; dol_fiche_head($head, 'export', $langs->trans("Configuration"), -1, 'technic'); - /* * Main Options */ @@ -287,8 +286,6 @@ if ($num2) { print "\n"; } -dol_fiche_end(); - print '
'; print ''; diff --git a/htdocs/accountancy/admin/fiscalyear_card.php b/htdocs/accountancy/admin/fiscalyear_card.php index 420246411c8..78c6510469b 100644 --- a/htdocs/accountancy/admin/fiscalyear_card.php +++ b/htdocs/accountancy/admin/fiscalyear_card.php @@ -20,6 +20,7 @@ * \ingroup Advanced accountancy * \brief Page to show a fiscal year */ + require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/fiscalyear.lib.php'; diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index b6aceb52ad4..a6215383f35 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -6,6 +6,7 @@ * Copyright (C) 2014 Marcos García * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2017 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,7 +20,6 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * */ /** @@ -37,10 +37,9 @@ $langs->load("compta"); $langs->load("bills"); $langs->load("admin"); $langs->load("accountancy"); -$langs->load("salaries"); -// Security check -if (empty($user->admin)) +// Security access +if (empty($user->rights->accounting->chartofaccount)) { accessforbidden(); } @@ -61,7 +60,7 @@ $list = array ( * Actions */ -$accounting_mode = defined('ACCOUNTING_MODE') ? ACCOUNTING_MODE : 'RECETTES-DEPENSES'; +$accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' : $conf->global->ACCOUNTING_MODE; if ($action == 'update') { $error = 0; @@ -160,20 +159,15 @@ llxHeader(); $form = new Form($db); -$linkback = '' . $langs->trans("BackToModuleList") . ''; +//$linkback = '' . $langs->trans("BackToModuleList") . ''; print load_fiche_titre($langs->trans('ConfigAccountingExpert'), $linkback, 'title_setup'); -$head = admin_accounting_prepare_head($accounting); - print '
'; print ''; print ''; -dol_fiche_head($head, 'general', $langs->trans("Configuration"), -1, 'cron'); - - // Default mode for calculating turnover (parameter ACCOUNTING_MODE) - +/* print ''; print ''; @@ -200,7 +194,7 @@ print "
\n"; print '
'; - +*/ // Others params @@ -287,18 +281,11 @@ foreach ($list as $key) print ''; - - - -dol_fiche_end(); - print '
'; print '
'; print '
'; -print '
'.$langs->trans("AccountancySetupDoneFromAccountancyMenu", $langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy")).'
'; - print '
'; print '
'; diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php index a3912aebc89..620a7786310 100644 --- a/htdocs/accountancy/admin/journals_list.php +++ b/htdocs/accountancy/admin/journals_list.php @@ -58,7 +58,7 @@ $active = 1; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); -if ($page == -1 || $page == null) { $page = 0 ; } +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $listlimit * $page ; $pageprev = $page - 1; $pagenext = $page + 1; @@ -128,8 +128,8 @@ complete_dictionary_with_modules($taborder,$tabname,$tablib,$tabsql,$tabsqlsort, // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") $elementList = array(); - // Must match ids defined into eldy.lib.php - $sourceList = array( + // Must match ids defined into eldy.lib.php + $sourceList = array( '1' => $langs->trans('AccountingJournalType1'), '2' => $langs->trans('AccountingJournalType2'), '3' => $langs->trans('AccountingJournalType3'), @@ -144,216 +144,217 @@ $elementList = array(); if (GETPOST('button_removefilter') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter_x')) { - $search_country_id = ''; + $search_country_id = ''; } // Actions add or modify an entry into a dictionary if (GETPOST('actionadd') || GETPOST('actionmodify')) { - $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); - $listfieldinsert=explode(',',$tabfieldinsert[$id]); - $listfieldmodify=explode(',',$tabfieldinsert[$id]); - $listfieldvalue=explode(',',$tabfieldvalue[$id]); + $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); + $listfieldinsert=explode(',',$tabfieldinsert[$id]); + $listfieldmodify=explode(',',$tabfieldinsert[$id]); + $listfieldvalue=explode(',',$tabfieldvalue[$id]); - // Check that all fields are filled - $ok=1; - foreach ($listfield as $f => $value) - { + // Check that all fields are filled + $ok=1; + foreach ($listfield as $f => $value) + { if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; - if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; + if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; if ($fieldnamekey == 'nature') $fieldnamekey = 'Nature'; - } - // Other checks - if (isset($_POST["code"])) - { - if ($_POST["code"]=='0') - { - $ok=0; - setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); - } - /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base + } + // Other checks + if (isset($_POST["code"])) + { + if ($_POST["code"]=='0') + { + $ok=0; + setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); + } + /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base { $ok = 0; - $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; + $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ - } + } // Clean some parameters - if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null + if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]=''; // If empty, we force to null if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]=''; // If empty, we force to null - // Si verif ok et action add, on ajoute la ligne - if ($ok && GETPOST('actionadd')) - { - if ($tabrowid[$id]) - { - // Recupere id libre pour insertion - $newid=0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); + // Si verif ok et action add, on ajoute la ligne + if ($ok && GETPOST('actionadd')) + { + if ($tabrowid[$id]) + { + // Recupere id libre pour insertion + $newid=0; + $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + $newid=($obj->newid + 1); - } else { - dol_print_error($db); - } - } + } else { + dol_print_error($db); + } + } - // Add new entry - $sql = "INSERT INTO ".$tabname[$id]." ("; - // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $tabrowid[$id].","; - $sql.= $tabfieldinsert[$id]; - $sql.=",active)"; - $sql.= " VALUES("; + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $tabrowid[$id].","; + $sql.= $tabfieldinsert[$id]; + $sql.=",active)"; + $sql.= " VALUES("; - // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $newid.","; - $i=0; - foreach ($listfieldinsert as $f => $value) - { - if ($value == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql.=",1)"; + // List of values + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $newid.","; + $i=0; + foreach ($listfieldinsert as $f => $value) + { + if ($value == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.=",1)"; - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST=array('id'=>$id); // Clean $_POST array, we keep only - } - else - { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } - else { - dol_print_error($db); - } - } - } + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + $_POST=array('id'=>$id); // Clean $_POST array, we keep only + } + else + { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } + else { + dol_print_error($db); + } + } + } - // Si verif ok et action modify, on modifie la ligne - if ($ok && GETPOST('actionmodify')) - { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + // Si verif ok et action modify, on modifie la ligne + if ($ok && GETPOST('actionmodify')) + { + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) - { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; - } - $i = 0; - foreach ($listfieldmodify as $field) - { - if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { - $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); - } - else if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql.=","; - $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) + { + $sql.= $tabrowid[$id]."="; + $sql.= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { + $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); + } + else if ($field == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + $sql.= $field."="; + if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if (! $resql) - { - setEventMessages($db->error(), null, 'errors'); - } - } - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if (! $resql) + { + setEventMessages($db->error(), null, 'errors'); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if (GETPOST('actioncancel')) { - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; - dol_syslog("delete", LOG_DEBUG); - $result = $db->query($sql); - if (! $result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } - else - { - dol_print_error($db); - } - } + dol_syslog("delete", LOG_DEBUG); + $result = $db->query($sql); + if (! $result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } + else + { + dol_print_error($db); + } + } } // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } + /* * View */ @@ -367,8 +368,8 @@ $titre=$langs->trans("DictionarySetup"); $linkback=''; if ($id) { - $titre.=' - '.$langs->trans($tablib[$id]); - $titlepicto='title_accountancy'; + $titre.=' - '.$langs->trans($tablib[$id]); + $titlepicto='title_accountancy'; } print load_fiche_titre($titre,$linkback,$titlepicto); @@ -377,7 +378,7 @@ print load_fiche_titre($titre,$linkback,$titlepicto); // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); } //var_dump($elementList); @@ -386,313 +387,315 @@ if ($action == 'delete') */ if ($id) { - // Complete requete recherche valeurs avec critere de tri - $sql=$tabsql[$id]; + // Complete requete recherche valeurs avec critere de tri + $sql=$tabsql[$id]; - if ($search_country_id > 0) - { - if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; - else $sql.=" WHERE "; - $sql.= " c.rowid = ".$search_country_id; - } + if ($search_country_id > 0) + { + if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; + else $sql.=" WHERE "; + $sql.= " c.rowid = ".$search_country_id; + } - if ($sortfield) - { - // If sort order is "country", we use country_code instead - if ($sortfield == 'country') $sortfield='country_code'; - $sql.= " ORDER BY ".$sortfield; - if ($sortorder) - { - $sql.=" ".strtoupper($sortorder); - } - $sql.=", "; - // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value - $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]); - $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]); - } - else { - $sql.=" ORDER BY "; - } - $sql.=$tabsqlsort[$id]; - $sql.=$db->plimit($listlimit+1,$offset); - //print $sql; + if ($sortfield) + { + // If sort order is "country", we use country_code instead + if ($sortfield == 'country') $sortfield='country_code'; + $sql.= " ORDER BY ".$sortfield; + if ($sortorder) + { + $sql.=" ".strtoupper($sortorder); + } + $sql.=", "; + // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]); + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]); + } + else { + $sql.=" ORDER BY "; + } + $sql.=$tabsqlsort[$id]; + $sql.=$db->plimit($listlimit+1,$offset); + //print $sql; - $fieldlist=explode(',',$tabfield[$id]); + $fieldlist=explode(',',$tabfield[$id]); - print '
'; - print ''; - print ''; + print ''; + print ''; + print ''; - print ''; + print '
'; + print '
'; - // Form to add a new line - if ($tabname[$id]) - { - $alabelisused=0; - $var=false; + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused=0; + $var=false; - $fieldlist=explode(',',$tabfield[$id]); + $fieldlist=explode(',',$tabfield[$id]); - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - $align="left"; - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') - { - $valuetoshow=$langs->trans("Label"); - } - if ($fieldlist[$field]=='nature') { $valuetoshow=$langs->trans("Nature"); } + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + $align="left"; + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + { + $valuetoshow=$langs->trans("Label"); + } + if ($fieldlist[$field]=='nature') { $valuetoshow=$langs->trans("Nature"); } - if ($valuetoshow != '') - { - print ''; - } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; - } + if ($valuetoshow != '') + { + print ''; + } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; + } - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - // Line to enter new values - print ''; + // Line to enter new values + print ''; - $obj = new stdClass(); - // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val) != '') - $obj->$val=GETPOST($val); - } - } + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd')) + { + foreach ($fieldlist as $key=>$val) + { + if (GETPOST($val) != '') + $obj->$val=GETPOST($val); + } + } - $tmpaction = 'create'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $tmpaction = 'create'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - if (empty($reshook)) - { - fieldList($fieldlist,$obj,$tabname[$id],'add'); - } + if (empty($reshook)) + { + fieldListJournal($fieldlist,$obj,$tabname[$id],'add'); + } - print ''; - print ""; + print ''; + print ""; - print ''; // Keep   to have a line with enough height - } + print ''; // Keep   to have a line with enough height + } - // List of available record in database - dol_syslog("htdocs/admin/dict", LOG_DEBUG); - $resql=$db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - $var=true; + // List of available record in database + dol_syslog("htdocs/admin/dict", LOG_DEBUG); + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + $var=true; - $param = '&id='.$id; - if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; - $paramwithsearch = $param; - if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; - if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; - if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha'); + $param = '&id='.$id; + if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; + $paramwithsearch = $param; + if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; + if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; + if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha'); - // There is several pages - if ($num > $listlimit) - { - print ''; - } + // There is several pages + if ($num > $listlimit) + { + print ''; + } - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $showfield=1; // By defaut - $align="left"; - $sortable=1; - $valuetoshow=''; - /* + // Title line with search boxes + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $showfield=1; // By defaut + $align="left"; + $sortable=1; + $valuetoshow=''; + /* $tmparray=getLabelOfField($fieldlist[$field]); $showfield=$tmp['showfield']; $valuetoshow=$tmp['valuetoshow']; $align=$tmp['align']; $sortable=$tmp['sortable']; */ - $valuetoshow=ucfirst($fieldlist[$field]); // By defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } - if ($fieldlist[$field]=='nature') { $valuetoshow=$langs->trans("Nature"); } + $valuetoshow=ucfirst($fieldlist[$field]); // By defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } + if ($fieldlist[$field]=='nature') { $valuetoshow=$langs->trans("Nature"); } - // Affiche nom du champ - if ($showfield) - { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); - } - } + // Affiche nom du champ + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); + } + } print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; - // Title line with search boxes - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + if ($num) + { + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) + { + $tmpaction='edit'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - if ($num) - { - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); - //print_r($obj); - print ''; - if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) - { - $tmpaction='edit'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + // Show fields + if (empty($reshook)) fieldListJournal($fieldlist,$obj,$tabname[$id],'edit'); - // Show fields - if (empty($reshook)) fieldList($fieldlist,$obj,$tabname[$id],'edit'); + print ''; + } + else + { + $tmpaction = 'view'; + $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - print ''; - } - else - { - $tmpaction = 'view'; - $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - $error=$hookmanager->error; $errors=$hookmanager->errors; + if (empty($reshook)) + { + foreach ($fieldlist as $field => $value) + { - if (empty($reshook)) - { - foreach ($fieldlist as $field => $value) - { + $showfield=1; + $align="left"; + $valuetoshow=$obj->{$fieldlist[$field]}; + if ($valuetoshow=='all') { + $valuetoshow=$langs->trans('All'); + } + else if ($fieldlist[$field]=='nature' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') { + $langs->load("accountancy"); + $key=$langs->trans("AccountingJournalType".strtoupper($obj->nature)); + $valuetoshow=($obj->nature && $key != "AccountingJournalType".strtoupper($obj->nature)?$key:$obj->{$fieldlist[$field]}); + } - $showfield=1; - $align="left"; - $valuetoshow=$obj->{$fieldlist[$field]}; - if ($valuetoshow=='all') { - $valuetoshow=$langs->trans('All'); - } - else if ($fieldlist[$field]=='nature' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') { - $langs->load("accountancy"); - $key=$langs->trans("AccountingJournalType".strtoupper($obj->nature)); - $valuetoshow=($obj->nature && $key != "AccountingJournalType".strtoupper($obj->nature)?$key:$obj->{$fieldlist[$field]}); - } - - $class='tddict'; + $class='tddict'; // Show value for field if ($showfield) print ''; - } - } + } + } - // Can an entry be erased or disabled ? - $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default - if (isset($obj->code) && $id != 10) - { - if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } - } + // Can an entry be erased or disabled ? + $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default + if (isset($obj->code) && $id != 10) + { + if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } + } - $canbemodified=$iserasable; + $canbemodified=$iserasable; - $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); - if ($param) $url .= '&'.$param; - $url.='&'; + $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); + if ($param) $url .= '&'.$param; + $url.='&'; - // Active - print '"; + // Active + print '"; - // Modify link - if ($canbemodified) print ''; - else print ''; + // Modify link + if ($canbemodified) print ''; + else print ''; - // Delete link - if ($iserasable) - { - print ''; - } - else print ''; + // Delete link + if ($iserasable) + { + print ''; + } + else print ''; - print ''; + print ''; - print ''; - } + print ''; + } - print "\n"; - $i++; - } - } - } - else { - dol_print_error($db); - } + print "\n"; + $i++; + } + } + } + else { + dol_print_error($db); + } - print '
'; - if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; - else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); - else print $valuetoshow; - print ''; + if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; + else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); + else print $valuetoshow; + print ''; - print ''; - print '
'; + print ''; + print '
'; - print ''; - print '
'; + print ''; + print '
 
 
'; - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); - print '
'; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + if ($filterfound) + { + $searchpicto=$form->showFilterAndCheckAddButtons(0); + print $searchpicto; + } + print '
'; - if ($filterfound) - { - $searchpicto=$form->showFilterAndCheckAddButtons(0); - print $searchpicto; - } - print '
'; + print ''; + print ''; + print ''; + print ''; + print '
'; + print '
'; - print ''; - print ''; - print ''; - print ''; - print '
'; - print '
'.$valuetoshow.''; - if ($canbedisabled) print ''.$actl[$obj->active].''; - else - { - if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); - else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); - else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); - else print $langs->trans("AlwaysActive"); - } - print "'; + if ($canbedisabled) print ''.$actl[$obj->active].''; + else + { + if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); + else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); + else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); + else print $langs->trans("AlwaysActive"); + } + print "'.img_edit().' '.img_edit().' '; - if ($user->admin) print ''.img_delete().''; - //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin - print ' '; + if ($user->admin) print ''.img_delete().''; + //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin + print ' 
'; + print ''; + print ''; - print '
'; + print ''; } print '
'; @@ -711,7 +714,7 @@ $db->close(); * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered * @return void */ -function fieldList($fieldlist, $obj='', $tabname='', $context='') +function fieldListJournal($fieldlist, $obj='', $tabname='', $context='') { global $conf,$langs,$db; global $form, $mysoc; diff --git a/htdocs/accountancy/admin/productaccount.php b/htdocs/accountancy/admin/productaccount.php index 85784ec16d7..bebca87404c 100644 --- a/htdocs/accountancy/admin/productaccount.php +++ b/htdocs/accountancy/admin/productaccount.php @@ -90,8 +90,8 @@ $arrayfields=array(); * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -312,6 +312,7 @@ if ($result) $texte=$langs->trans("ListOfProductsServices"); print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit); + print '
'; print ''; print ''; @@ -448,6 +449,7 @@ if ($result) $i ++; } print '
'; + print '
'; // Example : Adding jquery code print ''; @@ -816,6 +820,7 @@ if (empty($action) || $action == 'view') { print '
'; $i = 0; + print '
'; print ""; print ""; print ""; @@ -823,7 +828,7 @@ if (empty($action) || $action == 'view') { print ""; print ""; print ""; - print ""; + print ""; print ""; print ""; print ""; @@ -977,6 +982,7 @@ if (empty($action) || $action == 'view') { } print "
" . $langs->trans("Piece") . ' (' . $langs->trans("ObjectsRef") . ")" . $langs->trans("AccountAccounting") . "" . $langs->trans("SubledgerAccount") . "" . $langs->trans("Label") . "" . $langs->trans("LabelOperation") . "" . $langs->trans("PaymentMode") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
"; + print '
'; llxFooter(); } diff --git a/htdocs/accountancy/journal/expensereportsjournal.php b/htdocs/accountancy/journal/expensereportsjournal.php index 3862bc4ec63..c73286a8bdd 100644 --- a/htdocs/accountancy/journal/expensereportsjournal.php +++ b/htdocs/accountancy/journal/expensereportsjournal.php @@ -1,11 +1,11 @@ - * Copyright (C) 2007-2010 Jean Heimburger - * Copyright (C) 2011 Juanjo Menent - * Copyright (C) 2012 Regis Houssin - * Copyright (C) 2013-2017 Alexandre Spangaro - * Copyright (C) 2013-2016 Olivier Geffroy - * Copyright (C) 2013-2016 Florian Henry +/* Copyright (C) 2007-2010 Laurent Destailleur + * Copyright (C) 2007-2010 Jean Heimburger + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2013-2017 Alexandre Spangaro + * Copyright (C) 2013-2016 Olivier Geffroy + * Copyright (C) 2013-2016 Florian Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -298,7 +298,7 @@ if ($action == 'writebookkeeping') { $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; - $bookkeeping->label_operation = $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]); + $bookkeeping->label_operation = $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'; $bookkeeping->montant = $mt; $bookkeeping->sens = ($mt < 0) ? 'C' : 'D'; $bookkeeping->debit = ($mt > 0) ? $mt : 0; @@ -498,7 +498,7 @@ if (empty($action) || $action == 'view') { $nomlink = ''; $periodlink = ''; $exportlink = ''; - $builddate = time(); + $builddate=dol_now(); $description.= $langs->trans("DescJournalOnlyBindedVisible").'
'; $listofchoices=array('already'=>$langs->trans("AlreadyInGeneralLedger"), 'notyet'=>$langs->trans("NotYetInGeneralLedger")); @@ -510,19 +510,20 @@ if (empty($action) || $action == 'view') { // Button to write into Ledger if (empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) || $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT == '-1') { - print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone"); - print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, ''.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").''); + print '
'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone"); + print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, ''.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").''); } print '
'; if (empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) || $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT == '-1') { print ''; } else { - print ''; + print ''; } - //print ''; + //print ''; print '
'; + // TODO Avoid using js. We can use a direct link with $param print ' '; @@ -560,6 +565,7 @@ if (empty($action) || $action == 'view') { print '
'; $i = 0; + print '
'; print ""; print ""; print ""; @@ -567,7 +573,7 @@ if (empty($action) || $action == 'view') { print ""; print ""; print ""; - print ""; + print ""; print ""; print ""; print "\n"; @@ -619,8 +625,9 @@ if (empty($action) || $action == 'view') { print ""; print '"; print '"; - print ""; + print ""; } + // Product / Service foreach ( $tabht[$key] as $k => $mt ) { $accountingaccount = new AccountingAccount($db); @@ -677,7 +684,7 @@ if (empty($action) || $action == 'view') { // Subledger account print "'; - print ""; print '"; print '"; @@ -688,6 +695,7 @@ if (empty($action) || $action == 'view') { } print "
" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("AccountAccounting") . "" . $langs->trans("SubledgerAccount") . "" . $langs->trans("Label") . "" . $langs->trans("LabelOperation") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("SubledgerAccount") . "' . ($mt < 0 ? - price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
"; print '" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).($numtax?' - Localtax '.$numtax:''); + print "" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'.($numtax?' - Localtax '.$numtax:''); print "' . ($mt >= 0 ? price($mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "
"; + print '
'; // End of page llxFooter(); diff --git a/htdocs/accountancy/journal/sellsjournal.php b/htdocs/accountancy/journal/sellsjournal.php index 2d5d65607e2..42fbb7ff681 100644 --- a/htdocs/accountancy/journal/sellsjournal.php +++ b/htdocs/accountancy/journal/sellsjournal.php @@ -89,7 +89,7 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end $idpays = $mysoc->country_id; -$sql = "SELECT f.rowid, f.facnumber, f.type, f.datef as df, f.ref_client,"; +$sql = "SELECT f.rowid, f.facnumber, f.type, f.datef as df, f.ref_client, f.date_lim_reglement as dlr,"; $sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.total_ttc, fd.situation_percent, fd.vat_src_code,"; $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,"; $sql .= " p.rowid as pid, p.ref as pref, p.accountancy_code_sell, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte"; @@ -156,7 +156,7 @@ if ($result) { $compta_localtax2 = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva); // Define array to display all VAT rates that use this accounting account $compta_tva - if (price2num($obj->tva_tx) || ! empty($obj->vat_src_code)) + if (price2num($obj->tva_tx) || ! empty($obj->vat_src_code)) { $def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':'')]=(vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':'')); } @@ -178,6 +178,7 @@ if ($result) { // Invoice lines $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df); + $tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr); $tabfac[$obj->rowid]["ref"] = $obj->facnumber; $tabfac[$obj->rowid]["type"] = $obj->type; $tabfac[$obj->rowid]["description"] = $obj->label_compte; @@ -240,6 +241,7 @@ if ($action == 'writebookkeeping') { if ($mt) { $bookkeeping = new BookKeeping($db); $bookkeeping->doc_date = $val["date"]; + $bookkeeping->date_lim_reglement = $val["datereg"]; $bookkeeping->doc_ref = $val["ref"]; $bookkeeping->date_create = $now; $bookkeeping->doc_type = 'customer_invoice'; @@ -287,12 +289,13 @@ if ($action == 'writebookkeeping') { if ($accountingaccount->fetch(null, $k, true)) { $bookkeeping = new BookKeeping($db); $bookkeeping->doc_date = $val["date"]; + $bookkeeping->date_lim_reglement = $val["datereg"]; $bookkeeping->doc_ref = $val["ref"]; $bookkeeping->date_create = $now; $bookkeeping->doc_type = 'customer_invoice'; $bookkeeping->fk_doc = $key; $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add - $bookkeeping->thirdparty_code = $companystatic->code_client; + $bookkeeping->thirdparty_code = $companystatic->code_client; $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; @@ -340,6 +343,7 @@ if ($action == 'writebookkeeping') { if ($mt) { $bookkeeping = new BookKeeping($db); $bookkeeping->doc_date = $val["date"]; + $bookkeeping->date_lim_reglement = $val["datereg"]; $bookkeeping->doc_ref = $val["ref"]; $bookkeeping->date_create = $now; $bookkeeping->doc_type = 'customer_invoice'; @@ -349,7 +353,7 @@ if ($action == 'writebookkeeping') { $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; - $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.join(', ',$def_tva[$key][$k]) . ($numtax?' - Localtax '.$numtax:''); + $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:''); $bookkeeping->montant = $mt; $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; $bookkeeping->debit = ($mt < 0) ? -$mt : 0; @@ -388,8 +392,8 @@ if ($action == 'writebookkeeping') { if ($error >= 10) { - setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors'); - break; // Break in the foreach + setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors'); + break; // Break in the foreach } } @@ -437,7 +441,6 @@ $form = new Form($db); if ($action == 'exportcsv') { $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; - $sell_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; @@ -468,7 +471,7 @@ if ($action == 'exportcsv') { print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers") . '"' . $sep; print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; - print '"' . $sell_journal . '"'; + print '"' . $journal . '"'; print "\n"; } @@ -483,12 +486,12 @@ if ($action == 'exportcsv') { print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; - print " " . $sep; + print '""' . $sep; print '"' . utf8_decode(dol_trunc($accountingaccount->label, 32)) . '"' . $sep; print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep; print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; - print '"' . $sell_journal . '"'; + print '"' . $journal . '"'; print "\n"; } } @@ -508,12 +511,12 @@ if ($action == 'exportcsv') { print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; - print " " . $sep; - print '"' . $langs->trans("VAT") . ' - ' . $def_tva[$key] . '"' . $sep; - print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . join(', ',$def_tva[$key][$k]) . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep; + print '""' . $sep; + print '"' . $langs->trans("VAT") . ' - ' . $def_tva[$key] . ' %"' . $sep; + print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep; print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; - print '"' . $sell_journal . '"'; + print '"' . $journal . '"'; print "\n"; } } @@ -531,7 +534,7 @@ if (empty($action) || $action == 'view') { $nomlink = ''; $periodlink = ''; $exportlink = ''; - $builddate = time(); + $builddate=dol_now(); $description.= $langs->trans("DescJournalOnlyBindedVisible").'
'; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description .= $langs->trans("DepositsAreNotIncluded"); @@ -547,30 +550,31 @@ if (empty($action) || $action == 'view') { // Button to write into Ledger if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') { - print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone"); - print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, ''.$langs->transnoentitiesnoconv("MenuFinancial").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").''); + print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone"); + print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, ''.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").''); } print '
'; if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') { - print ''; + print ''; } else { - print ''; + print ''; } - print ''; + print ''; print '
'; + // TODO Avoid using js. We can use a direct link with $param print ' '; @@ -580,6 +584,7 @@ if (empty($action) || $action == 'view') { print '
'; $i = 0; + print '
'; print ""; print ""; print ""; @@ -587,7 +592,7 @@ if (empty($action) || $action == 'view') { print ""; print ""; print ""; - print ""; + print ""; print ""; print ""; print "\n"; @@ -693,7 +698,7 @@ if (empty($action) || $action == 'view') { // Subledger account print "'; - print ""; print '"; print '"; @@ -704,6 +709,7 @@ if (empty($action) || $action == 'view') { } print "
" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("AccountAccounting") . "" . $langs->trans("SubledgerAccount") . "" . $langs->trans("Label") . "" . $langs->trans("LabelOperation") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
"; print '" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).($numtax?' - Localtax '.$numtax:''); + print "" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'.($numtax?' - Localtax '.$numtax:''); print "' . ($mt < 0 ? price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
"; + print '
'; // End of page llxFooter(); diff --git a/htdocs/accountancy/report/result.php b/htdocs/accountancy/report/result.php deleted file mode 100644 index fad1fcd4b9b..00000000000 --- a/htdocs/accountancy/report/result.php +++ /dev/null @@ -1,302 +0,0 @@ - - * Copyright (C) 2016 Alexandre Spangaro - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/accountancy/report/result.php - * \ingroup Advanced accountancy - * \brief Page for accounting result - */ -require '../../main.inc.php'; - -// Class -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/report.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountancycategory.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; - -$error = 0; - -// Langs -$langs->load("accountancy"); -$langs->load("compta"); - -$mesg = ''; -$action = GETPOST('action','aZ09'); -$cat_id = GETPOST('account_category'); -$selectcpt = GETPOST('cpt_bk'); -$id = GETPOST('id', 'int'); -$rowid = GETPOST('rowid', 'int'); -$cancel = GETPOST('cancel'); -$simple_report = GETPOST('simple_report'); - - -// Filter -$year = GETPOST('year','int'); -if ($year == 0) { - $year_current = strftime("%Y", time()); - $year_start = $year_current; -} else { - $year_current = $year; - $year_start = $year; -} - -if($cat_id == 0){ - $cat_id = null; -} - -// Security check -if ($user->societe_id > 0) - accessforbidden(); -if (! $user->rights->accounting->comptarapport->lire) - accessforbidden(); - -$AccCat = new AccountancyCategory($db); - - -/* - * View - */ - -llxheader('', $langs->trans('ReportInOut')); - -$formaccounting = new FormAccounting($db); -$form = new Form($db); - -$textprevyear = '' . img_previous() . ''; -$textnextyear = ' ' . img_next() . ''; - -$nom = $langs->trans("ReportInOut").', '.$langs->trans("ByAccounts"); -$nomlink = ''; -$periodlink = ''; -$exportlink = ''; -$builddate = time(); -$description = ''; -$period = $langs->trans("Detail").' '. $form->selectyesno('simple_report',$simple_report,0) . " " .$textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear ; -report_header($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => '')); - -$moreforfilter=''; - -print '
'; -print ''."\n"; - -$months = array( $langs->trans("JanuaryMin"), - $langs->trans("FebruaryMin"), - $langs->trans("MarchMin"), - $langs->trans("AprilMin"), - $langs->trans("MayMin"), - $langs->trans("JuneMin"), - $langs->trans("JulyMin"), - $langs->trans("AugustMin"), - $langs->trans("SeptemberMin"), - $langs->trans("OctoberMin"), - $langs->trans("NovemberMin"), - $langs->trans("DecemberMin"), - ); - -print ''; -print ''; -print ''; -print ''; -print ''; -foreach($months as $k => $v){ - print ''; -} -print ''; - - - -//All categories -$cats = $AccCat->getCats(); -if ($catsCalcule < 0) dol_print_error($db, $AccCat->error, $AccCat->errors); - -$j=1; -$sommes = array(); - -foreach($cats as $cat ){ - if(!empty($cat['category_type'])){ // category calculed - - $formula = $cat['formula']; - - print ""; - print ''; - - $vars = array(); - - // Previous Fiscal year (N-1) - foreach($sommes as $code => $det){ - $vars[$code] = $det['NP']; - } - - - $result = strtr($formula, $vars); - - - $r = $AccCat->calculate($result); - - print ''; - $code = $cat['code']; // code categorie de calcule - $sommes[$code]['NP'] += $r; - - // Current fiscal year (N) - if (is_array($sommes) && ! empty($sommes)){ - foreach($sommes as $code => $det){ - $vars[$code] = $det['N']; - } - } - - $result = strtr($formula, $vars); - - $r = $AccCat->calculate($result); - - print ''; - $sommes[$code]['N'] += $r; - - // Detail by month - foreach($months as $k => $v){ - foreach($sommes as $code => $det){ - $vars[$code] = $det['M'][$k]; - } - $result = strtr($formula, $vars); - $r = $AccCat->calculate($result); - print ''; - $sommes[$code]['M'][$k] += $r; - } - - - print "\n"; - - - }else{ // normal category - - $totCat = array(); - $totCat['M'] = array(); - - // get cpts of category - $cpts = $AccCat->getCptsCat($cat['rowid']); - - - print ""; - print ''; - - foreach($cpts as $i => $cpt){ - $var = ! $var; - - $code = $cat['code']; - - // N-1 - $return = $AccCat->getResult($cpt['account_number'], 0, $year_current -1, $cpt['dc']); - - if ($return < 0) { - setEventMessages(null, $AccCat->errors, 'errors'); - $resultNP=0; - } else { - $resultNP=$AccCat->sdc; - } - - //N - $return = $AccCat->getResult($cpt['account_number'], 0, $year_current, $cpt['dc']); - if ($return < 0) { - setEventMessages(null, $AccCat->errors, 'errors'); - $resultN=0; - } else { - $resultN=$AccCat->sdc; - } - - $totCat['NP'] += $resultNP; - $totCat['N'] += $resultN; - - foreach($months as $k => $v){ - $return = $AccCat->getResult($cpt['account_number'], $k+1, $year_current, $cpt['dc']); - if ($return < 0) { - setEventMessages(null, $AccCat->errors, 'errors'); - $resultM=0; - } else { - $resultM=$AccCat->sdc; - } - $totCat['M'][$k] += $resultM; - - } - } - - print ''; - print ''; - - foreach($totCat['M'] as $k => $v){ - print ''; - } - print "\n"; - - foreach($cpts as $i => $cpt){ - $var = ! $var; - - $code = $cat['code']; - - // N-1 - $return = $AccCat->getResult($cpt['account_number'], 0, $year_current -1, $cpt['dc']); - - if ($return < 0) { - setEventMessages(null, $AccCat->errors, 'errors'); - $resultNP=0; - } else { - $resultNP=$AccCat->sdc; - } - - //N - $return = $AccCat->getResult($cpt['account_number'], 0, $year_current, $cpt['dc']); - if ($return < 0) { - setEventMessages(null, $AccCat->errors, 'errors'); - $resultN=0; - } else { - $resultN=$AccCat->sdc; - } - - $sommes[$code]['NP'] += $resultNP; - $sommes[$code]['N'] += $resultN; - print ''; - if ($simple_report == 'yes') { - print ''; - print ''; - print ''; - print ''; - } - - foreach($months as $k => $v){ - $return = $AccCat->getResult($cpt['account_number'], $k+1, $year_current, $cpt['dc']); - if ($return < 0) { - setEventMessages(null, $AccCat->errors, 'errors'); - $resultM=0; - } else { - $resultM=$AccCat->sdc; - } - $sommes[$code]['M'][$k] += $resultM; - if ($simple_report == 'yes') { - print ''; - } - } - - print "\n"; - } - } - -} - -print "
'.$langs->trans("Account").''.$langs->trans("Description").'N-1'.$langs->trans("NReal").''.$langs->trans($v).'
' . $cat['label'] . '' . price($r) . '' . price($r) . '' . price($r) . '
' . $cat['label'] . '' . price($totCat['NP']) . '' . price($totCat['N']) . '' . price($v) . '
' . length_accountg($cpt['account_number']) . '' . $cpt['name_cpt'] . '' . price($resultNP) . '' . price($resultN) . '' . price($resultM) . '
"; -print '
'; - -llxFooter(); -$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/supplier/card.php b/htdocs/accountancy/supplier/card.php index b73c40ced74..d36ae5e2543 100644 --- a/htdocs/accountancy/supplier/card.php +++ b/htdocs/accountancy/supplier/card.php @@ -22,9 +22,9 @@ * */ /** - * \file htdocs/accountancy/supplier/card.php - * \ingroup Accountancy - * \brief Card supplier ventilation + * \file htdocs/accountancy/supplier/card.php + * \ingroup Advanced accountancy + * \brief Card supplier ventilation */ require '../../main.inc.php'; @@ -44,7 +44,7 @@ $id = GETPOST('id'); if ($user->societe_id > 0) accessforbidden(); - + /* * Actions */ @@ -97,14 +97,14 @@ if (! empty($id)) { $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture_fourn as f ON f.rowid = l.fk_facture_fourn "; $sql .= " WHERE f.fk_statut > 0 AND l.rowid = " . $id; $sql .= " AND f.entity IN (" . getEntity('facture_fourn', 0) . ")"; // We don't share object for accountancy - + dol_syslog("/accounting/supplier/card.php sql=" . $sql, LOG_DEBUG); $result = $db->query($sql); - + if ($result) { $num_lines = $db->num_rows($result); $i = 0; - + if ($num_lines) { $objp = $db->fetch_object($result); diff --git a/htdocs/accountancy/supplier/index.php b/htdocs/accountancy/supplier/index.php index 3dac6a23567..74f071836aa 100644 --- a/htdocs/accountancy/supplier/index.php +++ b/htdocs/accountancy/supplier/index.php @@ -105,29 +105,6 @@ if ($action == 'validatehistory') { $db->commit(); setEventMessages($langs->trans('AutomaticBindingDone'), null, 'mesgs'); } -} elseif ($action == 'fixaccountancycode') { - $error = 0; - $db->begin(); - - $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det as fd"; - $sql1 .= " SET fk_code_ventilation = 0"; - $sql1 .= ' WHERE fd.fk_code_ventilation NOT IN '; - $sql1 .= ' (SELECT accnt.rowid '; - $sql1 .= ' FROM ' . MAIN_DB_PREFIX . 'accounting_account as accnt'; - $sql1 .= ' INNER JOIN ' . MAIN_DB_PREFIX . 'accounting_system as syst'; - $sql1 .= ' ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=' . $conf->global->CHARTOFACCOUNTS . ')'; - - dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG); - - $resql1 = $db->query($sql1); - if (! $resql1) { - $error ++; - $db->rollback(); - setEventMessage($db->lasterror(), 'errors'); - } else { - $db->commit(); - setEventMessage($langs->trans('Done'), 'mesgs'); - } } elseif ($action == 'cleanaccountancycode') { $error = 0; $db->begin(); @@ -140,7 +117,7 @@ if ($action == 'validatehistory') { $sql1.= " AND f.entity IN (" . getEntity('accountancy') . ")"; $sql1.= ")"; - dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG); + dol_syslog("htdocs/accountancy/customer/index.php cleanaccountancycode", LOG_DEBUG); $resql1 = $db->query($sql1); if (! $resql1) { @@ -168,10 +145,25 @@ print $langs->trans("DescVentilSupplier") . '
'; print $langs->trans("DescVentilMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToBind")) . '
'; print '
'; -//print '
'; -// TODO Remove this. Should be done always or into the repair.php script. -if ($conf->global->MAIN_FEATURES_LEVEL > 1) print '' . $langs->trans("CleanFixHistory", $year_current) . ''; -//print '
'; +// Clean database +$db->begin(); +$sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det as fd"; +$sql1 .= " SET fk_code_ventilation = 0"; +$sql1 .= ' WHERE fd.fk_code_ventilation NOT IN '; +$sql1 .= ' (SELECT accnt.rowid '; +$sql1 .= ' FROM ' . MAIN_DB_PREFIX . 'accounting_account as accnt'; +$sql1 .= ' INNER JOIN ' . MAIN_DB_PREFIX . 'accounting_system as syst'; +$sql1 .= ' ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=' . $conf->global->CHARTOFACCOUNTS . ')'; +dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG); +$resql1 = $db->query($sql1); +if (! $resql1) { + $error ++; + $db->rollback(); + setEventMessage($db->lasterror(), 'errors'); +} else { + $db->commit(); +} +// End clean database $y = $year_current; @@ -182,6 +174,7 @@ $buttonreset = ''; print ''; print ''; print ''; @@ -239,8 +232,7 @@ if ($resql) { print $db->lasterror(); // Show last sql error } print "
' . $langs->trans("Account") . '' . $langs->trans("Label") . '
\n"; - - +print ''; print '
'; @@ -248,6 +240,7 @@ print '
'; print_fiche_titre($langs->trans("OverviewOfAmountOfLinesBound"), $buttonreset, ''); +print '
'; print ''; print ''; print ''; @@ -305,7 +298,7 @@ if ($resql) { print $db->lasterror(); // Show last sql error } print "
' . $langs->trans("Account") . '' . $langs->trans("Label") . '
\n"; - +print '
'; @@ -317,6 +310,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. print_fiche_titre($langs->trans("OtherInfo"), '', ''); print "
\n"; + print '
'; print ''; print ''; for($i = 1; $i <= 12; $i ++) { @@ -357,6 +351,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. print $db->lasterror(); // Show last sql error } print "
' . $langs->trans("Total") . '
\n"; + print '
'; } diff --git a/htdocs/accountancy/supplier/lines.php b/htdocs/accountancy/supplier/lines.php index 66e6928da07..78b9320fdb1 100644 --- a/htdocs/accountancy/supplier/lines.php +++ b/htdocs/accountancy/supplier/lines.php @@ -32,6 +32,8 @@ require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; // Langs $langs->load("compta"); @@ -52,6 +54,9 @@ $search_desc = GETPOST('search_desc', 'alpha'); $search_amount = GETPOST('search_amount', 'alpha'); $search_account = GETPOST('search_account', 'alpha'); $search_vat = GETPOST('search_vat', 'alpha'); +$search_day=GETPOST("search_day","int"); +$search_month=GETPOST("search_month","int"); +$search_year=GETPOST("search_year","int"); $search_country = GETPOST('search_country', 'alpha'); $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); @@ -96,6 +101,9 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_amount = ''; $search_account = ''; $search_vat = ''; + $search_day = ''; + $search_month = ''; + $search_year = ''; $search_country = ''; $search_tvaintra = ''; } @@ -131,6 +139,9 @@ if (is_array($changeaccount) && count($changeaccount) > 0) { * View */ +$form = new Form($db); +$formother = new FormOther($db); + llxHeader('', $langs->trans("SuppliersVentilation") . ' - ' . $langs->trans("Dispatched")); print ' + + global->MAIN_USE_METEO_WITH_PERCENTAGE)) { + + print '
'; + print '
'; + print img_weather($text,'weather-clear.png',$options); + print '= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL0.' %'; + print '
'; + print img_weather($text,'weather-few-clouds.png',$options); + print '<= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL1.' %'; + print '
'; + print img_weather($text,'weather-clouds.png',$options); + print '<= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL2.' %'; + print '
'; + print img_weather($text,'weather-many-clouds.png',$options); + print '<= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL3.' %'; + print '
'; + print img_weather($text,'weather-storm.png',$options); + print '> '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL3.' %'; + print '
'; + print '
'; + + } else { + + print '
'; + print '
'; + print img_weather($text,'weather-clear.png',$options); + print '= '.$level0; + print '
'; + print img_weather($text,'weather-few-clouds.png',$options); + print '<= '.$level1; + print '
'; + print img_weather($text,'weather-clouds.png',$options); + print '<= '.$level2; + print '
'; + print img_weather($text,'weather-many-clouds.png',$options); + print '<= '.$level3; + print '
'; + print img_weather($text,'weather-storm.png',$options); + print '> '.$level3; + print '
'; + print '
'; + + } +} + +print ''; + +if($action == 'edit') { + + print '
'; + print '
'; + +} else { + + // Boutons d'action + print '
'; + +} + llxFooter(); $db->close(); diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index ce87f507cc6..fb9a101d474 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -1,16 +1,16 @@ - * Copyright (C) 2004-2015 Laurent Destailleur - * Copyright (C) 2004 Benoit Mortier - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2010-2016 Juanjo Menent - * Copyright (C) 2011-2015 Philippe Grand - * Copyright (C) 2011 Remy Younes - * Copyright (C) 2012-2015 Marcos García - * Copyright (C) 2012 Christophe Battarel - * Copyright (C) 2011-2016 Alexandre Spangaro - * Copyright (C) 2015 Ferran Marcet - * Copyright (C) 2016 Raphaël Doursenaud +/* Copyright (C) 2004 Rodolphe Quiedeville + * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004 Benoit Mortier + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2010-2016 Juanjo Menent + * Copyright (C) 2011-2015 Philippe Grand + * Copyright (C) 2011 Remy Younes + * Copyright (C) 2012-2015 Marcos García + * Copyright (C) 2012 Christophe Battarel + * Copyright (C) 2011-2016 Alexandre Spangaro + * Copyright (C) 2015 Ferran Marcet + * Copyright (C) 2016 Raphaël Doursenaud * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -54,6 +54,7 @@ $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; $confirm=GETPOST('confirm','alpha'); $id=GETPOST('id','int'); $rowid=GETPOST('rowid','alpha'); +$entity=GETPOST('entity','int'); $code=GETPOST('code','alpha'); $allowed=$user->admin; @@ -73,7 +74,7 @@ $active = 1; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); -if ($page == -1 || $page == null) { $page = 0 ; } +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $listlimit * $page ; $pageprev = $page - 1; $pagenext = $page + 1; @@ -88,7 +89,7 @@ $hookmanager->initHooks(array('admin')); // Put here declaration of dictionaries properties // Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this. -$taborder=array(9,0,4,3,2,0,1,8,19,16,27,0,5,11,0,33,34,0,6,0,29,0,7,17,24,28,0,10,23,12,13,0,14,0,22,20,18,21,0,15,30,0,26,0); +$taborder=array(9,0,4,3,2,0,1,8,19,16,27,0,5,11,0,33,34,0,6,0,29,0,7,17,35,36,24,28,0,10,23,12,13,0,14,0,22,20,18,21,0,15,30,0,26,0,); // Name of SQL tables of dictionaries $tabname=array(); @@ -126,6 +127,8 @@ $tabname[30]= MAIN_DB_PREFIX."c_format_cards"; //$tabname[32]= MAIN_DB_PREFIX."c_accounting_category"; $tabname[33]= MAIN_DB_PREFIX."c_hrm_department"; $tabname[34]= MAIN_DB_PREFIX."c_hrm_function"; +$tabname[35]= MAIN_DB_PREFIX."c_exp_tax_cat"; +$tabname[36]= MAIN_DB_PREFIX."c_exp_tax_range"; // Dictionary labels $tablib=array(); @@ -163,6 +166,8 @@ $tablib[30]= "DictionaryFormatCards"; //$tablib[32]= "DictionaryAccountancyCategory"; $tablib[33]= "DictionaryDepartment"; $tablib[34]= "DictionaryFunction"; +$tablib[35]= "DictionaryExpenseTaxCat"; +$tablib[36]= "DictionaryExpenseTaxRange"; // Requests to extract data $tabsql=array(); @@ -177,8 +182,8 @@ $tabsql[8] = "SELECT t.id as rowid, t.code as code, t.libelle, t.fk_country as $tabsql[9] = "SELECT c.code_iso as code, c.label, c.unicode, c.active FROM ".MAIN_DB_PREFIX."c_currencies AS c"; $tabsql[10]= "SELECT t.rowid, t.code, t.taux, t.localtax1_type, t.localtax1, t.localtax2_type, t.localtax2, c.label as country, c.code as country_code, t.fk_pays as country_id, t.recuperableonly, t.note, t.active, t.accountancy_code_sell, t.accountancy_code_buy FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c WHERE t.fk_pays=c.rowid"; $tabsql[11]= "SELECT t.rowid as rowid, t.element, t.source, t.code, t.libelle, t.position, t.active FROM ".MAIN_DB_PREFIX."c_type_contact AS t"; -$tabsql[12]= "SELECT c.rowid as rowid, c.code, c.libelle, c.libelle_facture, c.nbjour, c.type_cdr, c.decalage, c.active, c.sortorder FROM ".MAIN_DB_PREFIX.'c_payment_term AS c'; -$tabsql[13]= "SELECT c.id as rowid, c.code, c.libelle, c.type, c.active, c.accountancy_code FROM ".MAIN_DB_PREFIX."c_paiement AS c"; +$tabsql[12]= "SELECT c.rowid as rowid, c.code, c.libelle, c.libelle_facture, c.nbjour, c.type_cdr, c.decalage, c.active, c.sortorder, c.entity FROM ".MAIN_DB_PREFIX."c_payment_term AS c WHERE c.entity = " . getEntity($tabname[12]); +$tabsql[13]= "SELECT c.id as rowid, c.code, c.libelle, c.type, c.active, c.accountancy_code, c.entity FROM ".MAIN_DB_PREFIX."c_paiement AS c WHERE c.entity = " . getEntity($tabname[13]); $tabsql[14]= "SELECT e.rowid as rowid, e.code as code, e.libelle, e.price, e.organization, e.fk_pays as country_id, c.code as country_code, c.label as country, e.active FROM ".MAIN_DB_PREFIX."c_ecotaxe AS e, ".MAIN_DB_PREFIX."c_country as c WHERE e.fk_pays=c.rowid and c.active=1"; $tabsql[15]= "SELECT rowid as rowid, code, label as libelle, width, height, unit, active FROM ".MAIN_DB_PREFIX."c_paper_format"; $tabsql[16]= "SELECT code, label as libelle, sortorder, active FROM ".MAIN_DB_PREFIX."c_prospectlevel"; @@ -200,6 +205,8 @@ $tabsql[30]= "SELECT rowid, code, name, paper_size, orientation, metric, leftmar //$tabsql[32]= "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.sens, a.category_type, a.formula, a.position as position, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid and c.active=1"; $tabsql[33]= "SELECT rowid, pos, code, label, active FROM ".MAIN_DB_PREFIX."c_hrm_department"; $tabsql[34]= "SELECT rowid, pos, code, label, c_level, active FROM ".MAIN_DB_PREFIX."c_hrm_function"; +$tabsql[35]= "SELECT c.rowid, c.label, c.active, c.entity FROM ".MAIN_DB_PREFIX."c_exp_tax_cat c"; +$tabsql[36]= "SELECT r.rowid, r.fk_c_exp_tax_cat, r.range_ik, r.active, r.entity FROM ".MAIN_DB_PREFIX."c_exp_tax_range r"; // Criteria to sort dictionaries $tabsqlsort=array(); @@ -237,6 +244,8 @@ $tabsqlsort[30]="code ASC"; //$tabsqlsort[32]="position ASC"; $tabsqlsort[33]="code ASC"; $tabsqlsort[34]="code ASC"; +$tabsqlsort[35]="c.label ASC"; +$tabsqlsort[36]="r.fk_c_exp_tax_cat ASC, r.range_ik ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire $tabfield=array(); @@ -251,8 +260,8 @@ $tabfield[8] = "code,libelle,country_id,country".(! empty($conf->global->SOCIETE $tabfield[9] = "code,label,unicode"; $tabfield[10]= "country_id,country,code,taux,localtax1_type,localtax1,localtax2_type,localtax2,recuperableonly,accountancy_code_sell,accountancy_code_buy,note"; $tabfield[11]= "element,source,code,libelle,position"; -$tabfield[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder"; -$tabfield[13]= "code,libelle,type,accountancy_code"; +$tabfield[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder,entity"; +$tabfield[13]= "code,libelle,type,accountancy_code,entity"; $tabfield[14]= "code,libelle,price,organization,country_id,country"; $tabfield[15]= "code,libelle,width,height,unit"; $tabfield[16]= "code,libelle,sortorder"; @@ -272,8 +281,8 @@ $tabfield[29]= "code,label,percent,position"; $tabfield[30]= "code,name,paper_size,orientation,metric,leftmargin,topmargin,nx,ny,spacex,spacey,width,height,font_size,custom_x,custom_y"; //$tabfield[31]= "pcg_version,label"; //$tabfield[32]= "code,label,range_account,sens,category_type,formula,position,country_id,country"; -$tabfield[33]= "code,label"; -$tabfield[34]= "code,label"; +$tabfield[35]= "label"; +$tabfield[36]= "range_ik,fk_c_exp_tax_cat"; // Nom des champs d'edition pour modification d'un enregistrement $tabfieldvalue=array(); @@ -311,6 +320,8 @@ $tabfieldvalue[30]= "code,name,paper_size,orientation,metric,leftmargin,topmargi //$tabfieldvalue[32]= "code,label,range_account,sens,category_type,formula,position,country"; $tabfieldvalue[33]= "code,label"; $tabfieldvalue[34]= "code,label"; +$tabfieldvalue[35]= "label"; +$tabfieldvalue[36]= "range_ik,fk_c_exp_tax_cat"; // Nom des champs dans la table pour insertion d'un enregistrement $tabfieldinsert=array(); @@ -325,8 +336,8 @@ $tabfieldinsert[8] = "code,libelle,fk_country".(! empty($conf->global->SOCIETE_S $tabfieldinsert[9] = "code_iso,label,unicode"; $tabfieldinsert[10]= "fk_pays,code,taux,localtax1_type,localtax1,localtax2_type,localtax2,recuperableonly,accountancy_code_sell,accountancy_code_buy,note"; $tabfieldinsert[11]= "element,source,code,libelle,position"; -$tabfieldinsert[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder"; -$tabfieldinsert[13]= "code,libelle,type,accountancy_code"; +$tabfieldinsert[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder,entity"; +$tabfieldinsert[13]= "code,libelle,type,accountancy_code,entity"; $tabfieldinsert[14]= "code,libelle,price,organization,fk_pays"; $tabfieldinsert[15]= "code,label,width,height,unit"; $tabfieldinsert[16]= "code,label,sortorder"; @@ -348,6 +359,8 @@ $tabfieldinsert[30]= "code,name,paper_size,orientation,metric,leftmargin,topmarg //$tabfieldinsert[32]= "code,label,range_account,sens,category_type,formula,position,fk_country"; $tabfieldinsert[33]= "code,label"; $tabfieldinsert[34]= "code,label"; +$tabfieldinsert[35]= "label"; +$tabfieldinsert[36]= "range_ik,fk_c_exp_tax_cat"; // Nom du rowid si le champ n'est pas de type autoincrement // Example: "" if id field is "rowid" and has autoincrement on @@ -387,6 +400,8 @@ $tabrowid[30]= ""; //$tabrowid[32]= ""; $tabrowid[33]= "rowid"; $tabrowid[34]= "rowid"; +$tabrowid[35]= ""; +$tabrowid[36]= ""; // Condition to show dictionary in setup page $tabcond=array(); @@ -424,6 +439,8 @@ $tabcond[30]= ! empty($conf->label->enabled); //$tabcond[32]= ! empty($conf->accounting->enabled); $tabcond[33]= ! empty($conf->hrm->enabled); $tabcond[34]= ! empty($conf->hrm->enabled); +$tabcond[35]= ! empty($conf->expensereport->enabled); +$tabcond[36]= ! empty($conf->expensereport->enabled); // List of help for fields $tabhelp=array(); @@ -461,6 +478,8 @@ $tabhelp[30] = array('code'=>$langs->trans("EnterAnyCode"), 'name'=>$langs->tran //$tabhelp[32] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[33] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[34] = array('code'=>$langs->trans("EnterAnyCode")); +$tabhelp[35]= array(); +$tabhelp[36]= array('range_ik'=>$langs->trans('PrevRangeToThisRange')); // List of check for fields (NOT USED YET) $tabfieldcheck=array(); @@ -498,6 +517,8 @@ $tabfieldcheck[30] = array(); //$tabfieldcheck[32] = array(); $tabfieldcheck[33] = array(); $tabfieldcheck[34] = array(); +$tabfieldcheck[35]= array(); +$tabfieldcheck[36]= array(); // Complete all arrays with entries found into modules complete_dictionary_with_modules($taborder,$tabname,$tablib,$tabsql,$tabsqlsort,$tabfield,$tabfieldvalue,$tabfieldinsert,$tabrowid,$tabcond,$tabhelp,$tabfieldcheck); @@ -643,7 +664,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base { $ok = 0; - $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; + $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ } if (isset($_POST["country"]) && ($_POST["country"]=='0') && ($id != 2)) @@ -713,7 +734,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); } else if ($value == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; + $_POST[$listfieldvalue[$i]] = getEntity($tabname[$id]); } if ($i) $sql.=","; if ($listfieldvalue[$i] == 'sortorder') // For column name 'sortorder', we use the field name 'position' @@ -765,7 +786,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); } else if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; + $_POST[$listfieldvalue[$i]] = getEntity($tabname[$id]); } if ($i) $sql.=","; $sql.= $field."="; @@ -778,6 +799,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $i++; } $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + $sql.= " AND entity = '".getEntity($tabname[$id])."'"; dol_syslog("actionmodify", LOG_DEBUG); //print $sql; @@ -800,7 +822,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } else { $rowidcol="rowid"; } - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + $sql = "DELETE FROM ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); dol_syslog("delete", LOG_DEBUG); $result = $db->query($sql); @@ -824,10 +846,10 @@ if ($action == $acts[0]) else { $rowidcol="rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".dol_escape_htmltag($code)."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } $result = $db->query($sql); @@ -844,10 +866,10 @@ if ($action == $acts[1]) else { $rowidcol="rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".dol_escape_htmltag($code)."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } $result = $db->query($sql); @@ -864,10 +886,10 @@ if ($action == 'activate_favorite') else { $rowidcol="rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".dol_escape_htmltag($code)."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } $result = $db->query($sql); @@ -884,10 +906,10 @@ if ($action == 'disable_favorite') else { $rowidcol="rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".dol_escape_htmltag($code)."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } $result = $db->query($sql); @@ -939,6 +961,7 @@ print "
\n"; $param = '&id='.$id; if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; if ($search_code != '') $param.= '&search_code='.urlencode($search_country_id); +if ($entity != '') $param.= '&entity=' . (int) $entity; $paramwithsearch = $param; if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; @@ -996,16 +1019,22 @@ if ($id) if ($tabname[$id]) { $alabelisused=0; + $withentity=null; $fieldlist=explode(',',$tabfield[$id]); - print '
'; + print '
'; print ''; // Line for title print ''; foreach ($fieldlist as $field => $value) { + if ($fieldlist[$field] == 'entity') { + $withentity = getEntity($tabname[$id]); + continue; + } + // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut @@ -1075,6 +1104,9 @@ if ($id) if ($fieldlist[$field]=='affect') { $valuetoshow=$langs->trans("WithCounter"); } if ($fieldlist[$field]=='delay') { $valuetoshow=$langs->trans("NoticePeriod"); } if ($fieldlist[$field]=='newbymonth') { $valuetoshow=$langs->trans("NewByMonth"); } + if ($fieldlist[$field]=='fk_tva') { $valuetoshow=$langs->trans("VAT"); } + if ($fieldlist[$field]=='range_ik') { $valuetoshow=$langs->trans("RangeIk"); } + if ($fieldlist[$field]=='fk_c_exp_tax_cat'){ $valuetoshow=$langs->trans("CarCategory"); } if ($id == 2) // Special cas for state page { @@ -1096,6 +1128,8 @@ if ($id) if ($id == 4) print ''; print ''; print ''; print ''; @@ -1166,7 +1200,7 @@ if ($id) print '
'; } - print '
'; + print '
'; print '
'; print ''; + if (! is_null($withentity)) + print ''; print '
'; // Title line with search boxes @@ -1174,7 +1208,9 @@ if ($id) $filterfound=0; foreach ($fieldlist as $field => $value) { - $showfield=1; // By defaut + if ($fieldlist[$field] == 'entity') continue; + + $showfield=1; // By default if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } @@ -1216,6 +1252,8 @@ if ($id) print ''; foreach ($fieldlist as $field => $value) { + if ($fieldlist[$field] == 'entity') continue; + // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees $showfield=1; // By defaut @@ -1292,6 +1330,9 @@ if ($id) if ($fieldlist[$field]=='affect') { $valuetoshow=$langs->trans("WithCounter"); } if ($fieldlist[$field]=='delay') { $valuetoshow=$langs->trans("NoticePeriod"); } if ($fieldlist[$field]=='newbymonth') { $valuetoshow=$langs->trans("NewByMonth"); } + if ($fieldlist[$field]=='fk_tva') { $valuetoshow=$langs->trans("VAT"); } + if ($fieldlist[$field]=='range_ik') { $valuetoshow=$langs->trans("RangeIk"); } + if ($fieldlist[$field]=='fk_c_exp_tax_cat'){ $valuetoshow=$langs->trans("CarCategory"); } // Affiche nom du champ if ($showfield) @@ -1323,12 +1364,16 @@ if ($id) $error=$hookmanager->error; $errors=$hookmanager->errors; // Show fields - if (empty($reshook)) fieldList($fieldlist, $obj, $tabname[$id], 'edit'); + if (empty($reshook)) { + $withentity = fieldList($fieldlist, $obj, $tabname[$id], 'edit'); + } print ''; @@ -1343,11 +1388,19 @@ if ($id) if (empty($reshook)) { + $withentity=null; + foreach ($fieldlist as $field => $value) { - $showfield=1; + $showfield=1; $align="left"; - $valuetoshow=$obj->{$fieldlist[$field]}; + $valuetoshow=$obj->{$fieldlist[$field]}; + + if ($fieldlist[$field] == 'entity') { + $withentity = $valuetoshow; + continue; + } + if ($value == 'element') { $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; @@ -1509,6 +1562,26 @@ if ($id) else if ($fieldlist[$field]=='accountancy_code' || $fieldlist[$field]=='accountancy_code_sell' || $fieldlist[$field]=='accountancy_code_buy') { $valuetoshow = length_accountg($valuetoshow); } + elseif ($fieldlist[$field] == 'fk_tva') + { + foreach ($form->cache_vatrates as $key => $Tab) + { + if ($form->cache_vatrates[$key]['rowid'] == $valuetoshow) + { + $valuetoshow = $form->cache_vatrates[$key]['libtva']; + break; + } + } + } + elseif ($fieldlist[$field] == 'fk_c_exp_tax_cat') + { + $valuetoshow = getDictvalue(MAIN_DB_PREFIX.'c_exp_tax_cat', 'label', $valuetoshow); + $valuetoshow = $langs->trans($valuetoshow); + } + elseif ($tabname[$id] == MAIN_DB_PREFIX.'c_exp_tax_cat') + { + $valuetoshow = $langs->trans($valuetoshow); + } $class='tddict'; if ($fieldlist[$field] == 'note' && $id == 10) $class.=' tdoverflowmax200'; @@ -1542,7 +1615,8 @@ if ($id) // If rowidcol not defined if (empty($rowidcol) || in_array($id, array(6,7,8,13,17,19,27))) $rowidcol='rowid'; $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.((! empty($obj->{$rowidcol}) || $obj->{$rowidcol} == '0')?$obj->{$rowidcol}:(! empty($obj->code)?urlencode($obj->code):'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); - if ($param) $url .= '&'.$param; + if (! empty($param)) $url .= '&'.$param; + if (! is_null($withentity)) $url .= '&entity='.$withentity; $url.='&'; // Favorite @@ -1675,11 +1749,11 @@ $db->close(); * @param Object $obj If we show a particular record, obj is filled with record fields * @param string $tabname Name of SQL table * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered - * @return void + * @return string '' or value of entity into table */ function fieldList($fieldlist, $obj='', $tabname='', $context='') { - global $conf,$langs,$db; + global $conf,$langs,$db,$mysoc; global $form; global $region_id; global $elementList,$sourceList,$localtax_typeList; @@ -1689,8 +1763,15 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') $formcompany = new FormCompany($db); if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); + $withentity=''; + foreach ($fieldlist as $field => $value) { + if ($fieldlist[$field] == 'entity') { + $withentity = $obj->{$fieldlist[$field]}; + continue; + } + if (in_array($fieldlist[$field], array('code', 'libelle', 'type')) && $tabname == MAIN_DB_PREFIX."c_actioncomm" && in_array($obj->type, array('system','systemauto'))) { $hidden = (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''); @@ -1846,6 +1927,24 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') } print ''; } + elseif ($fieldlist[$field] == 'fk_tva') + { + print ''; + } + elseif ($fieldlist[$field] == 'fk_c_exp_tax_cat') + { + print ''; + } + elseif ($fieldlist[$field] == 'fk_range') + { + print ''; + } else { if ($fieldlist[$field]=='sortorder') $fieldlist[$field]='position'; @@ -1884,5 +1983,7 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') print ''; } } + + return $withentity; } diff --git a/htdocs/admin/dolistore/ajax/image.php b/htdocs/admin/dolistore/ajax/image.php new file mode 100644 index 00000000000..14d05a036e8 --- /dev/null +++ b/htdocs/admin/dolistore/ajax/image.php @@ -0,0 +1,68 @@ +. + * Copyright (C) 2008-2011 Laurent Destailleur + * + * This program is free software; you can redistribute it and/or modifyion 2.0 (the "License"); + * it under the terms of the GNU General Public License as published bypliance with the License. + * the Free Software Foundation; either version 3 of the License, or + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + */ + +if (!defined('REQUIRE_JQUERY_BLOCKUI')) define('REQUIRE_JQUERY_BLOCKUI', 1); + + +/** + * \file htdocs/commande/info.php + * \ingroup commande + * \brief Page des informations d'une commande + */ +$res = 0; +if (!$res && file_exists("../main.inc.php")) $res = @include("../main.inc.php"); +if (!$res && file_exists("../../main.inc.php")) $res = @include("../../main.inc.php"); +if (!$res && file_exists("../../../main.inc.php")) $res = @include("../../../main.inc.php"); +if (!$res && file_exists("../../../../main.inc.php")) $res = @include("../../../../main.inc.php"); +if (!$res && file_exists("../../../dolibarr/htdocs/main.inc.php")) + $res = @include("../../../dolibarr/htdocs/main.inc.php"); // Used on dev env only +if (!$res && file_exists("../../../../dolibarr/htdocs/main.inc.php")) + $res = @include("../../../../dolibarr/htdocs/main.inc.php"); // Used on dev env only +if (!$res && file_exists("../../../../../dolibarr/htdocs/main.inc.php")) + $res = @include("../../../../../dolibarr/htdocs/main.inc.php"); // Used on dev env only +if (!$res) die("Include of main fails"); + +// CORE + +global $lang, $user, $conf; + + +require_once DOL_DOCUMENT_ROOT.'/admin/dolistore/class/dolistore.class.php'; +$dolistore = new Dolistore(); + +$id_product = GETPOST('id_product', 'int'); +$id_image = GETPOST('id_image', 'int'); +// quality : image resize with this in the URL : "cart_default", "home_default", "large_default", "medium_default", "small_default", "thickbox_default" +$quality = GETPOST('quality', 'alpha'); + +try { + $url = $conf->global->MAIN_MODULE_DOLISTORE_API_SRV.'/api/images/products/'.$id_product.'/'.$id_image.'/'.$quality; + $api = new PrestaShopWebservice($conf->global->MAIN_MODULE_DOLISTORE_API_SRV, + $conf->global->MAIN_MODULE_DOLISTORE_API_KEY, $dolistore->debug_api); + //echo $url; + $request = $api->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'GET')); + header('Content-type:image'); + print $request['response']; +} catch (PrestaShopWebserviceException $e) { + // Here we are dealing with errors + $trace = $e->getTrace(); + if ($trace[0]['args'][0] == 404) die('Bad ID'); + else if ($trace[0]['args'][0] == 401) die('Bad auth key'); + else die('Can not access to '.$conf->global->MAIN_MODULE_DOLISTORE_API_SRV); +} + diff --git a/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php b/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php new file mode 100644 index 00000000000..10653df9dc0 --- /dev/null +++ b/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php @@ -0,0 +1,398 @@ + +* @copyright 2007-2013 PrestaShop SA +* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) +* International Registered Trademark & Property of PrestaShop SA +* PrestaShop Webservice Library +* @package PrestaShopWebservice +*/ + +/** + * @package PrestaShopWebservice + */ +class PrestaShopWebservice +{ + + /** @var string Shop URL */ + protected $url; + + /** @var string Authentification key */ + protected $key; + + /** @var boolean is debug activated */ + protected $debug; + + /** @var string PS version */ + protected $version; + + /** @var array compatible versions of PrestaShop Webservice */ + const PSCOMPATIBLEVERSIONMIN = '1.4.0.0'; + const PSCOMPATIBLEVERSIONMAX = '1.6.99.99'; + + + /** + * PrestaShopWebservice constructor. Throw an exception when CURL is not installed/activated + * + * getMessage(); + * } + * ?> + * + * @param string $url Root URL for the shop + * @param string $key Authentification key + * @param mixed $debug Debug mode Activated (true) or deactivated (false) + */ + function __construct($url, $key, $debug = true) { + if (!extension_loaded('curl')) + throw new PrestaShopWebserviceException('Please activate the PHP extension \'curl\' to allow use of PrestaShop webservice library'); + $this->url = $url; + $this->key = $key; + $this->debug = $debug; + $this->version = 'unknown'; + } + + /** + * Take the status code and throw an exception if the server didn't return 200 or 201 code + * + * @param int $status_code Status code of an HTTP return + */ + protected function checkStatusCode($status_code) + { + $error_label = 'This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s.'; + switch($status_code) + { + case 200: + case 201: + break; + case 204: + throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'No content')); + case 400: + throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Bad Request')); + case 401: + throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Unauthorized')); + case 404: + throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Not Found')); + case 405: + throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Method Not Allowed')); + case 500: + throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Internal Server Error')); + default: + throw new PrestaShopWebserviceException('This call to PrestaShop Web Services returned an unexpected HTTP status of:' . $status_code); + } + } + + /** + * Handles a CURL request to PrestaShop Webservice. Can throw exception. + * + * @param string $url Resource name + * @param mixed $curl_params CURL parameters (sent to curl_set_opt) + * @return array status_code, response + */ + public function executeRequest($url, $curl_params = array()) + { + $defaultParams = array( + CURLOPT_HEADER => TRUE, + CURLOPT_RETURNTRANSFER => TRUE, + CURLINFO_HEADER_OUT => TRUE, + CURLOPT_HTTPAUTH => CURLAUTH_BASIC, + CURLOPT_USERPWD => $this->key.':', + CURLOPT_HTTPHEADER => array( 'Expect:' ) + ); + + $session = curl_init($url); + + $curl_options = array(); + foreach ($defaultParams as $defkey => $defval) + { + if (isset($curl_params[$defkey])) + $curl_options[$defkey] = $curl_params[$defkey]; + else + $curl_options[$defkey] = $defaultParams[$defkey]; + } + foreach ($curl_params as $defkey => $defval) + if (!isset($curl_options[$defkey])) + $curl_options[$defkey] = $curl_params[$defkey]; + + curl_setopt_array($session, $curl_options); + $response = curl_exec($session); + + $index = strpos($response, "\r\n\r\n"); + if ($index === false && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD') + throw new PrestaShopWebserviceException('Bad HTTP response'); + + $header = substr($response, 0, $index); + $body = substr($response, $index + 4); + + $headerArrayTmp = explode("\n", $header); + + $headerArray = array(); + foreach ($headerArrayTmp as &$headerItem) + { + $tmp = explode(':', $headerItem); + $tmp = array_map('trim', $tmp); + if (count($tmp) == 2) + $headerArray[$tmp[0]] = $tmp[1]; + } + + if (array_key_exists('PSWS-Version', $headerArray)) + { + $this->version = $headerArray['PSWS-Version']; + if ( + version_compare(PrestaShopWebservice::PSCOMPATIBLEVERSIONMIN, $headerArray['PSWS-Version']) == 1 || + version_compare(PrestaShopWebservice::PSCOMPATIBLEVERSIONMAX, $headerArray['PSWS-Version']) == -1 + ) + throw new PrestaShopWebserviceException('This library is not compatible with this version of PrestaShop. Please upgrade/downgrade this library'); + } + + if ($this->debug) + { + $this->printDebug('HTTP REQUEST HEADER', curl_getinfo($session, CURLINFO_HEADER_OUT)); + $this->printDebug('HTTP RESPONSE HEADER', $header); + + } + $status_code = curl_getinfo($session, CURLINFO_HTTP_CODE); + if ($status_code === 0) + throw new PrestaShopWebserviceException('CURL Error: '.curl_error($session)); + curl_close($session); + if ($this->debug) + { + if ($curl_params[CURLOPT_CUSTOMREQUEST] == 'PUT' || $curl_params[CURLOPT_CUSTOMREQUEST] == 'POST') + $this->printDebug('XML SENT', urldecode($curl_params[CURLOPT_POSTFIELDS])); + if ($curl_params[CURLOPT_CUSTOMREQUEST] != 'DELETE' && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD') + $this->printDebug('RETURN HTTP BODY', $body); + } + return array('status_code' => $status_code, 'response' => $body, 'header' => $header); + } + + /** + * Output debug info + * + * @param string $title Title + * @param string $content Content + * @return void + */ + public function printDebug($title, $content) + { + echo '
'.$title.'
'.htmlentities($content).'
'; + } + + /** + * Return version + * + * @return string Version + */ + public function getVersion() + { + return $this->version; + } + + /** + * Load XML from string. Can throw exception + * + * @param string $response String from a CURL response + * @return SimpleXMLElement status_code, response + */ + protected function parseXML($response) + { + if ($response != '') + { + libxml_clear_errors(); + libxml_use_internal_errors(true); + $xml = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA); + if (libxml_get_errors()) + { + $msg = var_export(libxml_get_errors(), true); + libxml_clear_errors(); + throw new PrestaShopWebserviceException('HTTP XML response is not parsable: '.$msg); + } + return $xml; + } + else + throw new PrestaShopWebserviceException('HTTP response is empty'); + } + + /** + * Add (POST) a resource + *

Unique parameter must take :

+ * 'resource' => Resource name
+ * 'postXml' => Full XML string to add resource

+ * Examples are given in the tutorial

+ * + * @param array $options Options + * @return SimpleXMLElement status_code, response + */ + public function add($options) + { + $xml = ''; + + if (isset($options['resource'], $options['postXml']) || isset($options['url'], $options['postXml'])) + { + $url = (isset($options['resource']) ? $this->url.'/api/'.$options['resource'] : $options['url']); + $xml = $options['postXml']; + if (isset($options['id_shop'])) + $url .= '&id_shop='.$options['id_shop']; + if (isset($options['id_group_shop'])) + $url .= '&id_group_shop='.$options['id_group_shop']; + } + else + throw new PrestaShopWebserviceException('Bad parameters given'); + $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $xml)); + + self::checkStatusCode($request['status_code']); + return self::parseXML($request['response']); + } + + /** + * Retrieve (GET) a resource + *

Unique parameter must take :

+ * 'url' => Full URL for a GET request of Webservice (ex: http://mystore.com/api/customers/1/)
+ * OR
+ * 'resource' => Resource name,
+ * 'id' => ID of a resource you want to get

+ *

+ * + * get(array('resource' => 'orders', 'id' => 1)); + * // Here in $xml, a SimpleXMLElement object you can parse + * foreach ($xml->children()->children() as $attName => $attValue) + * echo $attName.' = '.$attValue.'
'; + * } + * catch (PrestaShopWebserviceException $ex) + * { + * echo 'Error : '.$ex->getMessage(); + * } + * ?> + *
+ * @param array $options Array representing resource to get. + * @return SimpleXMLElement status_code, response + */ + public function get($options) + { + if (isset($options['url'])) + $url = $options['url']; + elseif (isset($options['resource'])) + { + $url = $this->url.'/api/'.$options['resource']; + $url_params = array(); + if (isset($options['id'])) + $url .= '/'.$options['id']; + + $params = array('filter', 'display', 'sort', 'limit', 'id_shop', 'id_group_shop'); + foreach ($params as $p) + foreach ($options as $k => $o) + if (strpos($k, $p) !== false) + $url_params[$k] = $options[$k]; + if (count($url_params) > 0) + $url .= '?'.http_build_query($url_params); + } + else + throw new PrestaShopWebserviceException('Bad parameters given '); + + $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'GET')); + self::checkStatusCode($request['status_code']);// check the response validity + return self::parseXML($request['response']); + } + + /** + * Head method (HEAD) a resource + * + * @param array $options Array representing resource for head request. + * @return SimpleXMLElement status_code, response + */ + public function head($options) + { + if (isset($options['url'])) + $url = $options['url']; + elseif (isset($options['resource'])) + { + $url = $this->url.'/api/'.$options['resource']; + $url_params = array(); + if (isset($options['id'])) + $url .= '/'.$options['id']; + + $params = array('filter', 'display', 'sort', 'limit'); + foreach ($params as $p) + foreach ($options as $k => $o) + if (strpos($k, $p) !== false) + $url_params[$k] = $options[$k]; + if (count($url_params) > 0) + $url .= '?'.http_build_query($url_params); + } + else + throw new PrestaShopWebserviceException('Bad parameters given'); + $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'HEAD', CURLOPT_NOBODY => true)); + self::checkStatusCode($request['status_code']);// check the response validity + return $request['header']; + } + /** + * Edit (PUT) a resource + *

Unique parameter must take :

+ * 'resource' => Resource name ,
+ * 'id' => ID of a resource you want to edit,
+ * 'putXml' => Modified XML string of a resource

+ * Examples are given in the tutorial

+ * + * @param array $options Array representing resource to edit. + * @return SimpleXMLElement status_code, response + */ + public function edit($options) + { + $xml = ''; + if (isset($options['url'])) + $url = $options['url']; + elseif ((isset($options['resource'], $options['id']) || isset($options['url'])) && $options['putXml']) + { + $url = (isset($options['url']) ? $options['url'] : $this->url.'/api/'.$options['resource'].'/'.$options['id']); + $xml = $options['putXml']; + if (isset($options['id_shop'])) + $url .= '&id_shop='.$options['id_shop']; + if (isset($options['id_group_shop'])) + $url .= '&id_group_shop='.$options['id_group_shop']; + } + else + throw new PrestaShopWebserviceException('Bad parameters given'); + + $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_POSTFIELDS => $xml)); + self::checkStatusCode($request['status_code']);// check the response validity + return self::parseXML($request['response']); + } +} + +/** + * @package PrestaShopWebservice + */ +class PrestaShopWebserviceException extends Exception +{ + +} diff --git a/htdocs/admin/dolistore/class/dolistore.class.php b/htdocs/admin/dolistore/class/dolistore.class.php new file mode 100644 index 00000000000..07dbec4b902 --- /dev/null +++ b/htdocs/admin/dolistore/class/dolistore.class.php @@ -0,0 +1,343 @@ +. + * + * This program is free software; you can redistribute it and/or modifyion 2.0 (the "License"); + * it under the terms of the GNU General Public License as published bypliance with the License. + * the Free Software Foundation; either version 3 of the License, or + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + */ + +include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +include_once DOL_DOCUMENT_ROOT.'/admin/dolistore/class/PSWebServiceLibrary.class.php'; + + +/** + * Class Dolistore + */ +class Dolistore +{ + // params + public $start; // beginning of pagination + public $end; // end of pagination + public $per_page; // pagination: display per page + public $categorie; // the current categorie + public $search; // the search keywords + + // setups + public $url; // the url of this page + public $shop_url; // the url of the shop + public $vat_rate; // the vat rate used in the shop (prices are provided without vat) + public $lang; // the integer representing the lang in the store + public $debug_api; // usefull if no dialog + + + /** + * Constructor + */ + function __construct() + { + global $conf, $langs; + + $this->url = DOL_URL_ROOT.'/admin/modules.php?mode=marketplace'; + $this->shop_url = 'https://www.dolistore.com/index.php?controller=product&id_product='; + $this->vat_rate = 1.2; // 20% de TVA + $this->debug_api = false; + + $langtmp = explode('_', $langs->defaultlang); + $lang = $langtmp[0]; + $lang_array = array('en'=>0, 'fr'=>1, 'es'=>2, 'it'=>3, 'de'=>4); // Into table ps_lang of Prestashop - 1 + if (! in_array($lang, array_keys($lang_array))) $lang = 'en'; + $this->lang = $lang_array[$lang]; + } + + /** + * Load data from remote Dolistore market place. + * This fills ->categories + * + * @param array $options Options + * @return void + */ + function getRemoteData($options = array('start' => 0, 'end' => 10, 'per_page' => 50, 'categorie' => 0)) + { + global $conf, $langs; + + $this->start = $options['start']; + $this->end = $options['end']; + $this->per_page = $options['per_page']; + $this->categorie = $options['categorie']; + $this->search = $options['search']; + + if ($this->end == 0) { + $this->end = $this->per_page; + } + + try { + $this->api = new PrestaShopWebservice($conf->global->MAIN_MODULE_DOLISTORE_API_SRV, + $conf->global->MAIN_MODULE_DOLISTORE_API_KEY, $this->debug_api); + + // Here we set the option array for the Webservice : we want products resources + $opt = array(); + $opt['resource'] = 'products'; + + // make a search to limit the id returned. + if ($this->search != '') { + $opt2 = array(); + $opt2['url'] = $conf->global->MAIN_MODULE_DOLISTORE_API_SRV.'/api/search?query='.$this->search.'&language='.$this->lang; + // Call + $xml = $this->api->get($opt2); + $products = array(); + foreach ($xml->products->children() as $product) { + $products[] = (int) $product['id']; + } + $opt['filter[id]'] = '['.implode('|', $products).']'; + } elseif ($this->categorie != 0) { + $opt2 = array(); + $opt2['resource'] = 'categories'; + $opt2['id'] = $this->categorie; + // Call + $xml = $this->api->get($opt2); + $products = array(); + foreach ($xml->category->associations->products->children() as $product) { + $products[] = (int) $product->id; + } + $opt['filter[id]'] = '['.implode('|', $products).']'; + } + $opt['display'] = '[id,name,id_default_image,id_category_default,reference,price,condition,show_price,date_add,date_upd,description_short,description,module_version,dolibarr_min,dolibarr_max]'; + $opt['sort'] = 'id_desc'; + $opt['filter[active]'] = '[1]'; + $opt['limit'] = "$this->start,$this->end"; + // $opt['filter[id]'] contais list of product id that are result of search + + // Call API to get the detail + $xml = $this->api->get($opt); + $this->products = $xml->products->children(); + + + // Here we set the option array for the Webservice : we want categories resources + $opt = array(); + $opt['resource'] = 'categories'; + $opt['display'] = '[id,id_parent,nb_products_recursive,active,is_root_category,name,description]'; + $opt['sort'] = 'id_asc'; + // Call + $xml = $this->api->get($opt); + $this->categories = $xml->categories->children(); + } catch (PrestaShopWebserviceException $e) { + // Here we are dealing with errors + $trace = $e->getTrace(); + if ($trace[0]['args'][0] == 404) die('Bad ID'); + else if ($trace[0]['args'][0] == 401) die('Bad auth key'); + else die('Can not access to '.$conf->global->MAIN_MODULE_DOLISTORE_API_SRV); + } + } + + /** + * Return tree of Dolistore categories. $this->categories must have been loaded before. + * + * @param int $parent Id of parent category + * @return string + */ + function get_categories($parent = 0) + { + if (!isset($this->categories)) die('not possible'); + if ($parent != 0) { + $html = '
    '; + } else { + $html = ''; + } + + $nbofcateg = count($this->categories); + for ($i = 0; $i < $nbofcateg; $i++) + { + $cat = $this->categories[$i]; + if ($cat->is_root_category == 1 && $parent == 0) { + $html .= '
  • '.$cat->name->language[$this->lang].' '.$cat->nb_products_recursive.'

    '; + $html .= self::get_categories($cat->id); + $html .= "
  • \n"; + } elseif (trim($cat->id_parent) == $parent && $cat->active == 1 && trim($cat->id_parent) != 0) { // si cat est de ce niveau + $select = ($cat->id == $this->categorie) ? ' selected' : ''; + $html .= '
  • '.$cat->name->language[$this->lang].' '.$cat->nb_products_recursive.''; + $html .= self::get_categories($cat->id); + $html .= "
  • \n"; + } else { + + } + } + + if ($html == '
      ') { + return ''; + } + if ($parent != 0) { + return $html.'
    '; + } else { + return $html; + } + } + + /** + * Return list of product formated for output + * + * @return string HTML output + */ + function get_products() + { + global $langs, $conf; + $html = ""; + $parity = "pair"; + $last_month = time() - (30 * 24 * 60 * 60); + foreach ($this->products as $product) { + $parity = ($parity == "impair") ? 'pair' : 'impair'; + + // check new product ? + $newapp = ''; + if ($last_month < strtotime($product->date_add)) { + $newapp .= ''.$langs->trans('New').' '; + } + + // check updated ? + if ($last_month < strtotime($product->date_upd) && $newapp == '') { + $newapp .= ''.$langs->trans('Updated').' '; + } + + // add image or default ? + if ($product->id_default_image != '') { + $image_url = DOL_URL_ROOT.'/admin/dolistore/ajax/image.php?id_product='.$product->id.'&id_image='.$product->id_default_image; + $images = ''. + ''; + } else { + $images = ''; + } + + // free or pay ? + if ($product->price > 0) { + $price = '

    '.price(round((float) $product->price * $this->vat_rate, 2)).' €

    '; + $download_link = ''; + } else { + $price = '

    '.$langs->trans('Free').'

    '; + $download_link = ''; + $download_link.= '

    '; + } + + //checking versions + if ($this->version_compare($product->dolibarr_min, DOL_VERSION) <= 0) { + if ($this->version_compare($product->dolibarr_max, DOL_VERSION) >= 0) { + //compatible + $version = ''.$langs->trans('CompatibleUpTo', $product->dolibarr_max, + $product->dolibarr_min, $product->dolibarr_max).''; + $compatible = ''; + } else { + //never compatible, module expired + $version = ''.$langs->trans('NotCompatible', DOL_VERSION, + $product->dolibarr_min, $product->dolibarr_max).''; + $compatible = 'NotCompatible'; + } + } else { + //need update + $version = ''.$langs->trans('CompatibleAfterUpdate', DOL_VERSION, + $product->dolibarr_min, $product->dolibarr_max).''; + $compatible = 'NotCompatible'; + } + + //.'
    '.$langs->trans("SeeInMarkerPlace").' + + //output template + $html .= '
+ + + + + + '; + } + return $html; + } + + function get_previous_link($text = '<<') + { + return ''.$text.''; + } + + function get_next_link($text = '>>') + { + return ''.$text.''; + } + + function get_previous_url() + { + $param_array = array(); + if ($this->start < $this->per_page) { + $sub = 0; + } else { + $sub = $this->per_page; + } + $param_array['start'] = $this->start - $sub; + $param_array['end'] = $this->end - $sub; + if ($this->categorie != 0) { + $param_array['categorie'] = $this->categorie; + } + $param = http_build_query($param_array); + return $this->url."&".$param; + } + + function get_next_url() + { + $param_array = array(); + if (count($this->products) < $this->per_page) { + $add = 0; + } else { + $add = $this->per_page; + } + $param_array['start'] = $this->start + $add; + $param_array['end'] = $this->end + $add; + if ($this->categorie != 0) { + $param_array['categorie'] = $this->categorie; + } + $param = http_build_query($param_array); + return $this->url."&".$param; + } + + function version_compare($v1, $v2) + { + $v1 = explode('.', $v1); + $v2 = explode('.', $v2); + $ret = 0; + $level = 0; + $count1 = count($v1); + $count2 = count($v2); + $maxcount = max($count1, $count2); + while ($level < $maxcount) { + $operande1 = isset($v1[$level]) ? $v1[$level] : 'x'; + $operande2 = isset($v2[$level]) ? $v2[$level] : 'x'; + $level++; + if (strtoupper($operande1) == 'X' || strtoupper($operande2) == 'X' || $operande1 == '*' || $operande2 == '*') { + break; + } + if ($operande1 < $operande2) { + $ret = -$level; + break; + } + if ($operande1 > $operande2) { + $ret = $level; + break; + } + } + //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'
'."\n"; + return $ret; + } +} + diff --git a/htdocs/admin/dolistore/css/dolistore.css b/htdocs/admin/dolistore/css/dolistore.css new file mode 100644 index 00000000000..bba808a21a0 --- /dev/null +++ b/htdocs/admin/dolistore/css/dolistore.css @@ -0,0 +1,237 @@ + +div.divsearchfield { + float: left; + margin: 4px 12px 4px 2px; + padding-left: 2px; +} + +.margeCoteGauche,.margeCote{ + padding-right: 20px!important; +} +.margeCote,.margeCoteDroite{ + padding-left: 20px!important; +} +.nomargesupinf{ + margin-top: 0; + margin-bottom: 0; +} +#category-tree-left{ + display: none; + vertical-align: top; + width: 24%; +} +#listing-content{ + box-sizing: border-box; + display: inline-block; + width: 100%; +} +.tree{ + margin: 0px 0px 0px 0px; + padding:0px; + list-style: none; line-height: 2em; font-family: Arial; +} +.tree li{ + font-size: 16px; + position: relative;list-style: none; +} +.tree li:before{ + position: absolute; + left: -15px; + top: -4px; + content: ''; + display: block; + border-left: 1px solid #ddd; + height: 1em; + border-bottom: 1px solid #ddd; + width: 10px; +} +.tree li:after{ + position: absolute; + left: -15px; + bottom: -7px; + content: ''; + display: block; + border-left: 1px solid #ddd; + height: 100%; +} + +.tree li.root{ + margin: 0px 0px 0px 0px; +} +.tree li.root:before{ + display: none; +} + +.tree li.root:after{ + display: none; +} +.tree li:last-child:after{ + display: none +} +.blockUI { + cursor: auto!important; +} +.newAppParent{ + position: relative; + overflow: hidden; + min-height: 100px; +} +.newApp, .updatedApp{ + background-color: orange; + box-shadow: 0 0 20px rgba(0, 0, 0, 0.35); + box-sizing: border-box; + color: white; + display: block; + font-size: 18px; + font-weight: bold; + left: -34px; + padding: 5px 0; + position: absolute; + text-align: center; + text-shadow: 0 0 5px rgba(0, 0, 0, 0.35); + top: 22px; + transform: rotate(-45deg); + width: 150px; +} +.updatedApp{ + background-color: greenyellow; +} +.notcompatible { + color: red; +} +.compatibleafterupdate { + color: orange; +} +.compatible { + background-image: url("../img/compatible.png"); + background-position: left center; + background-repeat: no-repeat; + color: green; + display: inline-block; + height: 32px; + line-height: 32px; + padding-left: 35px; +} +tr.app { + height:250px; +} +tr.app td { + border-bottom: 1px solid #888; +} +div#newsDoli.tabBar { + margin-top: 50px; + margin-right: 30px; +} +.selected { + text-decoration: underline!important; +} +.searchDolistore, .searchDolistore:hover { + padding-left: 30px; + padding-right: 30px; + font-weight: bold; +} +.searchDolistore:hover { + text-decoration: underline!important; +} + +.score{ + font-size: 16px; + font-weight: bold; +} +.formReviewArea{ + display:none; +} +.formReview div.divsearchfield{ + float: none; +} +.input100{ + box-sizing: border-box; + width: 100%; +} +.input50{ + box-sizing: border-box; + width: 49%; +} +textarea.row4{ + min-height: 100px; +} + + +.reviewList { + max-height: 150px; + overflow-y: scroll; +} + +.reviewRow{ + margin-bottom: 20px; +} +.reviewRow .reviewMarge { + float:left; + width: 220px; + padding: 0 20px 20px 0; +} +.reviewRow .score { + font-size: 48px; + display: block; + text-align: center; +} +.reviewRow .reviewDate { + color:grey; +} +.reviewRow:after{ + clear: both; + content:''; + display: block; +} +h2.appTitle small{ + font-weight: normal; +} +tr.NotCompatible{ + /* IE 8 */ + -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=25)"; + + /* IE 5-7 */ + filter: alpha(opacity=25); + + /* Netscape */ + -moz-opacity: 0.25; + + /* Safari 1.x */ + -khtml-opacity: 0.25; + + /* Good browsers */ + opacity: 0.25; +} +tr.NotCompatible:hover{ + /* IE 8 */ + -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; + + /* IE 5-7 */ + filter: alpha(opacity=100); + + /* Netscape */ + -moz-opacity: 1; + + /* Safari 1.x */ + -khtml-opacity: 1; + + /* Good browsers */ + opacity: 1; +} +@media only screen and (min-width: 1150px) { + #categorieArea{ + display:none; + } + #category-tree-left{ + display:inline-block; + } + #listing-content{ + width: 75%; + float: right; + } +} +span.details{ + font-size: 12px; + margin-left: 10px; + vertical-align: super; +} \ No newline at end of file diff --git a/htdocs/admin/dolistore/img/Download-128.png b/htdocs/admin/dolistore/img/Download-128.png new file mode 100644 index 00000000000..89756d1f012 Binary files /dev/null and b/htdocs/admin/dolistore/img/Download-128.png differ diff --git a/htdocs/admin/dolistore/img/NoImageAvailable.png b/htdocs/admin/dolistore/img/NoImageAvailable.png new file mode 100644 index 00000000000..9a88d4362da Binary files /dev/null and b/htdocs/admin/dolistore/img/NoImageAvailable.png differ diff --git a/htdocs/admin/dolistore/img/compatible.png b/htdocs/admin/dolistore/img/compatible.png new file mode 100644 index 00000000000..93a85574165 Binary files /dev/null and b/htdocs/admin/dolistore/img/compatible.png differ diff --git a/htdocs/admin/dolistore/img/dolistore.png b/htdocs/admin/dolistore/img/dolistore.png new file mode 100644 index 00000000000..d3fc61e7293 Binary files /dev/null and b/htdocs/admin/dolistore/img/dolistore.png differ diff --git a/htdocs/admin/dolistore/img/follow.png b/htdocs/admin/dolistore/img/follow.png new file mode 100644 index 00000000000..78383c1157f Binary files /dev/null and b/htdocs/admin/dolistore/img/follow.png differ diff --git a/htdocs/admin/dolistore/img/object_dolistore.png b/htdocs/admin/dolistore/img/object_dolistore.png new file mode 100644 index 00000000000..213d0e0a3b7 Binary files /dev/null and b/htdocs/admin/dolistore/img/object_dolistore.png differ diff --git a/htdocs/admin/expedition.php b/htdocs/admin/expedition.php index ba389c5207a..d623de33f31 100644 --- a/htdocs/admin/expedition.php +++ b/htdocs/admin/expedition.php @@ -477,14 +477,14 @@ print ""; print "\n"; print ""; -$substitutionarray=pdf_getSubstitutionArray($langs); +$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; $htmltext.='
'; print '\n"; print '\n"; diff --git a/htdocs/admin/expedition_extrafields.php b/htdocs/admin/expedition_extrafields.php index 8c24c49cb23..09e0e8b9a92 100644 --- a/htdocs/admin/expedition_extrafields.php +++ b/htdocs/admin/expedition_extrafields.php @@ -47,7 +47,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/expeditiondet_extrafields.php b/htdocs/admin/expeditiondet_extrafields.php index 283eeab452a..ff388d8a69a 100644 --- a/htdocs/admin/expeditiondet_extrafields.php +++ b/htdocs/admin/expeditiondet_extrafields.php @@ -7,7 +7,7 @@ * Copyright (C) 2013 Philippe Grand * Copyright (C) 2013 Florian Henry * Copyright (C) 2015 Claudio Aschieri - * + * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -47,7 +47,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/expensereport.php b/htdocs/admin/expensereport.php index 97ce21ab585..86fac86f532 100644 --- a/htdocs/admin/expensereport.php +++ b/htdocs/admin/expensereport.php @@ -207,24 +207,26 @@ $head=expensereport_admin_prepare_head(); dol_fiche_head($head, 'expensereport', $langs->trans("ExpenseReports"), -1, 'trip'); -// Interventions numbering model /* -print load_fiche_titre($langs->trans("FicheinterNumberingModules"),'',''); + * Expense report numbering model + */ + +print load_fiche_titre($langs->trans("ExpenseReportNumberingModules"),'',''); print '
'; print '
'; print ''; print ''; + if (! is_null($withentity)) + print ''; print ''; print ''; print '
'; + print $form->load_tva('fk_tva', $obj->taux, $mysoc, new Societe($db), 0, 0, '', false, -1); + print ''; + print $form->selectExpenseCategories($obj->fk_c_exp_tax_cat); + print ''; + print $form->selectExpenseRanges($obj->fk_range); + print '
'.$newapp.$images.'

'.$product->name->language[$this->lang] + .'
'.$version.'

+ '.dol_print_date(dol_stringtotime($product->date_upd), 'dayhour').' - '.$langs->trans('Ref').': '.$product->reference.' - '.$langs->trans('Id').': '.$product->id.'

'.$product->description_short->language[$this->lang].'
'.$price.' + '.$download_link.'
".$langs->trans("Parameter")."
'; -print $form->textwithpicto($langs->trans("FreeLegalTextOnShippings"), $langs->trans("AddCRIfTooLong").'

'.$htmltext).'
'; +print $form->textwithpicto($langs->trans("FreeLegalTextOnShippings"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='SHIPPING_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { @@ -499,7 +499,7 @@ else print "
'; -print $form->textwithpicto($langs->trans("WatermarkOnDraftContractCards"), $htmltext).'
'; +print $form->textwithpicto($langs->trans("WatermarkOnDraftContractCards"), $htmltext, 1, 'help', '', 0, 2, 'watermarktooltip').'
'; print ''; print "
'; print ''; -print ''; +print ''; print ''; -print ''; +print ''; print ''; -print ''; -print "\n"; +print ''; +print ''."\n"; clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/fichinter/"); + $dir = dol_buildpath($reldir."core/modules/expensereport/"); if (is_dir($dir)) { @@ -235,21 +237,20 @@ foreach ($dirmodels as $reldir) while (($file = readdir($handle))!==false) { - if (preg_match('/^(mod_.*)\.php$/i',$file,$reg)) + if (substr($file, 0, 18) == 'mod_expensereport_' && substr($file, dol_strlen($file)-3, 3) == 'php') { - $file = $reg[1]; - $classname = substr($file,4); + $file = substr($file, 0, dol_strlen($file)-4); require_once $dir.$file.'.php'; - $module = new $file; + $module = new $file($db); + + // Show modules according to features level + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; if ($module->isEnabled()) { - // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; - print ''."\n"; print ''; - $ficheinter=new Fichinter($db); - $ficheinter->initAsSpecimen(); + $exp=new ExpenseReport($db); + $exp->initAsSpecimen(); // Info $htmltooltip=''; $htmltooltip.=''.$langs->trans("Version").': '.$module->getVersion().'
'; - $nextval=$module->getNextValue($mysoc,$ficheinter); - if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval + $nextval=$module->getNextValue($exp); + if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval $htmltooltip.=''.$langs->trans("NextValue").': '; if ($nextval) { if (preg_match('/^Error/',$nextval) || $nextval=='NotConfigured') @@ -291,11 +294,12 @@ foreach ($dirmodels as $reldir) $htmltooltip.=$langs->trans($module->error).'
'; } } + print ''; - print ''; + print "\n"; } } } @@ -303,9 +307,7 @@ foreach ($dirmodels as $reldir) } } } - -print '
'.$langs->trans("Name").''.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Example").''.$langs->trans("Example").''.$langs->trans("Status").''.$langs->trans("ShortInfo").'
'.$langs->trans("ShortInfo").'
'.$module->nom."\n"; print $module->info(); @@ -264,24 +265,26 @@ foreach ($dirmodels as $reldir) print ''; - if ($conf->global->FICHEINTER_ADDON == $classname) + if ($conf->global->EXPENSEREPORT_ADDON == $file) { print img_picto($langs->trans("Activated"),'switch_on'); } else { - print ''.img_picto($langs->trans("Disabled"),'switch_off').''; + print ''; + print img_picto($langs->trans("Disabled"),'switch_off'); + print ''; } print ''; print $form->textwithpicto('',$htmltooltip,1,0); print '

'; -*/ +print "
\n"; /* * Documents models for Interventions @@ -480,7 +482,7 @@ print ''; print "\n"; $var=true; -$substitutionarray=pdf_getSubstitutionArray($langs); +$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; @@ -488,7 +490,7 @@ $htmltext.='
'; $var=! $var; print ''; -print $form->textwithpicto($langs->trans("FreeLegalTextOnExpenseReports"), $langs->trans("AddCRIfTooLong").'

'.$htmltext).'
'; +print $form->textwithpicto($langs->trans("FreeLegalTextOnExpenseReports"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='EXPENSEREPORT_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { @@ -505,7 +507,7 @@ print ''."\n"; //Use draft Watermark print ''; -print $form->textwithpicto($langs->trans("WatermarkOnDraftExpenseReports"), $htmltext).'
'; +print $form->textwithpicto($langs->trans("WatermarkOnDraftExpenseReports"), $htmltext, 1, 'help', '', 0, 2, 'watermarktooltip').'
'; print ''; print ''."\n"; diff --git a/htdocs/admin/expensereport_extrafields.php b/htdocs/admin/expensereport_extrafields.php index d1d3aacc9cc..8635c336a2b 100644 --- a/htdocs/admin/expensereport_extrafields.php +++ b/htdocs/admin/expensereport_extrafields.php @@ -44,7 +44,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/expensereport_ik.php b/htdocs/admin/expensereport_ik.php new file mode 100644 index 00000000000..9e653dce906 --- /dev/null +++ b/htdocs/admin/expensereport_ik.php @@ -0,0 +1,188 @@ + + * Copyright (C) 2017 ATM Consulting + * Copyright (C) 2017 Pierre-Henry Favre + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +/** + * \file htdocs/admin/expensereport_ik.php + * \ingroup expensereport + * \brief Page to display expense tax ik + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php'; + +$langs->load('admin'); +$langs->load('other'); +$langs->load('trips'); +$langs->load('errors'); +$langs->load('dict'); + +if (!$user->admin) accessforbidden(); + +//Init error +$error = false; +$message = false; + +$action = GETPOST('action','alpha'); +$id = GETPOST('id','int'); +$offset = GETPOST('offset','int'); +$coef = GETPOST('coef','int'); + +$fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat'); +$fk_range = GETPOST('fk_range'); + +if ($action == 'updateik') +{ + $expIk = new ExpenseReportIk($db); + if ($id > 0) + { + $result = $expIk->fetch($id); + if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); + } + + $expIk->setValues($_POST); + $result = $expIk->create($user); + + if ($result > 0) setEventMessages('SetupSaved', null, 'mesgs'); + + header('Location: '.$_SERVER['PHP_SELF']); + exit; +} +elseif ($action == 'delete') // TODO add confirm +{ + $expIk = new ExpenseReportIk($db); + if ($id > 0) + { + $result = $expIk->fetch($id); + if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); + + $expIk->delete($user); + } + + + header('Location: '.$_SERVER['PHP_SELF']); + exit; +} + +$rangesbycateg = ExpenseReportIk::getAllRanges(); + +/* + * View + */ + +llxHeader(); + +$form=new Form($db); + +$linkback=''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans("ExpenseReportsIkSetup"),$linkback,'title_setup'); + +$head=expensereport_admin_prepare_head(); +dol_fiche_head($head, 'expenseik', $langs->trans("ExpenseReportsIk"), -1, 'trip'); + +echo $langs->trans('ExpenseReportIkDesc'); + +echo '
'; + +if ($action == 'edit') +{ + echo ''; + echo ''; + echo ''; + echo ''; +} + +echo ''; + +echo ''; + +foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) +{ + $title = ($Tab['active'] == 1) ? $langs->trans($Tab['label']) : $form->textwithpicto($langs->trans($Tab['label']), $langs->trans('expenseReportCatDisabled'), 1, 'help', '', 0, 3); + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + + if ($Tab['active'] == 0) continue; + + $tranche=1; + $var = true; + foreach ($Tab['ranges'] as $k => $range) + { + if (isset($Tab['ranges'][$k+1])) $label = $langs->trans('expenseReportRangeFromTo', $range->range_ik, ($Tab['ranges'][$k+1]->range_ik-1)); + else $label = $langs->trans('expenseReportRangeMoreThan', $range->range_ik); + + if ($range->range_active == 0) $label = $form->textwithpicto($label, $langs->trans('expenseReportRangeDisabled'), 1, 'help', '', 0, 3); + + echo ''; + + // Label + echo ''; + + // Offset + echo ''; + // Coef + echo ''; + + // Total for one + echo ''; + + // Action + echo ''; + + echo ''; + $var=!$var; + } +} + +echo '
'.$title.''.$langs->trans('expenseReportOffset').''.$langs->trans('expenseReportCoef').''.$langs->trans('expenseReportTotalForFive').' 
['.$langs->trans('RangeNum', $tranche++).'] - '.$label.''; + if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; + else echo $range->ik->offset; + echo ''; + if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; + else echo ($range->ik->id > 0 ? $range->ik->coef : $langs->trans('expenseReportCoefUndefined')); + echo ''.$langs->trans('expenseReportPrintExample', price($range->ik->offset + 5 * $range->ik->coef)).''; + if ($range->range_active == 1) + { + if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) + { + echo ''; + echo ''; + } + else + { + echo ''.img_edit().''; + if (!empty($range->ik->id)) echo ''.img_delete().''; + // TODO add delete link + } + } + echo '
'; +echo '
'; + +dol_fiche_end(); +llxFooter(); + +$db->close(); \ No newline at end of file diff --git a/htdocs/admin/expensereport_rules.php b/htdocs/admin/expensereport_rules.php new file mode 100644 index 00000000000..695bdf09a12 --- /dev/null +++ b/htdocs/admin/expensereport_rules.php @@ -0,0 +1,366 @@ + + * Copyright (C) 2017 ATM Consulting + * Copyright (C) 2017 Pierre-Henry Favre + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +/** + * \file htdocs/admin/expensereport_ik.php + * \ingroup expensereport + * \brief Page to display expense tax ik + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.php'; + +$langs->load('admin'); +$langs->load('other'); +$langs->load('trips'); +$langs->load('errors'); +$langs->load('dict'); + +if (!$user->admin) accessforbidden(); + +//Init error +$error = false; +$message = false; + +$action = GETPOST('action','alpha'); +$id = GETPOST('id','int'); + +$apply_to = GETPOST('apply_to'); +$fk_user = GETPOST('fk_user'); +$fk_usergroup = GETPOST('fk_usergroup'); + +$fk_c_type_fees = GETPOST('fk_c_type_fees'); +$code_expense_rules_type = GETPOST('code_expense_rules_type'); +$dates = dol_mktime(12, 0, 0, GETPOST('startmonth'), GETPOST('startday'), GETPOST('startyear')); +$datee = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); +$amount = GETPOST('amount'); +$restrictive = GETPOST('restrictive'); + +$object = new ExpenseReportRule($db); +if (!empty($id)) +{ + $result = $object->fetch($id); + if ($result < 0) dol_print_error('', $object->error, $object->errors); +} + +// TODO do action +if ($action == 'save') +{ + $error = 0; + + // check parameters + if (empty($apply_to)) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpenseReportApplyTo")), null, 'errors'); + } + if (empty($fk_c_type_fees)) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpenseReportDomain")), null, 'errors'); + } + if (empty($code_expense_rules_type)) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpenseReportLimitOn")), null, 'errors'); + } + if (empty($dates)) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpenseReportDateStart")), null, 'errors'); + } + if (empty($datee)) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpenseReportDateEnd")), null, 'errors'); + } + if (empty($amount)) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpenseReportLimitAmount")), null, 'errors'); + } + + if (empty($error)) + { + $object->setValues($_POST); + + if($apply_to=='U'){ + $object->fk_user=$fk_user; + $object->fk_usergroup=0; + $object->is_for_all=0; + }elseif($apply_to=='G'){ + $object->fk_usergroup=$fk_usergroup; + $object->fk_user=0; + $object->is_for_all=0; + }elseif($apply_to=='A'){ + $object->is_for_all=1; + $object->fk_user=0; + $object->fk_usergroup=0; + } + + $object->dates = $dates; + $object->datee = $datee; + + $object->entity = $conf->entity; + + $res = $object->create($user); + if ($res > 0) setEventMessages($langs->trans('ExpenseReportRuleSave'), null); + else dol_print_error($object->db); + + header('Location: '.$_SERVER['PHP_SELF']); + exit; + } +} +elseif ($action == 'delete') +{ + // TODO add confirm + $res = $object->delete($user); + + if ($res < 0) dol_print_error($object->db); + + header('Location: '.$_SERVER['PHP_SELF']); + exit; +} + +$rules = ExpenseReportRule::getAllRule(); + +$tab_apply = array('A' => $langs->trans('All'), 'G' => $langs->trans('Group'), 'U' => $langs->trans('User')); +$tab_rules_type = array('EX_DAY' => $langs->trans('Day'), 'EX_MON' => $langs->trans('Month'), 'EX_YEA' => $langs->trans('Year'), 'EX_EXP' => $langs->trans('OnExpense')); + +/* + * View + */ + +llxHeader(); + +$form=new Form($db); + +$linkback=''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans("ExpenseReportsRulesSetup"),$linkback,'title_setup'); + +$head=expensereport_admin_prepare_head(); +dol_fiche_head($head, 'expenserules', $langs->trans("ExpenseReportsRules"), -1, 'trip'); + +echo $langs->trans('ExpenseReportRulesDesc'); + +if ($action != 'edit') +{ + echo '
'; + echo ''; + echo ''; + + echo ''; + + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + + $var=true; + echo ''; + echo ''; + + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + + echo '
'.$langs->trans('ExpenseReportApplyTo').''.$langs->trans('ExpenseReportDomain').''.$langs->trans('ExpenseReportLimitOn').''.$langs->trans('ExpenseReportDateStart').''.$langs->trans('ExpenseReportDateEnd').''.$langs->trans('ExpenseReportLimitAmount').''.$langs->trans('ExpenseReportRestrictive').' 
'; + echo '
'.$form->selectarray('apply_to', $tab_apply, '', 0).'
'; + echo '
'.$form->select_dolusers('', 'fk_user').'
'; + echo '
'.$form->select_dolgroups('', 'fk_usergroup').'
'; + echo '
'.$form->selectExpense('', 'fk_c_type_fees', 0, 1, 1).''.$form->selectarray('code_expense_rules_type', $tab_rules_type, '', 0).''.$form->select_date(strtotime(date('Y-m-01', dol_now())), 'start', '', '', 0, '', 1, 0, 1).''.$form->select_date(strtotime(date('Y-m-t', dol_now())), 'end', '', '', 0, '', 1, 0, 1).''.$conf->currency.''.$form->selectyesno('restrictive', 0, 1).'
'; + echo '
'; +} + + +echo '
'; +echo ''; + +if ($action == 'edit') +{ + echo ''; + echo ''; +} + +echo ''; + +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; + +$var=true; +foreach ($rules as $rule) +{ + echo ''; + + echo ''; + + + echo ''; + + + + echo ''; + + + echo ''; + + + echo ''; + + + echo ''; + + + echo ''; + + + echo ''; + + echo ''; + $var=!$var; +} + + +echo '
'.$langs->trans('ExpenseReportApplyTo').''.$langs->trans('ExpenseReportDomain').''.$langs->trans('ExpenseReportLimitOn').''.$langs->trans('ExpenseReportDateStart').''.$langs->trans('ExpenseReportDateEnd').''.$langs->trans('ExpenseReportLimitAmount').''.$langs->trans('ExpenseReportRestrictive').' 
'; + if ($action == 'edit' && $object->id == $rule->id) + { + $selected = ($object->is_for_all > 0) ? 'A' : ($object->fk_usergroup > 0 ? 'G' : 'U'); + echo '
'.$form->selectarray('apply_to', $tab_apply, $selected, 0).'
'; + echo '
'.$form->select_dolusers($object->fk_user, 'fk_user').'
'; + echo '
'.$form->select_dolgroups($object->fk_usergroup, 'fk_usergroup').'
'; + } + else + { + if ($rule->is_for_all > 0) echo $tab_apply['A']; + elseif ($rule->fk_usergroup > 0) echo $tab_apply['G'].' ('.$rule->getGroupLabel().')'; + elseif ($rule->fk_user > 0) echo $tab_apply['U'].' ('.$rule->getUserName().')'; + } + echo '
'; + if ($action == 'edit' && $object->id == $rule->id) + { + echo $form->selectExpense($object->fk_c_type_fees, 'fk_c_type_fees', 0, 1, 1); + } + else + { + if ($rule->fk_c_type_fees == -1) echo $langs->trans('AllExpenseReport'); + else + { + $key = getDictvalue(MAIN_DB_PREFIX.'c_type_fees', 'code', $rule->fk_c_type_fees, false, 'id'); + if ($key != $langs->trans($key)) echo $langs->trans($key); + else echo $langs->trans(getDictvalue(MAIN_DB_PREFIX.'c_type_fees', 'label', $rule->fk_c_type_fees, false, 'id')); // TODO check to return trans of 'code' + } + } + echo ''; + if ($action == 'edit' && $object->id == $rule->id) + { + echo $form->selectarray('code_expense_rules_type', $tab_rules_type, $object->code_expense_rules_type, 0); + } + else + { + echo $tab_rules_type[$rule->code_expense_rules_type]; + } + echo ''; + if ($action == 'edit' && $object->id == $rule->id) + { + echo $form->select_date(strtotime(date('Y-m-d', $object->dates)), 'start', '', '', 0, '', 1, 0, 1); + } + else + { + echo dol_print_date($rule->dates, 'day'); + } + echo ''; + if ($action == 'edit' && $object->id == $rule->id) + { + echo $form->select_date(strtotime(date('Y-m-d', $object->datee)), 'end', '', '', 0, '', 1, 0, 1); + } + else + { + echo dol_print_date($rule->datee, 'day'); + } + echo ''; + if ($action == 'edit' && $object->id == $rule->id) + { + echo ''.$conf->currency; + } + else + { + echo price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency); + } + echo ''; + if ($action == 'edit' && $object->id == $rule->id) + { + echo $form->selectyesno('restrictive', $object->restrictive, 1); + } + else + { + echo yn($rule->restrictive, 1, 1); + } + echo ''; + if ($object->id != $rule->id) + { + echo ''.img_edit().' '; + echo ''.img_delete().''; + } + else + { + echo ' '; + echo ''.$langs->trans('Cancel').''; + } + echo '
'; +echo '
'; + +echo ''; + +dol_fiche_end(); +llxFooter(); + +$db->close(); \ No newline at end of file diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php index 85ee8c09934..1f574175898 100644 --- a/htdocs/admin/facture.php +++ b/htdocs/admin/facture.php @@ -711,7 +711,7 @@ print '\n"; print ''; -$substitutionarray=pdf_getSubstitutionArray($langs); +$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; @@ -722,7 +722,7 @@ print '
'; print ''; print ''; print ''; -print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'

'.$htmltext).'
'; +print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='INVOICE_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { @@ -744,7 +744,7 @@ print ''; print ''; print ''; print ''; -print $form->textwithpicto($langs->trans("WatermarkOnDraftBill"), $htmltext); +print $form->textwithpicto($langs->trans("WatermarkOnDraftBill"), $htmltext, 1, 'help', '', 0, 2, 'watermarktooltip').'
'; print ''; print ''; print ''; diff --git a/htdocs/admin/fichinter.php b/htdocs/admin/fichinter.php index 374d72fa7bf..0ada37d2ffb 100644 --- a/htdocs/admin/fichinter.php +++ b/htdocs/admin/fichinter.php @@ -524,7 +524,6 @@ print "
"; /* * Other options - * */ print load_fiche_titre($langs->trans("OtherOptions"),'',''); @@ -535,7 +534,7 @@ print ''.$langs->trans("Value").''; print " \n"; print "\n"; -$substitutionarray=pdf_getSubstitutionArray($langs); +$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; @@ -545,7 +544,7 @@ print ''; print ''; print ''; print ''; -print $form->textwithpicto($langs->trans("FreeLegalTextOnInterventions"), $langs->trans("AddCRIfTooLong").'

'.$htmltext).'
'; +print $form->textwithpicto($langs->trans("FreeLegalTextOnInterventions"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='FICHINTER_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { @@ -568,7 +567,7 @@ print ""; print ''; print ""; print ''; -print $form->textwithpicto($langs->trans("WatermarkOnDraftInterventionCards"), $htmltext).'
'; +print $form->textwithpicto($langs->trans("WatermarkOnDraftInterventionCards"), $htmltext, 1, 'help', '', 0, 2, 'watermarktooltip').'
'; print ''; print ''; print ''; diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php index f764f40c054..256dd08f9a8 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -1,8 +1,8 @@ +/* Copyright (C) 2001-2005 Rodolphe Quiedeville * Copyright (C) 2004-2015 Laurent Destailleur - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2016 Juanjo Menent + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2016 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -47,29 +47,36 @@ if (! $user->admin) accessforbidden(); $action = GETPOST('action','aZ09'); - if (! defined("MAIN_MOTD")) define("MAIN_MOTD",""); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$contextpage=array('adminihm','globaladmin'); +$hookmanager->initHooks($contextpage); + /* * Action */ -if (GETPOST('cancel')) +$parameters=array(); +$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 (GETPOST('cancel','alpha')) { - $action=''; + $action=''; } if ($action == 'removebackgroundlogin' && ! empty($conf->global->MAIN_LOGIN_BACKGROUND)) { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $logofile=$conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND; - dol_delete_file($logofile); - dolibarr_del_const($db, "MAIN_LOGIN_BACKGROUND",$conf->entity); - $mysoc->logo=''; + $logofile=$conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND; + dol_delete_file($logofile); + dolibarr_del_const($db, "MAIN_LOGIN_BACKGROUND",$conf->entity); + $mysoc->logo=''; - /*$logosmallfile=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; + /*$logosmallfile=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; dol_delete_file($logosmallfile); dolibarr_del_const($db, "MAIN_INFO_SOCIETE_LOGO_SMALL",$conf->entity); $mysoc->logo_small=''; @@ -82,61 +89,65 @@ if ($action == 'removebackgroundlogin' && ! empty($conf->global->MAIN_LOGIN_BACK if ($action == 'update') { - dolibarr_set_const($db, "MAIN_LANG_DEFAULT", $_POST["main_lang_default"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MULTILANGS", $_POST["main_multilangs"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_LANG_DEFAULT", $_POST["MAIN_LANG_DEFAULT"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MULTILANGS", $_POST["MAIN_MULTILANGS"],'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_THEME", $_POST["main_theme"],'chaine',0,'',$conf->entity); $val=GETPOST('THEME_TOPMENU_DISABLE_IMAGE'); if (! $val) dolibarr_del_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', $conf->entity); - else dolibarr_set_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', GETPOST('THEME_TOPMENU_DISABLE_IMAGE'),'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', GETPOST('THEME_TOPMENU_DISABLE_IMAGE'),'chaine',0,'',$conf->entity); $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_BACKBODY'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_BACKBODY', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_BACKBODY', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TOPMENU_BACK1'),array())))); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TOPMENU_BACK1'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TOPMENU_BACK1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TOPMENU_BACK1', $val,'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_TOPMENU_BACK1', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_BACKTITLE1'),array())))); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_VERMENU_BACK1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_VERMENU_BACK1', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_VERMENU_BACK1', $val,'chaine',0,'',$conf->entity); + + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_BACKTITLE1'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_BACKTITLE1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_BACKTITLE1', $val,'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_BACKTITLE1', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'),array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR1', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'),array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR2', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR2', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR1', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR1', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR2', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR2', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'),array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR1', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'),array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR2', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR2', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR1', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR1', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR2', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR2', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLENOTAB'),array())))); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLENOTAB'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $val,'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $val,'chaine',0,'',$conf->entity); - if (GETPOST('THEME_ELDY_USE_HOVER') == '') dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", '0', 'chaine', 0, '', $conf->entity); // If empty, we set to '0' ('000000' is for black) + if (GETPOST('THEME_ELDY_USE_HOVER') == '') dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", '0', 'chaine', 0, '', $conf->entity); // If empty, we set to '0' ('000000' is for black) else dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", $_POST["THEME_ELDY_USE_HOVER"], 'chaine', 0, '', $conf->entity); $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTLINK'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTLINK', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TEXTLINK', $val,'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_TEXTLINK', $val,'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_SIZE_LISTE_LIMIT", $_POST["main_size_liste_limit"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_SIZE_SHORTLIST_LIMIT", $_POST["main_size_shortliste_limit"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_DISABLE_JAVASCRIPT", $_POST["main_disable_javascript"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_BUTTON_HIDE_UNAUTHORIZED", $_POST["MAIN_BUTTON_HIDE_UNAUTHORIZED"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_START_WEEK", $_POST["MAIN_START_WEEK"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_DAYS", $_POST["MAIN_DEFAULT_WORKING_DAYS"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_HOURS", $_POST["MAIN_DEFAULT_WORKING_HOURS"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_SHOW_LOGO", $_POST["MAIN_SHOW_LOGO"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_FIRSTNAME_NAME_POSITION", $_POST["MAIN_FIRSTNAME_NAME_POSITION"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_SIZE_LISTE_LIMIT", $_POST["main_size_liste_limit"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_SIZE_SHORTLIST_LIMIT", $_POST["main_size_shortliste_limit"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_DISABLE_JAVASCRIPT", $_POST["main_disable_javascript"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_BUTTON_HIDE_UNAUTHORIZED", $_POST["MAIN_BUTTON_HIDE_UNAUTHORIZED"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_START_WEEK", $_POST["MAIN_START_WEEK"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_DAYS", $_POST["MAIN_DEFAULT_WORKING_DAYS"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_HOURS", $_POST["MAIN_DEFAULT_WORKING_HOURS"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_SHOW_LOGO", $_POST["MAIN_SHOW_LOGO"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_FIRSTNAME_NAME_POSITION", $_POST["MAIN_FIRSTNAME_NAME_POSITION"],'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_HELPCENTER_DISABLELINK", $_POST["MAIN_HELPCENTER_DISABLELINK"],'chaine',0,'',0); // Param for all entities dolibarr_set_const($db, "MAIN_MOTD", dol_htmlcleanlastbr($_POST["main_motd"]),'chaine',0,'',$conf->entity); @@ -147,43 +158,43 @@ if ($action == 'update') $varforimage='imagebackground'; $dirforimage=$conf->mycompany->dir_output.'/logos/'; if ($_FILES[$varforimage]["tmp_name"]) { - if (preg_match('/([^\\/:]+)$/i',$_FILES[$varforimage]["name"],$reg)) - { - $original_file=$reg[1]; + if (preg_match('/([^\\/:]+)$/i',$_FILES[$varforimage]["name"],$reg)) + { + $original_file=$reg[1]; - $isimage=image_format_supported($original_file); - if ($isimage >= 0) - { - dol_syslog("Move file ".$_FILES[$varforimage]["tmp_name"]." to ".$dirforimage.$original_file); - if (! is_dir($dirforimage)) - { - dol_mkdir($dirforimage); - } - $result=dol_move_uploaded_file($_FILES[$varforimage]["tmp_name"],$dirforimage.$original_file,1,0,$_FILES[$varforimage]['error']); - if ($result > 0) - { - dolibarr_set_const($db, "MAIN_LOGIN_BACKGROUND",$original_file,'chaine',0,'',$conf->entity); - } - else if (preg_match('/^ErrorFileIsInfectedWithAVirus/',$result)) - { - $error++; - $langs->load("errors"); - $tmparray=explode(':',$result); - setEventMessages($langs->trans('ErrorFileIsInfectedWithAVirus',$tmparray[1]), null, 'errors'); - } - else - { - $error++; - setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors'); - } - } - else - { - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorBadImageFormat"), null, 'errors'); - } - } + $isimage=image_format_supported($original_file); + if ($isimage >= 0) + { + dol_syslog("Move file ".$_FILES[$varforimage]["tmp_name"]." to ".$dirforimage.$original_file); + if (! is_dir($dirforimage)) + { + dol_mkdir($dirforimage); + } + $result=dol_move_uploaded_file($_FILES[$varforimage]["tmp_name"],$dirforimage.$original_file,1,0,$_FILES[$varforimage]['error']); + if ($result > 0) + { + dolibarr_set_const($db, "MAIN_LOGIN_BACKGROUND",$original_file,'chaine',0,'',$conf->entity); + } + else if (preg_match('/^ErrorFileIsInfectedWithAVirus/',$result)) + { + $error++; + $langs->load("errors"); + $tmparray=explode(':',$result); + setEventMessages($langs->trans('ErrorFileIsInfectedWithAVirus',$tmparray[1]), null, 'errors'); + } + else + { + $error++; + setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors'); + } + } + else + { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorBadImageFormat"), null, 'errors'); + } + } } @@ -214,59 +225,59 @@ print "
\n"; if ($action == 'edit') // Edit { - //WYSIWYG Editor - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + //WYSIWYG Editor + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - clearstatcache(); + clearstatcache(); - print '
'; - print ''; - print ''; + print '
'; + print '
'.$langs->trans("Language").'
'; + print ''; print ''; print ''; - // Default language - print ''; + // Default language + print ''; print ''; print ''; // Multilingual GUI - print ''; + print ''; print ''; print ''; print '
'.$langs->trans("Language").' 
'.$langs->trans("DefaultLanguage").''; - print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT, 'main_lang_default', 1, 0, 0, 0, 0, 'minwidth300'); - print '
'.$langs->trans("DefaultLanguage").''; + print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT, 'MAIN_LANG_DEFAULT', 1, 0, 0, 0, 0, 'minwidth300'); + print ' 
'.$langs->trans("EnableMultilangInterface").''; - print $form->selectyesno('main_multilangs',$conf->global->MAIN_MULTILANGS,1); - print '
'.$langs->trans("EnableMultilangInterface").''; + print $form->selectyesno('MAIN_MULTILANGS',$conf->global->MAIN_MULTILANGS,1); + print ' 

'."\n"; - // Themes and themes options - show_theme(null,1); - print '
'; + // Themes and themes options + show_theme(null,1); + print '
'; - // Other - print ''; - print ''; + // Other + print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'; + print ''; print ''; print ''; // Max size of lists - print ''; + print ''; print ''; print ''; // Max size of short lists on customer card - print ''; + print ''; print ''; print ''; - // show input border - /* + // show input border + /* print ''; @@ -275,38 +286,38 @@ if ($action == 'edit') // Edit */ // Disable javascript and ajax - print ''; + print ''; print ''; print ''; - // First day for weeks - print ''; + // First day for weeks + print ''; print ''; print ''; - // DefaultWorkingDays - print ''; + // DefaultWorkingDays + print ''; print ''; print ''; - // DefaultWorkingHours - print ''; + // DefaultWorkingHours + print ''; print ''; print ''; // Firstname/Name - print ''; + print $form->selectarray('MAIN_FIRSTNAME_NAME_POSITION',$array,(isset($conf->global->MAIN_FIRSTNAME_NAME_POSITION)?$conf->global->MAIN_FIRSTNAME_NAME_POSITION:0)); + print ''; print ''; print ''; @@ -342,28 +353,27 @@ if ($action == 'edit') // Edit print ''; // Hide wiki link on login page - print ''; + print ''; print ''; print ''; // Message of the day on home page - $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object')); - complete_substitutions_array($substitutionarray, $langs); - $substitutionarray['__(AnyTranslationKey)__']=$langs->trans('TranslationKey'); + $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount')); + complete_substitutions_array($substitutionarray, $langs); - print ''."\n"; @@ -379,16 +389,15 @@ if ($action == 'edit') // Edit print ''; // Message on login page - $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','user')); - complete_substitutions_array($substitutionarray, $langs); - $substitutionarray['__(AnyTranslationKey)__']=$langs->trans('TranslationKey'); - print ''; @@ -420,31 +429,31 @@ if ($action == 'edit') // Edit print '
'.$langs->trans("Parameters").''.$langs->trans("Value").' 
'.$langs->trans("DefaultMaxSizeList").'
'.$langs->trans("DefaultMaxSizeList").' 
'.$langs->trans("DefaultMaxSizeShortList").'
'.$langs->trans("DefaultMaxSizeShortList").' 
'.$langs->trans("showInputBorder").''; print $form->selectyesno('main_showInputBorder',isset($conf->global->THEME_ELDY_SHOW_BORDER_INPUT)?$conf->global->THEME_ELDY_SHOW_BORDER_INPUT:0,1); print '
'.$langs->trans("DisableJavascript").''; - print $form->selectyesno('main_disable_javascript',isset($conf->global->MAIN_DISABLE_JAVASCRIPT)?$conf->global->MAIN_DISABLE_JAVASCRIPT:0,1); - print '
'.$langs->trans("DisableJavascript").''; + print $form->selectyesno('main_disable_javascript',isset($conf->global->MAIN_DISABLE_JAVASCRIPT)?$conf->global->MAIN_DISABLE_JAVASCRIPT:0,1); + print ' 
'.$langs->trans("WeekStartOnDay").''; - print $formother->select_dayofweek((isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1'),'MAIN_START_WEEK',0); - print '
'.$langs->trans("WeekStartOnDay").''; + print $formother->select_dayofweek((isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1'),'MAIN_START_WEEK',0); + print ' 
'.$langs->trans("DefaultWorkingDays").''; - print ''; - print '
'.$langs->trans("DefaultWorkingDays").''; + print ''; + print ' 
'.$langs->trans("DefaultWorkingHours").''; - print ''; - print '
'.$langs->trans("DefaultWorkingHours").''; + print ''; + print ' 
'.$langs->trans("FirstnameNamePosition").''; + print '
'.$langs->trans("FirstnameNamePosition").''; $array=array(0=>$langs->trans("Firstname").' '.$langs->trans("Lastname"),1=>$langs->trans("Lastname").' '.$langs->trans("Firstname")); - print $form->selectarray('MAIN_FIRSTNAME_NAME_POSITION',$array,(isset($conf->global->MAIN_FIRSTNAME_NAME_POSITION)?$conf->global->MAIN_FIRSTNAME_NAME_POSITION:0)); - print ' 
'.$langs->trans("DisableLinkToHelp",img_picto('',DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/helpdoc.png','',1)).''; - print $form->selectyesno('MAIN_HELP_DISABLELINK', isset($conf->global->MAIN_HELP_DISABLELINK)?$conf->global->MAIN_HELP_DISABLELINK:0,1); - print '
'.$langs->trans("DisableLinkToHelp",img_picto('',DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/helpdoc.png','',1)).''; + print $form->selectyesno('MAIN_HELP_DISABLELINK', isset($conf->global->MAIN_HELP_DISABLELINK)?$conf->global->MAIN_HELP_DISABLELINK:0,1); + print ' 
'; - $texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'
'; - foreach($substitutionarray as $key => $val) - { - $texthelp.=$key.'
'; - } - print $form->textwithpicto($langs->trans("MessageOfDay"), $texthelp, 1, 'help', '', 0, 2, ''); + print '
'; + $texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'
'; + foreach($substitutionarray as $key => $val) + { + $texthelp.=$key.'
'; + } + print $form->textwithpicto($langs->trans("MessageOfDay"), $texthelp, 1, 'help', '', 0, 2, 'tooltipmessageofday'); - print '
'; + print ''; - $doleditor = new DolEditor('main_motd', (isset($conf->global->MAIN_MOTD)?$conf->global->MAIN_MOTD:''), '', 142, 'dolibarr_notes', 'In', false, true, true, ROWS_4, '90%'); + $doleditor = new DolEditor('main_motd', (isset($conf->global->MAIN_MOTD)?$conf->global->MAIN_MOTD:''), '', 142, 'dolibarr_notes', 'In', false, true, true, ROWS_4, '90%'); $doleditor->Create(); print '
'; + $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount','user')); + complete_substitutions_array($substitutionarray, $langs); + print '
'; $texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'
'; foreach($substitutionarray as $key => $val) { - $texthelp.=$key.'
'; + $texthelp.=$key.'
'; } - print $form->textwithpicto($langs->trans("MessageLogin"), $texthelp, 1, 'help', '', 0, 2, ''); + print $form->textwithpicto($langs->trans("MessageLogin"), $texthelp, 1, 'help', '', 0, 2, 'tooltipmessagelogin'); print '
'; $doleditor = new DolEditor('main_home', (isset($conf->global->MAIN_HOME)?$conf->global->MAIN_HOME:''), '', 142, 'dolibarr_notes', 'In', false, true, true, ROWS_4, '90%'); $doleditor->Create(); @@ -403,16 +412,16 @@ if ($action == 'edit') // Edit // Background print '
'; - print '
'; + print '
'; print ''; if (! empty($conf->global->MAIN_LOGIN_BACKGROUND)) { - print ''.img_delete($langs->trans("Delete")).''; - if (file_exists($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND)) { - print '   '; - print ''; - } + print ''.img_delete($langs->trans("Delete")).''; + if (file_exists($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND)) { + print '   '; + print ''; + } } else { - print ''; + print ''; } print '
'; print '
'."\n"; - print '
'; - print ''; - print '   '; - print ''; - print '
'; + print '
'; + print ''; + print '   '; + print ''; + print '
'; - print ''; + print ''; } else // Show { - // Language - print ''; - print ''; + // Language + print '
'.$langs->trans("Language").' 
'; + print ''; - print ''; + print ''; print ''; print ""; - print ''; + print ''; print ''; print ""; @@ -452,19 +461,19 @@ else // Show // Themes - show_theme(null,0); - print '
'; + show_theme(null,0); + print '
'; - // Other - print '
'.$langs->trans("Language").' 
'.$langs->trans("DefaultLanguage").''; - $s=picto_from_langcode($conf->global->MAIN_LANG_DEFAULT); - print ($s?$s.' ':''); - print ($conf->global->MAIN_LANG_DEFAULT=='auto'?$langs->trans("AutoDetectLang"):$langs->trans("Language_".$conf->global->MAIN_LANG_DEFAULT)); - print '
'.$langs->trans("DefaultLanguage").''; + $s=picto_from_langcode($conf->global->MAIN_LANG_DEFAULT); + print ($s?$s.' ':''); + print ($conf->global->MAIN_LANG_DEFAULT=='auto'?$langs->trans("AutoDetectLang"):$langs->trans("Language_".$conf->global->MAIN_LANG_DEFAULT)); + print ''; - if ($user->admin && $conf->global->MAIN_LANG_DEFAULT!='auto') print info_admin($langs->trans("SubmitTranslation".($conf->global->MAIN_LANG_DEFAULT=='en_US'?'ENUS':''),$conf->global->MAIN_LANG_DEFAULT),1); + if ($user->admin && $conf->global->MAIN_LANG_DEFAULT!='auto') print info_admin($langs->trans("SubmitTranslation".($conf->global->MAIN_LANG_DEFAULT=='en_US'?'ENUS':''),$conf->global->MAIN_LANG_DEFAULT),1); print '
'.$langs->trans("EnableMultilangInterface").'' . yn($conf->global->MAIN_MULTILANGS) . '
'.$langs->trans("EnableMultilangInterface").'' . yn($conf->global->MAIN_MULTILANGS) . ' 
'; - print ''; + // Other + print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'; + print ''; - print ''; + print ''; print ''; print ""; - print ''; + print ''; print ''; print ""; @@ -475,38 +484,38 @@ else // Show print ""; */ - // Disable javascript/ajax - print '"; - print ''; - print ""; + // Disable javascript/ajax + print '"; + print ''; + print ""; // First day for weeks - print ''; + print ''; print ''; print ''; - // DefaultWorkingDays - print ''; + // DefaultWorkingDays + print ''; print ''; print ''; - // DefaultWorkingHours - print ''; + // DefaultWorkingHours + print ''; print ''; print ''; // Firstname / Name position - print ''; + print ''; print ''; print ''; @@ -515,8 +524,8 @@ else // Show print yn((isset($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)?$conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED:0),1); print ''; - // Show logo - print ''; + // Show logo + print ''; print ''; print ""; @@ -529,62 +538,62 @@ else // Show print ''; */ - // Show bugtrack link + // Show bugtrack link print '"; print ''; print ""; - // Link to wiki help - print ''; + // Link to wiki help + print ''; - // Message of the day - print ''."\n"; + // Message of the day + print ''."\n"; - print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'.$langs->trans("DefaultMaxSizeList").'' . $conf->global->MAIN_SIZE_LISTE_LIMIT . '
'.$langs->trans("DefaultMaxSizeList").'' . $conf->global->MAIN_SIZE_LISTE_LIMIT . ' 
'.$langs->trans("DefaultMaxSizeShortList").'' . $conf->global->MAIN_SIZE_SHORTLIST_LIMIT . '
'.$langs->trans("DefaultMaxSizeShortList").'' . $conf->global->MAIN_SIZE_SHORTLIST_LIMIT . ' 
'.$langs->trans("DisableJavascript").''; - print yn($conf->global->MAIN_DISABLE_JAVASCRIPT)." 
'.$langs->trans("DisableJavascript").''; + print yn($conf->global->MAIN_DISABLE_JAVASCRIPT)." 
'.$langs->trans("WeekStartOnDay").''; - print $langs->trans("Day".(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1')); - print '
'.$langs->trans("WeekStartOnDay").''; + print $langs->trans("Day".(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1')); + print ' 
'.$langs->trans("DefaultWorkingDays").''; - print isset($conf->global->MAIN_DEFAULT_WORKING_DAYS)?$conf->global->MAIN_DEFAULT_WORKING_DAYS:'1-5'; - print '
'.$langs->trans("DefaultWorkingDays").''; + print isset($conf->global->MAIN_DEFAULT_WORKING_DAYS)?$conf->global->MAIN_DEFAULT_WORKING_DAYS:'1-5'; + print ' 
'.$langs->trans("DefaultWorkingHours").''; - print isset($conf->global->MAIN_DEFAULT_WORKING_HOURS)?$conf->global->MAIN_DEFAULT_WORKING_HOURS:'9-18'; - print '
'.$langs->trans("DefaultWorkingHours").''; + print isset($conf->global->MAIN_DEFAULT_WORKING_HOURS)?$conf->global->MAIN_DEFAULT_WORKING_HOURS:'9-18'; + print ' 
'.$langs->trans("FirstnameNamePosition").''; - if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { print $langs->trans("Firstname").' '.$langs->trans("Lastname"); } - else { print $langs->trans("Lastname").' '.$langs->trans("Firstname"); } - print '
'.$langs->trans("FirstnameNamePosition").''; + if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { print $langs->trans("Firstname").' '.$langs->trans("Lastname"); } + else { print $langs->trans("Lastname").' '.$langs->trans("Firstname"); } + print ' 
'.$langs->trans("EnableShowLogo").'' . yn($conf->global->MAIN_SHOW_LOGO) . '
'.$langs->trans("EnableShowLogo").'' . yn($conf->global->MAIN_SHOW_LOGO) . ' 
'.$langs->trans("ShowBugTrackLink", $langs->transnoentitiesnoconv("FindBug")).''; print yn($conf->global->MAIN_BUGTRACK_ENABLELINK)." 
'.$langs->trans("DisableLinkToHelp",img_picto('',DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/helpdoc.png','',1)).''; - print yn((isset($conf->global->MAIN_HELP_DISABLELINK)?$conf->global->MAIN_HELP_DISABLELINK:0),1); - print '
'.$langs->trans("DisableLinkToHelp",img_picto('',DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/helpdoc.png','',1)).''; + print yn((isset($conf->global->MAIN_HELP_DISABLELINK)?$conf->global->MAIN_HELP_DISABLELINK:0),1); + print '
'.$langs->trans("MessageOfDay").''; - if (isset($conf->global->MAIN_MOTD)) print dol_htmlcleanlastbr($conf->global->MAIN_MOTD); - else print ' '; - print '
'.$langs->trans("MessageOfDay").''; + if (isset($conf->global->MAIN_MOTD)) print dol_htmlcleanlastbr($conf->global->MAIN_MOTD); + else print ' '; + print '
'."\n"; + print ''."\n"; - print '
'; + print '
'; - // Login page - print ''; - print ''; + // Login page + print '
'.$langs->trans("LoginPage").' 
'; + print ''; - // Message login - print ''."\n"; + // Message login + print ''."\n"; // Link to help center - print ''; + print ''; - // Background login - print ''; + // Background login + print ''; - print '
'.$langs->trans("LoginPage").' 
'.$langs->trans("MessageLogin").''; - if (isset($conf->global->MAIN_HOME)) print dol_htmlcleanlastbr($conf->global->MAIN_HOME); - else print ' '; - print '
'.$langs->trans("MessageLogin").''; + if (isset($conf->global->MAIN_HOME)) print dol_htmlcleanlastbr($conf->global->MAIN_HOME); + else print ' '; + print '
'.$langs->trans("DisableLinkToHelpCenter").''; - print yn((isset($conf->global->MAIN_HELPCENTER_DISABLELINK)?$conf->global->MAIN_HELPCENTER_DISABLELINK:0),1); - print '
'.$langs->trans("DisableLinkToHelpCenter").''; + print yn((isset($conf->global->MAIN_HELPCENTER_DISABLELINK)?$conf->global->MAIN_HELPCENTER_DISABLELINK:0),1); + print '
'.$langs->trans("BackgroundImageLogin").''; - print '
'; - print $conf->global->MAIN_LOGIN_BACKGROUND; - if ($conf->global->MAIN_LOGIN_BACKGROUND && is_file($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND)) - { - print ''; - } - else - { - print ''; - } - print '
'; - print '
'.$langs->trans("BackgroundImageLogin").''; + print '
'; + print $conf->global->MAIN_LOGIN_BACKGROUND; + if ($conf->global->MAIN_LOGIN_BACKGROUND && is_file($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND)) + { + print ''; + } + else + { + print ''; + } + print '
'; + print '
'."\n"; + print ''."\n"; - print '
'; - print ''.$langs->trans("Modify").''; - print '
'; + print '
'; + print ''.$langs->trans("Modify").''; + print '
'; } diff --git a/htdocs/admin/ldap.php b/htdocs/admin/ldap.php index dd084894b3d..f9b863e487e 100644 --- a/htdocs/admin/ldap.php +++ b/htdocs/admin/ldap.php @@ -1,10 +1,10 @@ - * Copyright (C) 2004 Sebastien Di Cintio - * Copyright (C) 2004 Benoit Mortier - * Copyright (C) 2005 Regis Houssin - * Copyright (C) 2006-2011 Laurent Destailleur - * Copyright (C) 2011-2013 Juanjo Menent +/* Copyright (C) 2004 Rodolphe Quiedeville + * Copyright (C) 2004 Sebastien Di Cintio + * Copyright (C) 2004 Benoit Mortier + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2006-2011 Laurent Destailleur + * Copyright (C) 2011-2013 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -34,46 +34,55 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; $langs->load("admin"); if (!$user->admin) - accessforbidden(); + accessforbidden(); - $action = GETPOST('action','aZ09'); +$action = GETPOST('action','aZ09'); + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('adminldap','globaladmin')); /* * Actions */ -if ($action == 'setvalue' && $user->admin) +$parameters=array(); +$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)) { - $error=0; + if ($action == 'setvalue' && $user->admin) + { + $error=0; - $db->begin(); - if (! dolibarr_set_const($db, 'LDAP_SERVER_TYPE',GETPOST("type"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_SERVER_PROTOCOLVERSION',GETPOST("LDAP_SERVER_PROTOCOLVERSION"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_SERVER_HOST',GETPOST("host"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_SERVER_HOST_SLAVE',GETPOST("slave"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_SERVER_PORT',GETPOST("port"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_SERVER_DN',GETPOST("dn"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_ADMIN_DN',GETPOST("admin"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_ADMIN_PASS',GETPOST("pass"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_SERVER_USE_TLS',GETPOST("usetls"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_SYNCHRO_ACTIVE',GETPOST("activesynchro"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_CONTACT_ACTIVE',GETPOST("activecontact"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_MEMBER_ACTIVE',GETPOST("activemembers"),'chaine',0,'',$conf->entity)) $error++; + $db->begin(); + if (! dolibarr_set_const($db, 'LDAP_SERVER_TYPE',GETPOST("type"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_SERVER_PROTOCOLVERSION',GETPOST("LDAP_SERVER_PROTOCOLVERSION"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_SERVER_HOST',GETPOST("host"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_SERVER_HOST_SLAVE',GETPOST("slave"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_SERVER_PORT',GETPOST("port"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_SERVER_DN',GETPOST("dn"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_ADMIN_DN',GETPOST("admin"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_ADMIN_PASS',GETPOST("pass"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_SERVER_USE_TLS',GETPOST("usetls"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_SYNCHRO_ACTIVE',GETPOST("activesynchro"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_CONTACT_ACTIVE',GETPOST("activecontact"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_MEMBER_ACTIVE',GETPOST("activemembers"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_ACTIVE',GETPOST("activememberstypes"),'chaine',0,'',$conf->entity)) $error++; - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } - else - { - $db->rollback(); - dol_print_error($db); - } + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } + else + { + $db->rollback(); + dol_print_error($db); + } + } } - - /* * View */ @@ -127,7 +136,6 @@ print ''; // Synchro contact active if (! empty($conf->societe->enabled)) { - print ''.$langs->trans("LDAPDnContactActive").''; $arraylist=array(); $arraylist['0']=$langs->trans("No"); @@ -139,7 +147,6 @@ if (! empty($conf->societe->enabled)) // Synchro member active if (! empty($conf->adherent->enabled)) { - print ''.$langs->trans("LDAPDnMemberActive").''; $arraylist=array(); $arraylist['0']=$langs->trans("No"); @@ -149,6 +156,23 @@ if (! empty($conf->adherent->enabled)) print ''.$langs->trans("LDAPDnMemberActiveExample").''; } +// Synchro member type active +if (! empty($conf->adherent->enabled)) +{ + print ''.$langs->trans("LDAPDnMemberTypeActive").''; + $arraylist=array(); + $arraylist['0']=$langs->trans("No"); + $arraylist['1']=$langs->trans("DolibarrToLDAP"); + $arraylist['ldap2dolibarr']=$langs->trans("LDAPToDolibarr").' ('.$langs->trans("SupportedForLDAPImportScriptOnly").')'; + print $form->selectarray('activememberstypes',$arraylist,$conf->global->LDAP_MEMBER_TYPE_ACTIVE); + print ''.$langs->trans("LDAPDnMemberTypeActiveExample").''; +} + +// Fields from hook +$parameters=array(); +$reshook=$hookmanager->executeHooks('addAdminLdapOptions',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + print ''; print ''.$langs->trans("Parameter").''; print ''.$langs->trans("Value").''; @@ -193,11 +217,11 @@ print ''.$langs->trans("LDAPServerExample").''; print ''.$langs->trans("LDAPServerPort").''; if (! empty($conf->global->LDAP_SERVER_PORT)) { - print ''; + print ''; } else { - print ''; + print ''; } print ''.$langs->trans("LDAPServerPortExample").''; diff --git a/htdocs/admin/ldap_groups.php b/htdocs/admin/ldap_groups.php index fc68d815439..d431a7aaf30 100644 --- a/htdocs/admin/ldap_groups.php +++ b/htdocs/admin/ldap_groups.php @@ -220,8 +220,9 @@ if (function_exists("ldap_connect")) $dn=$object->_load_ldap_dn($info); // Get a gid number for objectclass PosixGroup - if(in_array('posixGroup',$info['objectclass'])) - $info['gidNumber'] = $ldap->getNextGroupGid(); + if (in_array('posixGroup',$info['objectclass'])) { + $info['gidNumber'] = $ldap->getNextGroupGid('LDAP_KEY_GROUPS'); + } $result1=$ldap->delete($dn); // To be sure to delete existing records $result2=$ldap->add($dn,$info,$user); // Now the test diff --git a/htdocs/admin/ldap_members.php b/htdocs/admin/ldap_members.php index cad37cc4ccc..0dccb9967fe 100644 --- a/htdocs/admin/ldap_members.php +++ b/htdocs/admin/ldap_members.php @@ -1,10 +1,10 @@ - * Copyright (C) 2004 Sebastien Di Cintio - * Copyright (C) 2004 Benoit Mortier - * Copyright (C) 2005 Regis Houssin - * Copyright (C) 2006-2008 Laurent Destailleur - * Copyright (C) 2011-2013 Juanjo Menent +/* Copyright (C) 2004 Rodolphe Quiedeville + * Copyright (C) 2004 Sebastien Di Cintio + * Copyright (C) 2004 Benoit Mortier + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2006-2008 Laurent Destailleur + * Copyright (C) 2011-2013 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -66,8 +66,9 @@ if ($action == 'setvalue' && $user->admin) if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PHONE',GETPOST("fieldphone"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PHONE_PERSO',GETPOST("fieldphoneperso"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_MOBILE',GETPOST("fieldmobile"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_SKYPE',GETPOST("fieldskype"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_SKYPE',GETPOST("fieldskype"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_FAX',GETPOST("fieldfax"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_COMPANY',GETPOST("fieldcompany"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_ADDRESS',GETPOST("fieldaddress"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_ZIP',GETPOST("fieldzip"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_TOWN',GETPOST("fieldtown"),'chaine',0,'',$conf->entity)) $error++; @@ -84,22 +85,22 @@ if ($action == 'setvalue' && $user->admin) if (! dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE', GETPOST("fieldlastsubscriptiondate"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT', GETPOST("fieldlastsubscriptionamount"),'chaine',0,'',$conf->entity)) $error++; - // This one must be after the others - $valkey=''; - $key=GETPOST("key"); - if ($key) $valkey=$conf->global->$key; - if (! dolibarr_set_const($db, 'LDAP_KEY_MEMBERS',$valkey,'chaine',0,'',$conf->entity)) $error++; + // This one must be after the others + $valkey=''; + $key=GETPOST("key"); + if ($key) $valkey=$conf->global->$key; + if (! dolibarr_set_const($db, 'LDAP_KEY_MEMBERS',$valkey,'chaine',0,'',$conf->entity)) $error++; - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } - else - { - $db->rollback(); - dol_print_error($db); - } + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } + else + { + $db->rollback(); + dol_print_error($db); + } } @@ -282,6 +283,14 @@ print ''.$langs->trans("LDAPFieldFaxExample").''; print ' '; print ''; +// Company + +print ''.$langs->trans("LDAPFieldCompany").''; +print ''; +print ''.$langs->trans("LDAPFieldCompanyExample").''; +print ' '; +print ''; + // Address print ''.$langs->trans("LDAPFieldAddress").''; diff --git a/htdocs/admin/ldap_members_types.php b/htdocs/admin/ldap_members_types.php new file mode 100644 index 00000000000..47286dc98da --- /dev/null +++ b/htdocs/admin/ldap_members_types.php @@ -0,0 +1,252 @@ + + * Copyright (C) 2004 Sebastien Di Cintio + * Copyright (C) 2004 Benoit Mortier + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2006-2011 Laurent Destailleur + * Copyright (C) 2011-2013 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/admin/ldap_members_types.php + * \ingroup ldap + * \brief Page to setup LDAP synchronization for members types + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; + +$langs->load("admin"); +$langs->load("errors"); + +if (!$user->admin) + accessforbidden(); + +$action = GETPOST('action','aZ09'); + + +/* + * Actions + */ + +if ($action == 'setvalue' && $user->admin) +{ + $error=0; + $db->begin(); + + if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_DN',GETPOST("membertype"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_OBJECT_CLASS',GETPOST("objectclass"),'chaine',0,'',$conf->entity)) $error++; + + if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_FULLNAME',GETPOST("fieldfullname"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_DESCRIPTION',GETPOST("fielddescription"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS',GETPOST("fieldmembertypemembers"),'chaine',0,'',$conf->entity)) $error++; + + // This one must be after the others + $valkey=''; + $key=GETPOST("key"); + if ($key) $valkey=$conf->global->$key; + if (! dolibarr_set_const($db, 'LDAP_KEY_MEMBERS_TYPES',$valkey,'chaine',0,'',$conf->entity)) $error++; + + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } + else + { + $db->rollback(); + dol_print_error($db); + } +} + + + +/* + * View + */ + +llxHeader('',$langs->trans("LDAPSetup"),'EN:Module_LDAP_En|FR:Module_LDAP|ES:Módulo_LDAP'); +$linkback=''.$langs->trans("BackToModuleList").''; + +print load_fiche_titre($langs->trans("LDAPSetup"),$linkback,'title_setup'); + +$head = ldap_prepare_head(); + +// Test si fonction LDAP actives +if (! function_exists("ldap_connect")) +{ + setEventMessages($langs->trans("LDAPFunctionsNotAvailableOnPHP"), null, 'errors'); +} + +dol_fiche_head($head, 'memberstypes', $langs->trans("LDAPSetup"), -1); + + +print $langs->trans("LDAPDescMembersTypes").'
'; +print '
'; + + +print '
'; +print ''; + +$form=new Form($db); + +print ''; +$var=true; + +print ''; +print ''; +print "\n"; + +// DN pour les types de membres + +print ''; +print ''; +print ''; + +// List of object class used to define attributes in structure + +print ''; +print ''; +print ''; + +print '
'.$langs->trans("LDAPSynchronizeMembersTypes").'
'.$langs->trans("LDAPMemberTypeDn").''; +print ''; +print ''.$langs->trans("LDAPMemberTypepDnExample").' 
'.$langs->trans("LDAPMemberTypeObjectClassList").''; +print ''; +print ''.$langs->trans("LDAPMemberTypeObjectClassListExample").' 
'; +print '
'; +print ''; +$var=true; + +print ''; +print ''; +print ''; +print ''; +print "\n"; + +// Filtre + +// Common name + +print ''; +print '"; +print ''; + +// Description + +print ''; +print '"; +print ''; + +// User group + +print ''; +print '"; +print ''; + +print '
'.$langs->trans("LDAPDolibarrMapping").''.$langs->trans("LDAPLdapMapping").''.$langs->trans("LDAPNamingAttribute").'
'.$langs->trans("LDAPFieldName").''; +print ''; +print ''.$langs->trans("LDAPFieldCommonNameExample").'global->LDAP_KEY_MEMBERS_TYPES && $conf->global->LDAP_KEY_MEMBERS_TYPES==$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME)?' checked':'').">
'.$langs->trans("LDAPFieldDescription").''; +print ''; +print ''.$langs->trans("LDAPFieldDescriptionExample").'global->LDAP_KEY_MEMBERS_TYPES && $conf->global->LDAP_KEY_MEMBER_TYPES==$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION)?' checked':'').">
'.$langs->trans("LDAPFieldGroupMembers").''; +print ''; +print ''.$langs->trans("LDAPFieldGroupMembersExample").'global->LDAP_KEY_MEMBERS_TYPES && $conf->global->LDAP_KEY_MEMBERS_TYPES==$conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS)?' checked':'').">
'; + +print info_admin($langs->trans("LDAPDescValues")); + +dol_fiche_end(); + +print '
'; + +print '
'; + + +/* + * Test de la connexion + */ +if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == '1') +{ + $butlabel=$langs->trans("LDAPTestSynchroMemberType"); + $testlabel='testmembertype'; + $key=$conf->global->LDAP_KEY_MEMBERS_TYPES; + $dn=$conf->global->LDAP_MEMBER_TYPE_DN; + $objectclass=$conf->global->LDAP_MEMBER_TYPE_OBJECT_CLASS; + + show_ldap_test_button($butlabel,$testlabel,$key,$dn,$objectclass); +} + +if (function_exists("ldap_connect")) +{ + if ($_GET["action"] == 'testmembertype') + { + // Creation objet + $object=new AdherentType($db); + $object->initAsSpecimen(); + + // Test synchro + $ldap=new Ldap(); + $result=$ldap->connect_bind(); + + if ($result > 0) + { + $info=$object->_load_ldap_info(); + $dn=$object->_load_ldap_dn($info); + + // Get a gid number for objectclass PosixGroup + if (in_array('posixGroup',$info['objectclass'])) { + $info['gidNumber'] = $ldap->getNextGroupGid('LDAP_KEY_MEMBERS_TYPES'); + } + + $result1=$ldap->delete($dn); // To be sure to delete existing records + $result2=$ldap->add($dn,$info,$user); // Now the test + $result3=$ldap->delete($dn); // Clean what we did + + if ($result2 > 0) + { + print img_picto('','info').' '; + print ''.$langs->trans("LDAPSynchroOK").'
'; + } + else + { + print img_picto('','error').' '; + print ''.$langs->trans("LDAPSynchroKOMayBePermissions"); + print ': '.$ldap->error; + print '
'; + print $langs->trans("ErrorLDAPMakeManualTest",$conf->ldap->dir_temp).'
'; + } + + print "
\n"; + print "LDAP input file used for test:

\n"; + print nl2br($ldap->dump_content($dn,$info)); + print "\n
"; + } + else + { + print img_picto('','error').' '; + print ''.$langs->trans("LDAPSynchroKO"); + print ': '.$ldap->error; + print '
'; + print $langs->trans("ErrorLDAPMakeManualTest",$conf->ldap->dir_temp).'
'; + } + } +} + +llxFooter(); +$db->close(); diff --git a/htdocs/admin/ldap_users.php b/htdocs/admin/ldap_users.php index a0866c1305a..8be03267783 100644 --- a/htdocs/admin/ldap_users.php +++ b/htdocs/admin/ldap_users.php @@ -63,28 +63,33 @@ if ($action == 'setvalue' && $user->admin) if (! dolibarr_set_const($db, 'LDAP_FIELD_MAIL',GETPOST("fieldmail"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_PHONE',GETPOST("fieldphone"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_MOBILE',GETPOST("fieldmobile"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_FIELD_SKYPE',GETPOST("fieldskype"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_SKYPE',GETPOST("fieldskype"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_FAX',GETPOST("fieldfax"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_COMPANY',GETPOST("fieldcompany"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_ADDRESS',GETPOST("fieldaddress"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_ZIP',GETPOST("fieldzip"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_TOWN',GETPOST("fieldtown"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_COUNTRY',GETPOST("fieldcountry"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_DESCRIPTION',GETPOST("fielddescription"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_SID',GETPOST("fieldsid"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_TITLE',GETPOST("fieldtitle"),'chaine',0,'',$conf->entity)) $error++; - // This one must be after the others - $valkey=''; - $key=GETPOST("key"); - if ($key) $valkey=$conf->global->$key; - if (! dolibarr_set_const($db, 'LDAP_KEY_USERS',$valkey,'chaine',0,'',$conf->entity)) $error++; + // This one must be after the others + $valkey=''; + $key=GETPOST("key"); + if ($key) $valkey=$conf->global->$key; + if (! dolibarr_set_const($db, 'LDAP_KEY_USERS',$valkey,'chaine',0,'',$conf->entity)) $error++; - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } - else - { - $db->rollback(); - dol_print_error($db); - } + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } + else + { + $db->rollback(); + dol_print_error($db); + } } @@ -208,7 +213,7 @@ print ''; print ''.$langs->trans("LDAPFieldPasswordNotCrypted").''; print ''; print ''.$langs->trans("LDAPFieldPasswordExample").''; -print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_PASSWORD)?' checked':'').">"; +print ' '; print ''; // Password crypted @@ -216,7 +221,7 @@ print ''; print ''.$langs->trans("LDAPFieldPasswordCrypted").''; print ''; print ''.$langs->trans("LDAPFieldPasswordExample").''; -print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_PASSWORD_CRYPTED)?' checked':'').">"; +print ' '; print ''; // Mail @@ -259,12 +264,52 @@ print ''.$langs->trans("LDAPFieldFaxExample").''; print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_FAX)?' checked':'').">"; print ''; +// Company + +print ''.$langs->trans("LDAPFieldCompany").''; +print ''; +print ''.$langs->trans("LDAPFieldCompanyExample").''; +print ' '; +print ''; + +// Address + +print ''.$langs->trans("LDAPFieldAddress").''; +print ''; +print ''.$langs->trans("LDAPFieldAddressExample").''; +print ' '; +print ''; + +// ZIP + +print ''.$langs->trans("LDAPFieldZip").''; +print ''; +print ''.$langs->trans("LDAPFieldZipExample").''; +print ' '; +print ''; + +// TOWN + +print ''.$langs->trans("LDAPFieldTown").''; +print ''; +print ''.$langs->trans("LDAPFieldTownExample").''; +print ' '; +print ''; + +// COUNTRY + +print ''.$langs->trans("LDAPFieldCountry").''; +print ''; +print ' '; +print ' '; +print ''; + // Title print ''.$langs->trans("LDAPFieldTitle").''; print ''; print ''.$langs->trans("LDAPFieldTitleExample").''; -print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_TITLE)?' checked':'').">"; +print ' '; print ''; // Note @@ -272,7 +317,7 @@ print ''; print ''.$langs->trans("Note").''; print ''; print ''.$langs->trans("LDAPFieldDescriptionExample").''; -print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_DESCRIPTION)?' checked':'').">"; +print ' '; print ''; // Sid @@ -385,7 +430,7 @@ if (function_exists("ldap_connect")) { $required_fields = array( $conf->global->LDAP_KEY_USERS, - $conf->global->LDAP_FIELD_FULLNAME, + $conf->global->LDAP_FIELD_FULLNAME, $conf->global->LDAP_FIELD_NAME, $conf->global->LDAP_FIELD_FIRSTNAME, $conf->global->LDAP_FIELD_LOGIN, @@ -394,7 +439,7 @@ if (function_exists("ldap_connect")) $conf->global->LDAP_FIELD_PASSWORD_CRYPTED, $conf->global->LDAP_FIELD_PHONE, $conf->global->LDAP_FIELD_FAX, - $conf->global->LDAP_FIELD_SKYPE, + $conf->global->LDAP_FIELD_SKYPE, $conf->global->LDAP_FIELD_MOBILE, $conf->global->LDAP_FIELD_MAIL, $conf->global->LDAP_FIELD_TITLE, @@ -402,35 +447,35 @@ if (function_exists("ldap_connect")) $conf->global->LDAP_FIELD_SID ); - // Remove from required_fields all entries not configured in LDAP (empty) and duplicated - $required_fields=array_unique(array_values(array_filter($required_fields, "dol_validElement"))); + // Remove from required_fields all entries not configured in LDAP (empty) and duplicated + $required_fields=array_unique(array_values(array_filter($required_fields, "dol_validElement"))); - // Get from LDAP database an array of results - $ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 1); - //$ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, '', 1); + // Get from LDAP database an array of results + $ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 1); + //$ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, '', 1); - if (is_array($ldapusers)) - { - $liste=array(); - foreach ($ldapusers as $key => $ldapuser) - { - // Define the label string for this user - $label=''; - foreach ($required_fields as $value) - { - if ($value) - { - $label.=$value."=".$ldapuser[$value]." "; - } - } - $liste[$key] = $label; - } + if (is_array($ldapusers)) + { + $liste=array(); + foreach ($ldapusers as $key => $ldapuser) + { + // Define the label string for this user + $label=''; + foreach ($required_fields as $value) + { + if ($value) + { + $label.=$value."=".$ldapuser[$value]." "; + } + } + $liste[$key] = $label; + } - } - else - { - setEventMessages($ldap->error, $ldap->errors, 'errors'); - } + } + else + { + setEventMessages($ldap->error, $ldap->errors, 'errors'); + } print "
\n"; print "LDAP search for user:
\n"; diff --git a/htdocs/admin/limits.php b/htdocs/admin/limits.php index 1d4b5cee8d4..36b0d4d0df1 100644 --- a/htdocs/admin/limits.php +++ b/htdocs/admin/limits.php @@ -101,25 +101,24 @@ if ($action == 'edit') print ''; clearstatcache(); - $var=true; print ''; print ''; - + print ''; - + print ''; - + print ''; - + print ''; @@ -135,25 +134,23 @@ if ($action == 'edit') } else { - $var=true; - print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans("MAIN_MAX_DECIMALS_UNIT"),$langs->trans("ParameterActiveForNextInputOnly")); print '
'; print $form->textwithpicto($langs->trans("MAIN_MAX_DECIMALS_TOT"),$langs->trans("ParameterActiveForNextInputOnly")); print '
'.$langs->trans("MAIN_MAX_DECIMALS_SHOWN").'
'; print $form->textwithpicto($langs->trans("MAIN_ROUNDING_RULE_TOT"),$langs->trans("ParameterActiveForNextInputOnly")); print '
'; print ''; - + print ''; - + print ''; - + print ''; - + print ''; diff --git a/htdocs/admin/livraison.php b/htdocs/admin/livraison.php index 24e2772ae0d..bff8d75069a 100644 --- a/htdocs/admin/livraison.php +++ b/htdocs/admin/livraison.php @@ -454,7 +454,7 @@ print ''; print "\n"; $var=true; -$substitutionarray=pdf_getSubstitutionArray($langs); +$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; @@ -465,7 +465,7 @@ print '
'; print ''; print ''; print '
'; // Param - $label = $langs->trans($key); + $label = $langs->trans($key); print ''; // Value @@ -120,7 +120,7 @@ print ''; print ''; print "
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans("MAIN_MAX_DECIMALS_UNIT"),$langs->trans("ParameterActiveForNextInputOnly")); print ''.$conf->global->MAIN_MAX_DECIMALS_UNIT.'
'; print $form->textwithpicto($langs->trans("MAIN_MAX_DECIMALS_TOT"),$langs->trans("ParameterActiveForNextInputOnly")); print ''.$conf->global->MAIN_MAX_DECIMALS_TOT.'
'.$langs->trans("MAIN_MAX_DECIMALS_SHOWN").''.$conf->global->MAIN_MAX_DECIMALS_SHOWN.'
'; print $form->textwithpicto($langs->trans("MAIN_ROUNDING_RULE_TOT"),$langs->trans("ParameterActiveForNextInputOnly")); print ''.$conf->global->MAIN_ROUNDING_RULE_TOT.'
 
'; -print $form->textwithpicto($langs->trans("FreeLegalTextOnDeliveryReceipts"), $langs->trans("AddCRIfTooLong").'

'.$htmltext).'
'; +print $form->textwithpicto($langs->trans("FreeLegalTextOnDeliveryReceipts"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='DELIVERY_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { diff --git a/htdocs/admin/livraison_extrafields.php b/htdocs/admin/livraison_extrafields.php index 84037ae9b80..5c9a17edc7a 100644 --- a/htdocs/admin/livraison_extrafields.php +++ b/htdocs/admin/livraison_extrafields.php @@ -47,7 +47,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/livraisondet_extrafields.php b/htdocs/admin/livraisondet_extrafields.php index 22a7e89d724..47e5b2eb975 100644 --- a/htdocs/admin/livraisondet_extrafields.php +++ b/htdocs/admin/livraisondet_extrafields.php @@ -7,7 +7,7 @@ * Copyright (C) 2013 Philippe Grand * Copyright (C) 2013 Florian Henry * Copyright (C) 2015 Claudio Aschieri - * + * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -47,7 +47,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/loan.php b/htdocs/admin/loan.php index c3e8bad9f6d..65363f468e8 100644 --- a/htdocs/admin/loan.php +++ b/htdocs/admin/loan.php @@ -23,7 +23,7 @@ */ require '../main.inc.php'; - + // Class require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; @@ -47,7 +47,7 @@ $list = array ( /* * Actions */ - + if ($action == 'update') { $error = 0; @@ -99,7 +99,7 @@ foreach ($list as $key) print '
\n"; -print '
'; +print '
'; llxFooter(); $db->close(); \ No newline at end of file diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index 279c65fa204..d77f448f811 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -50,7 +50,7 @@ $substitutionarrayfortest=array( '__ID__' => 'RecipientIdRecord', //'__EMAIL__' => 'RecipientEMail', // Done into actions_sendmails '__CHECK_READ__' => (is_object($object) && is_object($object->thirdparty))?'':'', -'__SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$usersignature:''), // Done into actions_sendmails +'__USER_SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$usersignature:''), // Done into actions_sendmails '__LOGIN__' => 'RecipientLogin', '__LASTNAME__' => 'RecipientLastname', '__FIRSTNAME__' => 'RecipientFirstname', @@ -69,20 +69,20 @@ complete_substitutions_array($substitutionarrayfortest, $langs); if ($action == 'update' && empty($_POST["cancel"])) { - dolibarr_set_const($db, "MAIN_DISABLE_ALL_MAILS", GETPOST("MAIN_DISABLE_ALL_MAILS"),'chaine',0,'',$conf->entity); - // Send mode parameters - dolibarr_set_const($db, "MAIN_MAIL_SENDMODE", GETPOST("MAIN_MAIL_SENDMODE"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_SMTP_PORT", GETPOST("MAIN_MAIL_SMTP_PORT"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_SMTP_SERVER", GETPOST("MAIN_MAIL_SMTP_SERVER"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_SMTPS_ID", GETPOST("MAIN_MAIL_SMTPS_ID"), 'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW", GETPOST("MAIN_MAIL_SMTPS_PW"), 'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS", GETPOST("MAIN_MAIL_EMAIL_TLS"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS", GETPOST("MAIN_MAIL_EMAIL_STARTTLS"),'chaine',0,'',$conf->entity); - // Content parameters - dolibarr_set_const($db, "MAIN_MAIL_EMAIL_FROM", GETPOST("MAIN_MAIL_EMAIL_FROM"), 'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_ERRORS_TO", GETPOST("MAIN_MAIL_ERRORS_TO"), 'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_AUTOCOPY_TO", GETPOST("MAIN_MAIL_AUTOCOPY_TO"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, 'MAIN_MAIL_DEFAULT_FROMTYPE',GETPOST('MAIN_MAIL_DEFAULT_FROMTYPE'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_DISABLE_ALL_MAILS", GETPOST("MAIN_DISABLE_ALL_MAILS"),'chaine',0,'',$conf->entity); + // Send mode parameters + dolibarr_set_const($db, "MAIN_MAIL_SENDMODE", GETPOST("MAIN_MAIL_SENDMODE"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTP_PORT", GETPOST("MAIN_MAIL_SMTP_PORT"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTP_SERVER", GETPOST("MAIN_MAIL_SMTP_SERVER"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTPS_ID", GETPOST("MAIN_MAIL_SMTPS_ID"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW", GETPOST("MAIN_MAIL_SMTPS_PW"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS", GETPOST("MAIN_MAIL_EMAIL_TLS"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS", GETPOST("MAIN_MAIL_EMAIL_STARTTLS"),'chaine',0,'',$conf->entity); + // Content parameters + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_FROM", GETPOST("MAIN_MAIL_EMAIL_FROM"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_ERRORS_TO", GETPOST("MAIN_MAIL_ERRORS_TO"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_AUTOCOPY_TO", GETPOST("MAIN_MAIL_AUTOCOPY_TO"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, 'MAIN_MAIL_DEFAULT_FROMTYPE', GETPOST('MAIN_MAIL_DEFAULT_FROMTYPE'),'chaine',0,'',$conf->entity); header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); exit; @@ -119,24 +119,12 @@ $server=! empty($conf->global->MAIN_MAIL_SMTP_SERVER)?$conf->global->MAIN_MAIL_S if (! $server) $server='127.0.0.1'; -$wikihelp='EN:Setup EMails|FR:Paramétrage EMails|ES:Configuración EMails'; +$wikihelp='EN:Setup_EMails|FR:Paramétrage_EMails|ES:Configuración_EMails'; llxHeader('',$langs->trans("Setup"),$wikihelp); print load_fiche_titre($langs->trans("EMailsSetup"),'','title_setup'); - -$h = 0; - -$head[$h][0] = DOL_URL_ROOT."/admin/mails.php"; -$head[$h][1] = $langs->trans("OutGoingEmailSetup"); -$head[$h][2] = 'common'; -$h++; - -$head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php"; -$head[$h][1] = $langs->trans("DictionaryEMailTemplates"); -$head[$h][2] = 'templates'; -$h++; - +$head = email_admin_prepare_head(); // List of sending methods $listofmethods=array(); @@ -243,7 +231,7 @@ if ($action == 'edit') $var=true; print ''; - print ''; + print ''; // Disable @@ -418,19 +406,36 @@ if ($action == 'edit') print ''; - // Default from type + // Default from type + $liste = array(); + $liste['user'] = $langs->trans('UserEmail'); + $liste['company'] = $langs->trans('CompanyEmail').' ('.(empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?$langs->trans("NotDefined"):$conf->global->MAIN_INFO_SOCIETE_MAIL).')'; + /* + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1'; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i=0; + while($i < $num) + { + $obj = $db->fetch_object($resql); + if ($obj) + { + $liste['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>'; + } + $i++; + } + } + else dol_print_error($db);*/ - $liste = array(); - $liste['user'] = $langs->trans('UserEmail'); - $liste['company'] = $langs->trans('CompanyEmail').' ('.(empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?$langs->trans("NotDefined"):$conf->global->MAIN_INFO_SOCIETE_MAIL).')'; + print ''; - print ''; + // Separator - // Separator - - print ''; + print ''; // From @@ -444,30 +449,30 @@ if ($action == 'edit') print ''; - print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; + print $form->selectarray('MAIN_MAIL_DEFAULT_FROMTYPE', $liste, $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE, 0); + print '
'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; - print $form->selectarray('MAIN_MAIL_DEFAULT_FROMTYPE',$liste,$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE,0); - print '
 
 
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print '
'; - print ''; - print '     '; - print ''; - print '
'; + print '
'; + print ''; + print '     '; + print ''; + print '
'; print ''; } else { - dol_fiche_head($head, 'common', '', -1); + dol_fiche_head($head, 'common', '', -1); - print $langs->trans("EMailsDesc")."
\n"; - print "
\n"; + print $langs->trans("EMailsDesc")."
\n"; + print "
\n"; $var=true; print ''; - print ''; + print ''; // Disable @@ -561,21 +566,54 @@ else print ''; // Default from type + $liste = array(); + $liste['user'] = $langs->trans('UserEmail'); + $liste['company'] = $langs->trans('CompanyEmail').' ('.(empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?$langs->trans("NotDefined"):$conf->global->MAIN_INFO_SOCIETE_MAIL).')'; + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1'; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i=0; + while($i < $num) + { + $obj = $db->fetch_object($resql); + if ($obj) + { + $liste['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>'; + } + $i++; + } + } + else dol_print_error($db); - print ''; - print ''; + print ''; + print ''; // Separator print ''; - // Errors To + // Errors To print ''; print ''; + elseif ($value == 'lang') + { + print ''; + } + elseif ($value == 'fk_user') + { + print ''; + } + elseif ($value == 'topic') print ''; + elseif ($value == 'type_template') + { + print ''; + } elseif (! in_array($value, array('content', 'content_lines'))) print ''; } if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) print ''; - print ''; // Action column - print ''; @@ -660,10 +691,15 @@ if ($resql) */ $valuetoshow=ucfirst($fieldlist[$field]); // By defaut $valuetoshow=$langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field]=='fk_user') { $valuetoshow=$langs->trans("Owner"); } if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } + if ($fieldlist[$field]=='private') { $align='center'; } + if ($fieldlist[$field]=='position') { $align='center'; } + + if ($fieldlist[$field]=='joinfiles') { $valuetoshow=$langs->trans("FilesAttachedToEmail"); $align='center'; } if ($fieldlist[$field]=='content') { $valuetoshow=$langs->trans("Content"); $showfield=0;} if ($fieldlist[$field]=='content_lines') { $valuetoshow=$langs->trans("ContentLines"); $showfield=0; } @@ -681,7 +717,6 @@ if ($resql) print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); print getTitleFieldOfList(''); - print getTitleFieldOfList(''); print ''; if ($num) @@ -689,13 +724,13 @@ if ($resql) // Lines with values while ($i < $num) { - $obj = $db->fetch_object($resql); - //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) { - $tmpaction='edit'; + $tmpaction='edit'; $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks $error=$hookmanager->error; $errors=$hookmanager->errors; @@ -703,7 +738,8 @@ if ($resql) // Show fields if (empty($reshook)) fieldList($fieldlist,$obj,$tabname[$id],'edit'); - print ''; + print ''; - $fieldsforcontent = array('content'); + $fieldsforcontent = array('topic', 'joinfiles', 'content'); if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { - $fieldsforcontent = array('content', 'content_lines'); + $fieldsforcontent = array('topic', 'joinfiles', 'content', 'content_lines'); } foreach ($fieldsforcontent as $tmpfieldlist) { @@ -725,16 +761,29 @@ if ($resql) $class = 'tddict'; // Show value for field if ($showfield) { - - print ''; - print ''; - + // Show line for topic, joinfiles and content + print ''; + print ''; + print ''; + print ''; } } } @@ -758,49 +807,74 @@ if ($resql) { $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; } + if ($value == 'lang' && $valuetoshow) + { + $valuetoshow = $valuetoshow.' - '.$langs->trans("Language_".$valuetoshow); + } + if ($value == 'fk_user') + { + if ($valuetoshow > 0) + { + $fuser=new User($db); + $fuser->fetch($valuetoshow); + $valuetoshow = $fuser->getNomUrl(1); + } + } + if ($value == 'private') + { + $align="center"; + if ($valuetoshow) $valuetoshow=yn($valuetoshow); + else $valuetoshow=''; + } + if ($value == 'position') + { + $align="center"; + } + if ($value == 'joinfiles') + { + $align="center"; + if ($valuetoshow) $valuetoshow=1; + else $valuetoshow=''; + } $class='tddict'; // Show value for field if ($showfield) { - print ''; + print ''; + print ''; } } } // Can an entry be erased or disabled ? $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default - $canbemodified=$iserasable; + if (! $user->admin && $obj->fk_user != $user->id) + { + $iserasable=0; + $canbedisabled=0; + $canbemodified=0; + } $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); if ($param) $url .= '&'.$param; $url.='&'; - // Active + // Status / Active print '"; - // Modify link - if ($canbemodified) print ''; - else print ''; - - // Delete link + // Modify link / Delete link + print ''; } - else print ''; + print ''; + /* $fieldsforcontent = array('content'); @@ -864,7 +938,7 @@ $db->close(); */ function fieldList($fieldlist, $obj='', $tabname='', $context='') { - global $conf,$langs,$db; + global $conf, $langs, $user, $db; global $form; global $region_id; global $elementList,$sourceList,$localtax_typeList; @@ -872,35 +946,109 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') $formadmin = new FormAdmin($db); $formcompany = new FormCompany($db); - if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); foreach ($fieldlist as $field => $value) { - if ($fieldlist[$field] == 'lang') + if ($fieldlist[$field] == 'fk_user') { print ''; + } + elseif ($fieldlist[$field] == 'lang') + { + print ''; } // Le type de template elseif ($fieldlist[$field] == 'type_template') { print ''; } - elseif (in_array($fieldlist[$field], array('content','content_lines'))) continue; + elseif ($context == 'add' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue; + elseif ($context == 'edit' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue; + elseif ($context == 'hide' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue; else { - print ''; } } diff --git a/htdocs/admin/menus.php b/htdocs/admin/menus.php index 888045f3297..5e0b6fac6f6 100644 --- a/htdocs/admin/menus.php +++ b/htdocs/admin/menus.php @@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; $action=GETPOST('action','aZ09'); +$cancel=GETPOST('cancel','alpha'); $langs->load("companies"); $langs->load("products"); @@ -62,22 +63,22 @@ error_reporting($err); * Actions */ -if ($action == 'update' && empty($_POST["cancel"])) +if ($action == 'update' && ! $cancel) { $_SESSION["mainmenu"]="home"; // Le gestionnaire de menu a pu changer - dolibarr_set_const($db, "MAIN_MENU_STANDARD", $_POST["MAIN_MENU_STANDARD"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MENU_SMARTPHONE", $_POST["MAIN_MENU_SMARTPHONE"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MENU_STANDARD", GETPOST('MAIN_MENU_STANDARD','alpha'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MENU_SMARTPHONE", GETPOST('MAIN_MENU_SMARTPHONE','alpha'),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MENUFRONT_STANDARD", $_POST["MAIN_MENUFRONT_STANDARD"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MENUFRONT_SMARTPHONE",$_POST["MAIN_MENUFRONT_SMARTPHONE"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MENUFRONT_STANDARD", GETPOST('MAIN_MENUFRONT_STANDARD','alpha'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MENUFRONT_SMARTPHONE", GETPOST('MAIN_MENUFRONT_SMARTPHONE','alpha'),'chaine',0,'',$conf->entity); // Define list of menu handlers to initialize $listofmenuhandler=array(); - $listofmenuhandler[preg_replace('/(_backoffice|_frontoffice|_menu)?\.php/i','',$_POST["MAIN_MENU_STANDARD"])]=1; - $listofmenuhandler[preg_replace('/(_backoffice|_frontoffice|_menu)?\.php/i','',$_POST["MAIN_MENUFRONT_STANDARD"])]=1; - if (isset($_POST["MAIN_MENU_SMARTPHONE"])) $listofmenuhandler[preg_replace('/(_backoffice|_frontoffice|_menu)?\.php/i','',$_POST["MAIN_MENU_SMARTPHONE"])]=1; - if (isset($_POST["MAIN_MENUFRONT_SMARTPHONE"])) $listofmenuhandler[preg_replace('/(_backoffice|_frontoffice|_menu)?\.php/i','',$_POST["MAIN_MENUFRONT_SMARTPHONE"])]=1; + $listofmenuhandler[preg_replace('/(_backoffice|_frontoffice|_menu)?\.php/i','',GETPOST('MAIN_MENU_STANDARD','alpha'))]=1; + $listofmenuhandler[preg_replace('/(_backoffice|_frontoffice|_menu)?\.php/i','',GETPOST('MAIN_MENUFRONT_STANDARD','alpha'))]=1; + if (GETPOST('MAIN_MENU_SMARTPHONE','alpha')) $listofmenuhandler[preg_replace('/(_backoffice|_frontoffice|_menu)?\.php/i','',GETPOST('MAIN_MENU_SMARTPHONE','alpha'))]=1; + if (GETPOST('MAIN_MENUFRONT_SMARTPHONE','alpha')) $listofmenuhandler[preg_replace('/(_backoffice|_frontoffice|_menu)?\.php/i','',GETPOST('MAIN_MENUFRONT_SMARTPHONE','alpha'))]=1; // Initialize menu handlers foreach ($listofmenuhandler as $key => $val) @@ -179,7 +180,7 @@ if ($action == 'edit') print ''; // Menu top - + print ''; print ''; // Menu smartphone - + print ''; print ''; print ''; - + print ''; print ''; print ''; - + print ''; print ''; print ''."\n"; + print ''."\n"; // Picto + Name of module print ' '; print ''; - print "\n"; $url='https://www.dolistore.com'; print ''; @@ -825,17 +824,67 @@ if ($mode == 'marketplace') print ''; print ''; - - print "\n"; - $url='https://partners.dolibarr.org'; - print ''; - print ''; - print ''; - print ''; - print "
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; - if($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'user'){ - print $langs->trans('UserEmail'); - } else { - print $langs->trans('CompanyEmail'); - } - print '
'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; + if ($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'user') + { + print $langs->trans('UserEmail'); + } + else if ($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'company') + { + print $langs->trans('CompanyEmail').' '.dol_escape_htmltag('<'.$mysoc->email.'>'); + } + else { + $id = preg_replace('/senderprofile_/', '', $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE); + if ($id > 0) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/emailsenderprofile.class.php'; + $emailsenderprofile = new EmailSenderProfile($db); + $emailsenderprofile->fetch($id); + print $emailsenderprofile->label.' '.dol_escape_htmltag('<'.$emailsenderprofile->email.'>'); + } + } + print '
 
'.$langs->trans("MAIN_MAIL_ERRORS_TO").''.$conf->global->MAIN_MAIL_ERRORS_TO; @@ -602,10 +640,10 @@ else dol_fiche_end(); - if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) - { - print '
'; - /* + if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) + { + print '
'; + /* // Warning 1 if ($linuxlike) { @@ -615,9 +653,9 @@ else print info_admin($langs->trans("SendmailOptionNotComplete")); } }*/ - // Warning 2 - print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); - } + // Warning 2 + print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); + } // Boutons actions @@ -649,8 +687,8 @@ else if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && ! in_array($action, array('testconnect', 'test', 'testhtml'))) { - $text = $langs->trans("WarningPHPMail"); - print info_admin($text); + $text = $langs->trans("WarningPHPMail"); + print info_admin($text); } // Run the test to connect @@ -678,7 +716,7 @@ else // Show email send test form if ($action == 'test' || $action == 'testhtml') { - print '
'; + print '
'; print load_fiche_titre($action == 'testhtml'?$langs->trans("DoTestSendHTML"):$langs->trans("DoTestSend")); dol_fiche_head(''); @@ -714,7 +752,7 @@ else $formmail->param["returnurl"]=$_SERVER["PHP_SELF"]; // Init list of files - if (GETPOST("mode")=='init') + if (GETPOST("mode")=='init') { $formmail->clear_attached_files(); } diff --git a/htdocs/admin/mails_emailing.php b/htdocs/admin/mails_emailing.php new file mode 100644 index 00000000000..1202e9817d3 --- /dev/null +++ b/htdocs/admin/mails_emailing.php @@ -0,0 +1,623 @@ + + * Copyright (C) 2009-2012 Regis Houssin + * Copyright (C) 2013 Juanjo Menent + * Copyright (C) 2016 Jonathan TISSEAU + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/admin/mails.php + * \brief Page to setup emails sending + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + +$langs->load("companies"); +$langs->load("products"); +$langs->load("admin"); +$langs->load("mails"); +$langs->load("other"); +$langs->load("errors"); + +$action=GETPOST('action','alpha'); + +if (! $user->admin) accessforbidden(); + +$usersignature=$user->signature; +// For action = test or send, we ensure that content is not html, even for signature, because this we want a test with NO html. +if ($action == 'test' || $action == 'send') +{ + $usersignature=dol_string_nohtmltag($usersignature); +} + +$substitutionarrayfortest=array( +'__LOGIN__' => $user->login, +'__ID__' => 'TESTIdRecord', +'__EMAIL__' => 'TESTEMail', +'__LASTNAME__' => 'TESTLastname', +'__FIRSTNAME__' => 'TESTFirstname', +'__USER_SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$usersignature:''), +//'__PERSONALIZED__' => 'TESTPersonalized' // Hiden because not used yet +); +complete_substitutions_array($substitutionarrayfortest, $langs); + + + +/* + * Actions + */ + +if ($action == 'update' && empty($_POST["cancel"])) +{ + // Send mode parameters + dolibarr_set_const($db, "MAIN_MAIL_SENDMODE_EMAILING", GETPOST("MAIN_MAIL_SENDMODE_EMAILING"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTP_PORT_EMAILING", GETPOST("MAIN_MAIL_SMTP_PORT_EMAILING"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTP_SERVER_EMAILING", GETPOST("MAIN_MAIL_SMTP_SERVER_EMAILING"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTPS_ID_EMAILING", GETPOST("MAIN_MAIL_SMTPS_ID_EMAILING"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW_EMAILING", GETPOST("MAIN_MAIL_SMTPS_PW_EMAILING"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS_EMAILING", GETPOST("MAIN_MAIL_EMAIL_TLS_EMAILING"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS_EMAILING", GETPOST("MAIN_MAIL_EMAIL_STARTTLS_EMAILING"),'chaine',0,'',$conf->entity); + + header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); + exit; +} + + +// Actions to send emails +$id=0; +$actiontypecode=''; // Not an event for agenda +$trigger_name=''; // Disable triggers +$paramname='id'; +$mode='emailfortest'; +$trackid=(($action == 'testhtml')?"testhtml":"test"); +$sendcontext='emailing'; // Force to use dedicated context of setup for emailing +include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + +if ($action == 'presend' && GETPOST('trackid') == 'test') $action='test'; +if ($action == 'presend' && GETPOST('trackid') == 'testhtml') $action='testhtml'; + + + + +/* + * View + */ + +$linuxlike=1; +if (preg_match('/^win/i',PHP_OS)) $linuxlike=0; +if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0; + +if (empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING)) $conf->global->MAIN_MAIL_SENDMODE_EMAILING='default'; +$port=! empty($conf->global->MAIN_MAIL_SMTP_PORT_EMAILING)?$conf->global->MAIN_MAIL_SMTP_PORT_EMAILING:ini_get('smtp_port'); +if (! $port) $port=25; +$server=! empty($conf->global->MAIN_MAIL_SMTP_SERVER_EMAILING)?$conf->global->MAIN_MAIL_SMTP_SERVER_EMAILING:ini_get('SMTP'); +if (! $server) $server='127.0.0.1'; + + +$wikihelp='EN:Setup_EMails|FR:Paramétrage_EMails|ES:Configuración_EMails'; +llxHeader('',$langs->trans("Setup"),$wikihelp); + +print load_fiche_titre($langs->trans("EMailsSetup"),'','title_setup'); + +$head = email_admin_prepare_head(); + +// List of sending methods +$listofmethods=array(); +$listofmethods['default']=$langs->trans('DefaultOutgoingEmailSetup'); +$listofmethods['mail']='PHP mail function'; +//$listofmethods['simplemail']='Simplemail class'; +$listofmethods['smtps']='SMTP/SMTPS socket library'; +$listofmethods['swiftmailer']='Swift Mailer socket library'; + + +if ($action == 'edit') +{ + $form=new Form($db); + + if ($conf->use_javascript_ajax) + { + print "\n".''."\n"; + } + + print '
'; + print ''; + print ''; + + dol_fiche_head($head, 'common_emailing', '', -1); + + print $langs->trans("EMailsDesc")."
\n"; + print "
\n"; + + + clearstatcache(); + $var=true; + + print ''; + print ''; + + // Method + + print ''; + + // Host server + + print ''; + + // Port + + print ''; + + // ID + if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer')))) + { + + $mainstmpid=(! empty($conf->global->MAIN_MAIL_SMTPS_ID_EMAILING)?$conf->global->MAIN_MAIL_SMTPS_ID_EMAILING:''); + print ''; + } + + // PW + if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer')))) + { + + $mainsmtppw=(! empty($conf->global->MAIN_MAIL_SMTPS_PW_EMAILING)?$conf->global->MAIN_MAIL_SMTPS_PW_EMAILING:''); + print ''; + } + + // TLS + + print ''; + + // STARTTLS + + print ''; + + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_MAIL_SENDMODE").''; + + // SuperAdministrator access only + if ((empty($conf->global->MAIN_MODULE_MULTICOMPANY)) || ($user->admin && !$user->entity)) + { + print $form->selectarray('MAIN_MAIL_SENDMODE_EMAILING',$listofmethods,$conf->global->MAIN_MAIL_SENDMODE_EMAILING); + } + else + { + $text = $listofmethods[$conf->global->MAIN_MAIL_SENDMODE_EMAILING]; + if (empty($text)) $text = $langs->trans("Undefined"); + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($text,$htmltext,1,'superadmin'); + print ''; + } + print '
'; + if (! $conf->use_javascript_ajax && $linuxlike && $conf->global->MAIN_MAIL_SENDMODE_EMAILING == 'mail') + { + print $langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike"); + print ''; + print $langs->trans("SeeLocalSendMailSetup"); + } + else + { + $mainserver = (! empty($conf->global->MAIN_MAIL_SMTP_SERVER_EMAILING)?$conf->global->MAIN_MAIL_SMTP_SERVER_EMAILING:''); + $smtpserver = ini_get('SMTP')?ini_get('SMTP'):$langs->transnoentities("Undefined"); + if ($linuxlike) print $langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike"); + else print $langs->trans("MAIN_MAIL_SMTP_SERVER",$smtpserver); + print ''; + // SuperAdministrator access only + if (empty($conf->multicompany->enabled) || ($user->admin && ! $user->entity)) + { + print ''; + print ''; + print ''.$langs->trans("SeeLocalSendMailSetup").''; + } + else + { + $text = ! empty($mainserver) ? $mainserver : $smtpserver; + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($text,$htmltext,1,'superadmin'); + print ''; + } + } + print '
'; + if (! $conf->use_javascript_ajax && $linuxlike && $conf->global->MAIN_MAIL_SENDMODE_EMAILING == 'mail') + { + print $langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike"); + print ''; + print $langs->trans("SeeLocalSendMailSetup"); + } + else + { + $mainport = (! empty($conf->global->MAIN_MAIL_SMTP_PORT_EMAILING) ? $conf->global->MAIN_MAIL_SMTP_PORT_EMAILING : ''); + $smtpport = ini_get('smtp_port')?ini_get('smtp_port'):$langs->transnoentities("Undefined"); + if ($linuxlike) print $langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike"); + else print $langs->trans("MAIN_MAIL_SMTP_PORT",$smtpport); + print ''; + // SuperAdministrator access only + if (empty($conf->multicompany->enabled) || ($user->admin && ! $user->entity)) + { + print ''; + print ''; + print ''.$langs->trans("SeeLocalSendMailSetup").''; + } + else + { + $text = (! empty($mainport) ? $mainport : $smtpport); + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($text,$htmltext,1,'superadmin'); + print ''; + } + } + print '
'.$langs->trans("MAIN_MAIL_SMTPS_ID").''; + // SuperAdministrator access only + if (empty($conf->multicompany->enabled) || ($user->admin && !$user->entity)) + { + print ''; + } + else + { + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($conf->global->MAIN_MAIL_SMTPS_ID_EMAILING,$htmltext,1,'superadmin'); + print ''; + } + print '
'.$langs->trans("MAIN_MAIL_SMTPS_PW").''; + // SuperAdministrator access only + if (empty($conf->multicompany->enabled) || ($user->admin && !$user->entity)) + { + print ''; + } + else + { + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($conf->global->MAIN_MAIL_SMTPS_PW_EMAILING,$htmltext,1,'superadmin'); + print ''; + } + print '
'.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; + if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer')))) + { + if (function_exists('openssl_open')) + { + print $form->selectyesno('MAIN_MAIL_EMAIL_TLS_EMAILING',(! empty($conf->global->MAIN_MAIL_EMAIL_TLS_EMAILING)?$conf->global->MAIN_MAIL_EMAIL_TLS_EMAILING:0),1); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'.$langs->trans("MAIN_MAIL_EMAIL_STARTTLS").''; + if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer')))) + { + if (function_exists('openssl_open')) + { + print $form->selectyesno('MAIN_MAIL_EMAIL_STARTTLS_EMAILING',(! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS_EMAILING)?$conf->global->MAIN_MAIL_EMAIL_STARTTLS_EMAILING:0),1); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'; + + dol_fiche_end(); + + print '
'; + print ''; + print '     '; + print ''; + print '
'; + + print '
'; +} +else +{ + dol_fiche_head($head, 'common_emailing', '', -1); + + print $langs->trans("EMailsDesc")."
\n"; + print "
\n"; + + + $var=true; + + print ''; + print ''; + + // Method + + print ''; + + if (! empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') + { + // Host server + + if ($linuxlike && (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING == 'mail')) + { + print ''; + } + else + { + print ''; + } + + // Port + + if ($linuxlike && (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING == 'mail')) + { + print ''; + } + else + { + print ''; + } + + // SMTPS ID + + if (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer'))) + { + print ''; + } + + // SMTPS PW + + if (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer'))) + { + print ''; + } + + // TLS + + print ''; + + // STARTTLS + + print ''; + } + + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_MAIL_SENDMODE").''; + $text=$listofmethods[$conf->global->MAIN_MAIL_SENDMODE_EMAILING]; + if (empty($text)) $text=$langs->trans("Undefined").img_warning(); + print $text; + print '
'.$langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTP_SERVER",ini_get('SMTP')?ini_get('SMTP'):$langs->transnoentities("Undefined")).''.(! empty($conf->global->MAIN_MAIL_SMTP_SERVER_EMAILING)?$conf->global->MAIN_MAIL_SMTP_SERVER_EMAILING:'').'
'.$langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTP_PORT",ini_get('smtp_port')?ini_get('smtp_port'):$langs->transnoentities("Undefined")).''.(! empty($conf->global->MAIN_MAIL_SMTP_PORT_EMAILING)?$conf->global->MAIN_MAIL_SMTP_PORT_EMAILING:'').'
'.$langs->trans("MAIN_MAIL_SMTPS_ID").''.$conf->global->MAIN_MAIL_SMTPS_ID_EMAILING.'
'.$langs->trans("MAIN_MAIL_SMTPS_PW").''.preg_replace('/./','*',$conf->global->MAIN_MAIL_SMTPS_PW_EMAILING).'
'.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; + if (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer'))) + { + if (function_exists('openssl_open')) + { + print yn($conf->global->MAIN_MAIL_EMAIL_TLS_EMAILING); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'.$langs->trans("MAIN_MAIL_EMAIL_STARTTLS").''; + if (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer'))) + { + if (function_exists('openssl_open')) + { + print yn($conf->global->MAIN_MAIL_EMAIL_STARTTLS_EMAILING); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'; + + dol_fiche_end(); + + + if ($conf->global->MAIN_MAIL_SENDMODE_EMAILING == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) + { + print '
'; + /* + // Warning 1 + if ($linuxlike) + { + $sendmailoption=ini_get('mail.force_extra_parameters'); + if (empty($sendmailoption) || ! preg_match('/ba/',$sendmailoption)) + { + print info_admin($langs->trans("SendmailOptionNotComplete")); + } + }*/ + // Warning 2 + print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); + } + + + // Boutons actions + print '
'; + + print ''.$langs->trans("Modify").''; + + if (! empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') + { + if ($conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'mail' || ! $linuxlike) + { + if (function_exists('fsockopen') && $port && $server) + { + print ''.$langs->trans("DoTestServerAvailability").''; + } + } + else + { + print ''.$langs->trans("DoTestServerAvailability").''; + } + + print ''.$langs->trans("DoTestSend").''; + + if (! empty($conf->fckeditor->enabled)) + { + print ''.$langs->trans("DoTestSendHTML").''; + } + } + + print '
'; + + + if ($conf->global->MAIN_MAIL_SENDMODE_EMAILING == 'mail' && ! in_array($action, array('testconnect', 'test', 'testhtml'))) + { + $text = $langs->trans("WarningPHPMail"); + print info_admin($text); + } + + // Run the test to connect + if ($action == 'testconnect') + { + print load_fiche_titre($langs->trans("DoTestServerAvailability")); + + include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + $mail = new CMailFile('','','',''); + $result=$mail->check_server_port($server,$port); + if ($result) print '
'.$langs->trans("ServerAvailableOnIPOrPort",$server,$port).'
'; + else + { + $errormsg = $langs->trans("ServerNotAvailableOnIPOrPort",$server,$port); + + if ($mail->error) { + $errormsg .= ' - '.$mail->error; + } + + setEventMessages($errormsg, null, 'errors'); + } + print '
'; + } + + // Show email send test form + if ($action == 'test' || $action == 'testhtml') + { + print '
'; + print load_fiche_titre($action == 'testhtml'?$langs->trans("DoTestSendHTML"):$langs->trans("DoTestSend")); + + dol_fiche_head(''); + + // Cree l'objet formulaire mail + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + $formmail->fromname = (isset($_POST['fromname'])?$_POST['fromname']:$conf->global->MAIN_MAIL_EMAIL_FROM); + $formmail->frommail = (isset($_POST['frommail'])?$_POST['frommail']:$conf->global->MAIN_MAIL_EMAIL_FROM); + $formmail->trackid=(($action == 'testhtml')?"testhtml":"test"); + $formmail->withfromreadonly=0; + $formmail->withsubstit=0; + $formmail->withfrom=1; + $formmail->witherrorsto=1; + $formmail->withto=(! empty($_POST['sendto'])?$_POST['sendto']:($user->email?$user->email:1)); + $formmail->withtocc=(! empty($_POST['sendtocc'])?$_POST['sendtocc']:1); // ! empty to keep field if empty + $formmail->withtoccc=(! empty($_POST['sendtoccc'])?$_POST['sendtoccc']:1); // ! empty to keep field if empty + $formmail->withtopic=(isset($_POST['subject'])?$_POST['subject']:$langs->trans("Test")); + $formmail->withtopicreadonly=0; + $formmail->withfile=2; + $formmail->withbody=(isset($_POST['message'])?$_POST['message']:($action == 'testhtml'?$langs->transnoentities("PredefinedMailTestHtml"):$langs->transnoentities("PredefinedMailTest"))); + $formmail->withbodyreadonly=0; + $formmail->withcancel=1; + $formmail->withdeliveryreceipt=1; + $formmail->withfckeditor=($action == 'testhtml'?1:0); + $formmail->ckeditortoolbar='dolibarr_mailings'; + // Tableau des substitutions + $formmail->substit=$substitutionarrayfortest; + // Tableau des parametres complementaires du post + $formmail->param["action"]="send"; + $formmail->param["models"]="body"; + $formmail->param["mailid"]=0; + $formmail->param["returnurl"]=$_SERVER["PHP_SELF"]; + + // Init list of files + if (GETPOST("mode")=='init') + { + $formmail->clear_attached_files(); + } + + print $formmail->get_form('addfile','removefile'); + + dol_fiche_end(); + } +} + + +llxFooter(); + +$db->close(); diff --git a/htdocs/admin/mails_senderprofile_list.php b/htdocs/admin/mails_senderprofile_list.php new file mode 100644 index 00000000000..e695ca122b4 --- /dev/null +++ b/htdocs/admin/mails_senderprofile_list.php @@ -0,0 +1,646 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/admin/mails_senderprofile_list.php + * \ingroup core + * \brief Page to adminsiter email sender profiles + */ + +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check anti CSRF attack test +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test done when option MAIN_SECURITY_CSRF_WITH_TOKEN is on. +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) + + +require '../main.inc.php'; +require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'); +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/emailsenderprofile.class.php'; + +// Load traductions files requiredby by page +$langs->loadLangs(array("errors","admin","mails","languages")); + +$action = GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; +$massaction = GETPOST('massaction','alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files','int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm','alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'emailsenderprofilelist'; // To manage different context of search +$backtopage = GETPOST('backtopage','alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss','aZ'); // Option for the css output (always '' except when 'print') + +$id = GETPOST('id','int'); + +// Load variable for pagination +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object=new EmailSenderProfile($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->monmodule->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('emailsenderprofilelist')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('emailsenderprofile'); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (! $sortfield) $sortfield="t.".key($object->fields); // Set here default search field. By default 1st field in definition. +if (! $sortorder) $sortorder="ASC"; + +// Protection if external user +$socid=0; +if ($user->societe_id > 0) +{ + //$socid = $user->societe_id; + accessforbidden(); +} + +// Initialize array of search criterias +$search_all=trim(GETPOST("search_all",'alpha')); +$search=array(); +foreach($object->fields as $key => $val) +{ + if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); +} + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach($object->fields as $key => $val) +{ + if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; +} + +// Definition of fields for list +$arrayfields=array(); +foreach($object->fields as $key => $val) +{ + // If $val['visible']==0, then we never show the field + if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled']); +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } +} + + + + +/* + * Actions + */ + +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters=array(); +$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)) +{ + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + foreach($object->fields as $key => $val) + { + $search[$key]=''; + } + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass='EmailSenderProfile'; + $objectlabel='EmailSenderProfile'; + $permtoread = $user->admin; + $permtodelete = $user->admin; + $uploaddir = $conf->admin->dir_output.'/senderprofiles'; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + + + +/* + * View + */ + +$form=new Form($db); + +$now=dol_now(); + +//$help_url="EN:Module_EmailSenderProfile|FR:Module_EmailSenderProfile_FR|ES:Módulo_EmailSenderProfile"; +$help_url=''; +$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("EmailSenderProfiles")); + + +llxHeader(); + +$titre=$langs->trans("EMailsSetup"); +$linkback=''; +$titlepicto='title_setup'; + +print load_fiche_titre($titre,$linkback,$titlepicto); + +$head = email_admin_prepare_head(); + +dol_fiche_head($head, 'senderprofiles', '', -1); + +// Build and execute select +// -------------------------------------------------------------------- +$sql = 'SELECT '; +foreach($object->fields as $key => $val) +{ + $sql.='t.'.$key.', '; +} +// Add fields from extrafields +foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); +// Add fields from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +$sql=preg_replace('/, $/','', $sql); +$sql.= " FROM ".MAIN_DB_PREFIX."c_email_senderprofile as t"; +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."emailsenderprofile_extrafields as ef on (t.rowid = ef.fk_object)"; +$sql.= " WHERE t.entity IN (".getEntity('emailsenderprofile').")"; +foreach($search as $key => $val) +{ + $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); + if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); +} +if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_all); +// Add where from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode_search=0; + if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); + } +} +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; + +/* If a group by is required +$sql.= " GROUP BY " +foreach($object->fields as $key => $val) +{ + $sql.='t.'.$key.', '; +} +// Add fields from extrafields +foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +*/ + +$sql.=$db->order($sortfield,$sortorder); + +// Count total nb of records +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} + +$sql.= $db->plimit($limit+1, $offset); + +dol_syslog($script_file, LOG_DEBUG); +$resql=$db->query($sql); +if (! $resql) +{ + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + +// Direct jump if only one record found +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +{ + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/monmodule/emailsenderprofile_card.php?id='.$id); + exit; +} + + +// Example : Adding jquery code +print ''; + +$arrayofselected=is_array($toselect)?$toselect:array(); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); +foreach($search as $key => $val) +{ + $param.= '&search_'.$key.'='.urlencode($search[$key]); +} +if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + +// List of mass actions available +$arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), +); +if ($user->rights->monmodule->delete) $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($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + +$moreforfilter = ''; +/*$moreforfilter.='
'; +$moreforfilter.= $langs->trans('MyFilter') . ': '; +$moreforfilter.= '
';*/ + +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; +else $moreforfilter = $hookmanager->resPrint; + +if (! empty($moreforfilter)) +{ + print '
'; + print $moreforfilter; + print '
'; +} + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print ''."\n"; + + +// Fields title search +// -------------------------------------------------------------------- +print ''; +foreach($object->fields as $key => $val) +{ + if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print ''; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } +} +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Rest of fields search +foreach($object->fields as $key => $val) +{ + if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print ''; +} +// Action column +print ''; +print ''."\n"; + + +// Fields title label +// -------------------------------------------------------------------- +print ''; +foreach($object->fields as $key => $val) +{ + if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print getTitleFieldOfList($langs->trans($extralabels[$key]), 0, $_SERVER["PHP_SELF"], $sortonfield, "", $param, ($align?'align="'.$align.'"':''), $sortfield, $sortorder)."\n"; + } + } +} +// Hook fields +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Rest of fields title +foreach($object->fields as $key => $val) +{ + if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; +} +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; +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 +} + + +// Loop on record +// -------------------------------------------------------------------- +$i=0; +$totalarray=array(); +while ($i < min($num, $limit)) +{ + $obj = $db->fetch_object($resql); + if (empty($obj)) break; // Should not happen + + // Store properties in $object + $object->id = $obj->rowid; + foreach($object->fields as $key => $val) + { + if (isset($obj->$key)) $object->$key = $obj->$key; + } + + // Show here line of result + print ''; + foreach($object->fields as $key => $val) + { + if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) + { + print ''; + if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour'); + elseif ($key == 'ref') print $object->getNomUrl(1, '', 0, '', 1); + elseif ($key == 'status') print $object->getLibStatut(3); + else print $obj->$key; + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + $totalarray['val']['t.'.$key] += $obj->$key; + } + } + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='ef.'.$tmpkey; + $totalarray['val']['ef.'.$tmpkey] += $obj->$tmpkey; + } + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Rest of fields + foreach($object->fields as $key => $val) + { + if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; + if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) + { + print ''; + if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour'); + elseif ($key == 'status') print $object->getLibStatut(3); + else print $obj->$key; + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + $totalarray['val']['t.'.$key] += $obj->$key; + } + } + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print ''; + + $i++; +} + +// Show total line +if (isset($totalarray['pos'])) +{ + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if (! empty($totalarray['pos'][$i])) print ''; + else + { + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + else print ''; + } + } + print ''; +} + +// If no record found +if ($num == 0) +{ + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print ''; +} + + +$db->free($resql); + +$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '
'; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + { + $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 ''; +$searchpicto=$form->showFilterButtons(); +print $searchpicto; +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 '
'.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").'
'.$langs->trans("NoRecordFound").'
'."\n"; +print '
'."\n"; + +print '
'."\n"; + +if (in_array('builddoc',$arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) +{ + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); + + $filedir=$diroutputmassaction; + $genallowed=$user->rights->monmodule->read; + $delallowed=$user->rights->monmodule->read; + + print $formfile->showdocuments('massfilesarea_monmodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '
'.$langs->trans("ShowTempMassFilesArea").''; + } +} + +dol_fiche_end(); + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php index aae1b5db470..8c1cb138bc3 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -28,8 +28,8 @@ /** * \file htdocs/admin/mails_templates.php - * \ingroup setup - * \brief Page to administer data tables + * \ingroup core + * \brief Page to administer emails templates */ require '../main.inc.php'; @@ -39,20 +39,23 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; -if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -$langs->load("errors"); -$langs->load("admin"); -$langs->load("main"); -$langs->load("mails"); +// Load traductions files requiredby by page +$langs->loadLangs(array("errors","admin","mails","languages")); -$action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; -$confirm=GETPOST('confirm','alpha'); -$id=GETPOST('id','int'); -$rowid=GETPOST('rowid','alpha'); +$action = GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; +$confirm = GETPOST('confirm','alpha'); // Result of a confirmation + +$id = GETPOST('id','int'); +$rowid = GETPOST('rowid','alpha'); $search_label=GETPOST('search_label','alpha'); +$search_type_template=GETPOST('search_type_template','alpha'); +$search_lang=GETPOST('search_lang','alpha'); +$search_fk_user=GETPOST('search_fk_user','intcomma'); +$search_topic=GETPOST('search_topic','alpha'); -$allowed=$user->admin; +$allowed=1; if (! $allowed) accessforbidden(); $acts[0] = "activate"; @@ -61,17 +64,20 @@ $actl[0] = img_picto($langs->trans("Disabled"),'switch_off'); $actl[1] = img_picto($langs->trans("Activated"),'switch_on'); $listoffset=GETPOST('listoffset','alpha'); -$listlimit=GETPOST('listlimit','alpha')>0?GETPOST('listlimit','alpha'):1000; +$listlimit =GETPOST('listlimit','alpha')>0?GETPOST('listlimit','alpha'):1000; $active = 1; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); -if ($page == -1 || $page == null) { $page = 0 ; } +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $listlimit * $page ; $pageprev = $page - 1; $pagenext = $page + 1; +if (empty($sortfield)) $sortfield='label, lang, position'; +if (empty($sortorder)) $sortorder='ASC'; + // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('emailtemplates')); @@ -81,30 +87,24 @@ $tabname[25]= MAIN_DB_PREFIX."c_email_templates"; // Criteria to sort dictionaries $tabsqlsort=array(); -$tabsqlsort[25]="label ASC"; +$tabsqlsort[25]="label ASC, lang ASC, position ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire $tabfield=array(); -$tabfield[25]= "label,type_template,private,position,topic,content"; +$tabfield[25]= "label,type_template,lang,fk_user,private,position,topic,joinfiles,content"; if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfield[25].=',content_lines'; // Nom des champs d'edition pour modification d'un enregistrement $tabfieldvalue=array(); -$tabfieldvalue[25]= "label,type_template,private,position,topic,content"; +$tabfieldvalue[25]= "label,type_template,fk_user,lang,private,position,topic,joinfiles,content"; if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldvalue[25].=',content_lines'; // Nom des champs dans la table pour insertion d'un enregistrement $tabfieldinsert=array(); -$tabfieldinsert[25]= "label,type_template,private,position,topic,content"; +$tabfieldinsert[25]= "label,type_template,fk_user,lang,private,position,topic,joinfiles,content"; if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldinsert[25].=',content_lines'; $tabfieldinsert[25].=',entity'; // Must be at end because not into other arrays -// Nom du rowid si le champ n'est pas de type autoincrement -// Example: "" if id field is "rowid" and has autoincrement on -// "nameoffield" if id field is not "rowid" or has not autoincrement on -$tabrowid=array(); -$tabrowid[25]= ""; - // Condition to show dictionary in setup page $tabcond=array(); $tabcond[25]= true; @@ -116,22 +116,35 @@ $formmail=new FormMail($db); if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { $tmp=FormMail::getAvailableSubstitKey('formemail'); - $tmp['__(AnyTranslationKey)__']='__(AnyTranslationKey)__'; - $helpsubstit = $langs->trans("AvailableVariables").':
'.implode('
', $tmp); - $helpsubstitforlines = $langs->trans("AvailableVariables").':
'.implode('
', $tmp); + $tmp['__(AnyTranslationKey)__']='Translation'; + $helpsubstit = $langs->trans("AvailableVariables").':
'; + $helpsubstitforlines = $langs->trans("AvailableVariables").':
'; + foreach($tmp as $key => $val) + { + $helpsubstit.=$key.' -> '.$val.'
'; + $helpsubstitforlines.=$key.' -> '.$val.'
'; + } } else { $tmp=FormMail::getAvailableSubstitKey('formemailwithlines'); - $tmp['__(AnyTranslationKey)__']='__(AnyTranslationKey)__'; - $helpsubstit = $langs->trans("AvailableVariables").':
'.implode('
', $tmp); + $tmp['__(AnyTranslationKey)__']='Translation'; + $helpsubstit = $langs->trans("AvailableVariables").':
'; + $helpsubstitforlines = $langs->trans("AvailableVariables").':
'; + foreach($tmp as $key => $val) + { + $helpsubstit.=$key.' -> '.$val.'
'; + } $tmp=FormMail::getAvailableSubstitKey('formemailforlines'); - $helpsubstitforlines = $langs->trans("AvailableVariables").':
'.implode('
', $tmp); + foreach($tmp as $key => $val) + { + $helpsubstitforlines.=$key.' -> '.$val.'
'; + } } $tabhelp=array(); -$tabhelp[25] = array('topic'=>$helpsubstit,'content'=>$helpsubstit,'content_lines'=>$helpsubstitforlines,'type_template'=>$langs->trans("TemplateForElement"),'private'=>$langs->trans("TemplateIsVisibleByOwnerOnly"), 'position'=>$langs->trans("PositionIntoComboList")); +$tabhelp[25] = array('topic'=>$helpsubstit,'joinfiles'=>$langs->trans('AttachMainDocByDefault'), 'content'=>$helpsubstit,'content_lines'=>$helpsubstitforlines,'type_template'=>$langs->trans("TemplateForElement"),'private'=>$langs->trans("TemplateIsVisibleByOwnerOnly"), 'position'=>$langs->trans("PositionIntoComboList")); // List of check for fields (NOT USED YET) $tabfieldcheck=array(); @@ -144,16 +157,21 @@ $sourceList=array(); // We save list of template email Dolibarr can manage. This list can found by a grep into code on "->param['models']" $elementList = array(); -if ($conf->propal->enabled) $elementList['propal_send']=$langs->trans('MailToSendProposal'); -if ($conf->commande->enabled) $elementList['order_send']=$langs->trans('MailToSendOrder'); -if ($conf->facture->enabled) $elementList['facture_send']=$langs->trans('MailToSendInvoice'); -if ($conf->expedition->enabled) $elementList['shipping_send']=$langs->trans('MailToSendShipment'); -if ($conf->ficheinter->enabled) $elementList['fichinter_send']=$langs->trans('MailToSendIntervention'); +if ($conf->propal->enabled) $elementList['propal_send']=$langs->trans('MailToSendProposal'); +if ($conf->commande->enabled) $elementList['order_send']=$langs->trans('MailToSendOrder'); +if ($conf->facture->enabled) $elementList['facture_send']=$langs->trans('MailToSendInvoice'); +if ($conf->expedition->enabled) $elementList['shipping_send']=$langs->trans('MailToSendShipment'); +if ($conf->ficheinter->enabled) $elementList['fichinter_send']=$langs->trans('MailToSendIntervention'); if ($conf->supplier_proposal->enabled) $elementList['supplier_proposal_send']=$langs->trans('MailToSendSupplierRequestForQuotation'); -if ($conf->fournisseur->enabled) $elementList['order_supplier_send']=$langs->trans('MailToSendSupplierOrder'); -if ($conf->fournisseur->enabled) $elementList['invoice_supplier_send']=$langs->trans('MailToSendSupplierInvoice'); -if ($conf->societe->enabled) $elementList['thirdparty']=$langs->trans('MailToThirdparty'); -if ($conf->contrat->enabled) $elementList['contract']=$langs->trans('MailToSendContract'); +if ($conf->fournisseur->enabled) $elementList['order_supplier_send']=$langs->trans('MailToSendSupplierOrder'); +if ($conf->fournisseur->enabled) $elementList['invoice_supplier_send']=$langs->trans('MailToSendSupplierInvoice'); +if ($conf->societe->enabled) $elementList['thirdparty']=$langs->trans('MailToThirdparty'); +if ($conf->adherent->enabled) $elementList['member']=$langs->trans('MailToMember'); +if ($conf->contrat->enabled) $elementList['contract']=$langs->trans('MailToSendContract'); +$elementList['user']=$langs->trans('MailToUser'); +$elementList['all'] =$langs->trans('VisibleEverywhere'); +$elementList['none']=$langs->trans('VisibleNowhere'); + $parameters=array('elementList'=>$elementList); $reshook=$hookmanager->executeHooks('emailElementlist',$parameters); // Note that $action and $object may have been modified by some hooks @@ -170,8 +188,8 @@ $id = 25; * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -183,6 +201,10 @@ if (empty($reshook)) if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { $search_label=''; + $search_type_template=''; + $search_lang=''; + $search_fk_user=''; + $search_topic=''; $toselect=''; $search_array_options=array(); } @@ -199,12 +221,14 @@ if (empty($reshook)) $ok=1; foreach ($listfield as $f => $value) { + // Not mandatory fields + if ($value == 'joinfiles') continue; if ($value == 'content') continue; if ($value == 'content_lines') continue; - if ($value == 'content') $value='content-'.$rowid; - if ($value == 'content_lines') $value='content_lines-'.$rowid; - if (! isset($_POST[$value]) || $_POST[$value]=='') + if (GETPOST('actionmodify') && $value == 'topic') $_POST['topic']=$_POST['topic-'.$rowid]; + + if ((! isset($_POST[$value]) || $_POST[$value]=='' || $_POST[$value]=='-1') && $value != 'lang' && $value != 'fk_user' && $value != 'position') { $ok=0; $fieldnamekey=$listfield[$f]; @@ -213,7 +237,11 @@ if (empty($reshook)) if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; - if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; + if ($fieldnamekey == 'type_template') $fieldnamekey = 'TypeOfTemplate'; + if ($fieldnamekey == 'fk_user') $fieldnamekey = 'Owner'; + if ($fieldnamekey == 'private') $fieldnamekey = 'Private'; + if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; + if ($fieldnamekey == 'topic') $fieldnamekey = 'Topic'; setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); } @@ -222,46 +250,27 @@ if (empty($reshook)) // Si verif ok et action add, on ajoute la ligne if ($ok && GETPOST('actionadd')) { - if ($tabrowid[$id]) - { - // Recupere id libre pour insertion - $newid=0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); - - } else { - dol_print_error($db); - } - } - // Add new entry $sql = "INSERT INTO ".$tabname[$id]." ("; // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $tabrowid[$id].","; $sql.= $tabfieldinsert[$id]; $sql.=",active)"; $sql.= " VALUES("; // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $newid.","; $i=0; foreach ($listfieldinsert as $f => $value) { - //var_dump($i.' - '.$listfieldvalue[$i].' - '.$_POST[$listfieldvalue[$i]].' - '.$value); - if ($value == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } + //var_dump($i.' - '.$listfieldvalue[$i].' - '.$_POST[$listfieldvalue[$i]].' - '.$value); + $keycode=$listfieldvalue[$i]; + if ($value == 'lang') $keycode='langcode'; + if ($value == 'entity') $_POST[$keycode] = $conf->entity; if ($i) $sql.=","; - if ($value == 'private' && ! is_numeric($_POST[$listfieldvalue[$i]])) $_POST[$listfieldvalue[$i]]='0'; - if ($value == 'position' && ! is_numeric($_POST[$listfieldvalue[$i]])) $_POST[$listfieldvalue[$i]]='1'; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; // For vat, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($value == 'fk_user' && ! ($_POST[$keycode] > 0)) $_POST[$keycode]=''; + if ($value == 'private' && ! is_numeric($_POST[$keycode])) $_POST[$keycode]='0'; + if ($value == 'position' && ! is_numeric($_POST[$keycode])) $_POST[$keycode]='1'; + if ($_POST[$keycode] == '' && $keycode != 'langcode') $sql.="null"; // lang must be '' if not defined so the unique key that include lang will work + else $sql.="'".$db->escape($_POST[$keycode])."'"; $i++; } $sql.=",1)"; @@ -287,29 +296,27 @@ if (empty($reshook)) // Si verif ok et action modify, on modifie la ligne if ($ok && GETPOST('actionmodify')) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + $rowidcol="rowid"; // Modify entry $sql = "UPDATE ".$tabname[$id]." SET "; // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) - { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; - } $i = 0; foreach ($listfieldmodify as $field) { - if ($field == 'content') $_POST['content']=$_POST['content-'.$rowid]; - if ($field == 'content_lines') $_POST['content_lines']=$_POST['content_lines-'.$rowid]; - if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } + $keycode=$listfieldvalue[$i]; + if ($field == 'lang') $keycode='langcode'; + + if ($field == 'fk_user' && ! ($_POST['fk_user'] > 0)) $_POST['fk_user']=''; + if ($field == 'topic') $_POST['topic']=$_POST['topic-'.$rowid]; + if ($field == 'joinfiles') $_POST['joinfiles']=$_POST['joinfiles-'.$rowid]; + if ($field == 'content') $_POST['content']=$_POST['content-'.$rowid]; + if ($field == 'content_lines') $_POST['content_lines']=$_POST['content_lines-'.$rowid]; + if ($field == 'entity') $_POST[$keycode] = $conf->entity; if ($i) $sql.=","; $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; // For vat, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($_POST[$keycode] == '' || ($keycode == 'langcode' && empty($_POST[$keycode]))) $sql.="null"; // For vat, we want/accept code = '' + else $sql.="'".$db->escape($_POST[$keycode])."'"; $i++; } $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; @@ -317,7 +324,11 @@ if (empty($reshook)) dol_syslog("actionmodify", LOG_DEBUG); //print $sql; $resql = $db->query($sql); - if (! $resql) + if ($resql) + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + } + else { setEventMessages($db->error(), null, 'errors'); } @@ -326,8 +337,7 @@ if (empty($reshook)) if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + $rowidcol="rowid"; $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; @@ -349,15 +359,9 @@ if (empty($reshook)) // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + $rowidcol="rowid"; - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; - } + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; $result = $db->query($sql); if (!$result) @@ -369,15 +373,9 @@ if (empty($reshook)) // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + $rowidcol="rowid"; - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; - } + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; $result = $db->query($sql); if (!$result) @@ -403,18 +401,7 @@ $titlepicto='title_setup'; print load_fiche_titre($titre,$linkback,$titlepicto); -$h = 0; - -$head[$h][0] = DOL_URL_ROOT."/admin/mails.php"; -$head[$h][1] = $langs->trans("OutGoingEmailSetup"); -$head[$h][2] = 'common'; -$h++; - -$head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php"; -$head[$h][1] = $langs->trans("DictionaryEMailTemplates"); -$head[$h][2] = 'templates'; -$h++; - +$head = email_admin_prepare_head(); dol_fiche_head($head, 'templates', '', -1); @@ -426,18 +413,23 @@ if ($action == 'delete') //var_dump($elementList); -$sql="SELECT rowid as rowid, label, type_template, private, position, topic, content_lines, content, active"; +$sql="SELECT rowid as rowid, label, type_template, lang, fk_user, private, position, topic, joinfiles, content_lines, content, active"; $sql.=" FROM ".MAIN_DB_PREFIX."c_email_templates"; $sql.=" WHERE entity IN (".getEntity('email_template').")"; -if ($search_label) $sql.=natural_search('label', $search_label); - -if ($search_country_id > 0) +if (! $user->admin) { - if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; - else $sql.=" WHERE "; - $sql.= " c.rowid = ".$search_country_id; + $sql.=" AND (private = 0 OR (private = 1 AND fk_user = ".$user->id."))"; // Show only public and private to me + $sql.=" AND (active = 1 OR fk_user = ".$user->id.")"; // Show only active or owned by me } - +if (empty($conf->global->MAIN_MULTILANGS)) +{ + $sql.= " AND (lang = '".$langs->defaultlang."' OR lang IS NULL OR lang = '')"; +} +if ($search_label) $sql.=natural_search('label', $search_label); +if ($search_type_template != '' && $search_type_template != '-1') $sql.=natural_search('type_template', $search_type_template); +if ($search_lang) $sql.=natural_search('lang', $search_lang); +if ($search_fk_user != '' && $search_fk_user != '-1') $sql.=natural_search('fk_user', $search_fk_user, 2); +if ($search_topic) $sql.=natural_search('topic', $search_topic); if ($sortfield) { // If sort order is "country", we use country_code instead @@ -461,6 +453,10 @@ $sql.=$db->plimit($listlimit+1,$offset); $fieldlist=explode(',',$tabfield[$id]); +// Form to add a new line +$alabelisused=0; +$var=false; + print '
'; print ''; print ''; @@ -468,28 +464,26 @@ print ''; print ''; -// Form to add a new line -$alabelisused=0; -$var=false; - -$fieldlist=explode(',',$tabfield[$id]); - -if ($action != 'edit') +// Line to enter new values (title) +print ''; +foreach ($fieldlist as $field => $value) { - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut $valuetoshow=$langs->trans($valuetoshow); // try to translate $align="left"; - if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } + if ($fieldlist[$field]=='fk_user') { $valuetoshow=$langs->trans("Owner");} + if ($fieldlist[$field]=='lang') { $valuetoshow=(empty($conf->global->MAIN_MULTILANGS) ? ' ' : $langs->trans("Language")); } if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } + if ($fieldlist[$field]=='private') { $align='center'; } + if ($fieldlist[$field]=='position') { $align='center'; } + + if ($fieldlist[$field]=='topic') { $valuetoshow=''; } + if ($fieldlist[$field]=='joinfiles') { $valuetoshow=''; } if ($fieldlist[$field]=='content') { $valuetoshow=''; } if ($fieldlist[$field]=='content_lines') { $valuetoshow=''; } @@ -506,85 +500,102 @@ if ($action != 'edit') print ''; } if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; - } - - print ''; - print ''; - - // Line to enter new values - print ""; - - $obj = new stdClass(); - // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val) != '') - $obj->$val=GETPOST($val); - } - } - - $tmpaction = 'create'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; - - if (empty($reshook)) - { - if ($tabname[$id] == MAIN_DB_PREFIX.'c_email_templates' && $action == 'edit') - { - fieldList($fieldlist,$obj,$tabname[$id],'hide'); - } - else - { - fieldList($fieldlist,$obj,$tabname[$id],'add'); - } - } - - print ''; - print ""; - - $fieldsforcontent = array('content'); - if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) - { - $fieldsforcontent = array('content', 'content_lines'); - } - foreach ($fieldsforcontent as $tmpfieldlist) - { - print ''; - if ($tmpfieldlist == 'content') - { - print ''; - } - //else print ''; - print ''; - } - - $colspan=count($fieldlist)+1; - //print ''; // Keep   to have a line with enough height } +print ''; +print ''; + +$obj = new stdClass(); +// If data was already input, we define them in obj to populate input fields. +if (GETPOST('actionadd')) +{ + foreach ($fieldlist as $key => $val) { + if (GETPOST($val) != '') + $obj->$val = GETPOST($val); + } +} + +$tmpaction = 'create'; +$parameters = array( + 'fieldlist' => $fieldlist, + 'tabname' => $tabname[$id] +); +$reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks +$error = $hookmanager->error; +$errors = $hookmanager->errors; + + +// Line to enter new values (input fields) +print ""; + +if (empty($reshook)) +{ + if ($action == 'edit') { + fieldList($fieldlist, $obj, $tabname[$id], 'hide'); + } else { + fieldList($fieldlist, $obj, $tabname[$id], 'add'); + } +} + +print ''; +print ""; + +$fieldsforcontent = array('topic', 'joinfiles', 'content'); +if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { $fieldsforcontent = array('content','content_lines'); } +foreach ($fieldsforcontent as $tmpfieldlist) +{ + print ''; + if ($tmpfieldlist == 'topic') { + print ''; + } + // else print ''; + print ''; +} + + + +$colspan=count($fieldlist)+1; +//print ''; // Keep   to have a line with enough height print '
'; - print ''; - print '
'; - print '
'; - if ($tmpfieldlist == 'content') print ''.$form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'
'; - if ($tmpfieldlist == 'content_lines') print ''.$form->textwithpicto($langs->trans("ContentForLines"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'
'; - - if ($context != 'hide') - { - //print ''; - $okforextended=true; - if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended=false; - $doleditor = new DolEditor($tmpfieldlist, (! empty($obj->{$tmpfieldlist})?$obj->{$tmpfieldlist}:''), '', 120, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_4, '90%'); - print $doleditor->Create(1); - } - else print ' '; - print '
'; - if ($action != 'edit') - { - print ''; - } - print '
 
'; +print ''; +print '
'; +print '
'; + // Label + if ($tmpfieldlist == 'topic') + { + print '' . $form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . ' '; + } + if ($tmpfieldlist == 'joinfiles') + { + print '' . $form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . ' '; + } + if ($tmpfieldlist == 'content') + print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist); + if ($tmpfieldlist == 'content_lines') + print $form->textwithpicto($langs->trans("ContentForLines"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '
'; + // Input field + if ($tmpfieldlist == 'topic') { + print ''; + } + else if ($tmpfieldlist == 'joinfiles') { + print ''; + } + else + { + if ($context != 'hide') { + // print ''; + $okforextended = true; + if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) + $okforextended = false; + $doleditor = new DolEditor($tmpfieldlist, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 120, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_4, '90%'); + print $doleditor->Create(1); + } + else + print ' '; + } + print '
'; + if ($action != 'edit') { + print ''; + } + print '
 
'; print ''; @@ -593,6 +604,7 @@ print '
'; print '
'; + print '
'; print ''; print ''; @@ -630,12 +642,31 @@ if ($resql) foreach ($fieldlist as $field => $value) { if ($value == 'label') print '
'; + print $formadmin->select_language($search_lang, 'search_lang', 0, null, 1); + print ''; + $restrictid=array(); + if (! $user->admin) $restrictid=array($user->id); + //var_dump($restrictid); + print $form->select_dolusers($search_fk_user, 'search_fk_user', 1, null, 0, 'hierarchyme', null, 0, 0, 1, '', 0, '', 'maxwidth200'); + print ''.$form->selectarray('search_type_template', $elementList, $search_type_template, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone').''; + print ''; $searchpicto=$form->showFilterButtons(); print $searchpicto; print '
'; + print ''; print ''; print ''; print ''; @@ -711,10 +747,10 @@ if ($resql) print ''; print '
'; // To create an artificial CR for the current tr we are on - $okforextended = true; - if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) - $okforextended = false; - $doleditor = new DolEditor($tmpfieldlist.'-'.$rowid, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%'); - print $doleditor->Create(1); - print '
'; + if ($tmpfieldlist == 'topic') + { + print '' . $form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . ' '; + print ''; + } + if ($tmpfieldlist == 'joinfiles') + { + print '' . $form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . ' '; + print ''; + } + if ($tmpfieldlist == 'content') + { + $okforextended = true; + if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended = false; + $doleditor = new DolEditor($tmpfieldlist.'-'.$rowid, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%'); + print $doleditor->Create(1); + } + print ''.$valuetoshow.''.$valuetoshow.''; if ($canbedisabled) print ''.$actl[$obj->active].''; - else - { - if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); - else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); - else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); - else print $langs->trans("AlwaysActive"); - } print "'.img_edit().' '; + if ($canbemodified) print ''.img_edit().''; if ($iserasable) { - print ''; - if ($user->admin) print ''.img_delete().''; + print '   '.img_delete().''; //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin - print ' '; - print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT,'lang'); + if ($user->admin) + { + print $form->select_dolusers($obj->{$fieldlist[$field]}, 'fk_user', 1, null, 0, '', null, 0, 0, 1, '', 0, '', 'maxwidth200'); + } + else + { + if ($context == 'add') // I am not admin and we show the add form + { + print $user->getNomUrl(1); // Me + $forcedvalue=$user->id; + } + else + { + if ($obj && ! empty($obj->{$fieldlist[$field]}) && $obj->{$fieldlist[$field]} > 0) + { + $fuser=new User($db); + $fuser->fetch($obj->{$fieldlist[$field]}); + print $fuser->getNomUrl(1); + $forcedvalue=$fuser->id; + } + else + { + $forcedvalue=$obj->{$fieldlist[$field]}; + } + } + $keyname=$fieldlist[$field]; + print ''; + } + print ''; + if (! empty($conf->global->MAIN_MULTILANGS)) + { + $selectedlang = $langs->defaultlang; + if ($context == 'edit') $selectedlang = $obj->{$fieldlist[$field]}; + print $formadmin->select_language($selectedlang, 'langcode', 0, null, 1); + } + else + { + if (! empty($obj->{$fieldlist[$field]})) + { + print $obj->{$fieldlist[$field]}.' - '.$langs->trans('Language_'.$obj->{$fieldlist[$field]}); + } + $keyname=$fieldlist[$field]; + if ($keyname == 'lang') $keyname='langcode'; // Avoid conflict with lang param + print ''; + } print ''; - print $form->selectarray('type_template', $elementList,(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); + if ($context == 'edit' && ! empty($obj->{$fieldlist[$field]}) && ! in_array($obj->{$fieldlist[$field]}, array_keys($elementList))) + { + // Current tempalte type is an unknown type, so we must keep it as it is. + print ''; + print $obj->{$fieldlist[$field]}; + } + else + { + print $form->selectarray('type_template', $elementList, (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 1); + } print ''; - $size=''; $class=''; + $size=''; $class=''; $classtd=''; if ($fieldlist[$field]=='code') $class='maxwidth100'; - if ($fieldlist[$field]=='private') $class='maxwidth50'; - if ($fieldlist[$field]=='position') $class='maxwidth50'; + if ($fieldlist[$field]=='private') { $class='maxwidth50'; $classtd='center'; } + if ($fieldlist[$field]=='position') { $class='maxwidth50'; $classtd='center'; } if ($fieldlist[$field]=='libelle') $class='quatrevingtpercent'; if ($fieldlist[$field]=='topic') $class='quatrevingtpercent'; if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" '; - print ''; + + print ''; + if ($fieldlist[$field]=='private') + { + if (empty($user->admin)) + { + print $form->selectyesno($fieldlist[$field], '1', 1); + } + else + { + //print ''; + print $form->selectyesno($fieldlist[$field], (isset($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 1); + } + } + else + { + print ''; + } print '
'.$langs->trans("DefaultMenuManager").''; $formadmin->select_menu(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?$conf->global->MAIN_MENU_STANDARD:$conf->global->MAIN_MENU_STANDARD_FORCED, 'MAIN_MENU_STANDARD', $dirstandard, empty($conf->global->MAIN_MENU_STANDARD_FORCED)?'':' disabled'); @@ -190,7 +191,7 @@ if ($action == 'edit') print '
'.$langs->trans("DefaultMenuSmartphoneManager").''; $formadmin->select_menu(empty($conf->global->MAIN_MENU_SMARTPHONE_FORCED)?$conf->global->MAIN_MENU_SMARTPHONE:$conf->global->MAIN_MENU_SMARTPHONE_FORCED, 'MAIN_MENU_SMARTPHONE', array_merge($dirstandard,$dirsmartphone), empty($conf->global->MAIN_MENU_SMARTPHONE_FORCED)?'':' disabled'); @@ -217,7 +218,7 @@ else print '
'.$langs->trans("DefaultMenuManager").''; $filelib=preg_replace('/.php$/i','',(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?$conf->global->MAIN_MENU_STANDARD:$conf->global->MAIN_MENU_STANDARD_FORCED)); @@ -229,7 +230,7 @@ else print '
'.$langs->trans("DefaultMenuSmartphoneManager").''; diff --git a/htdocs/admin/modulehelp.php b/htdocs/admin/modulehelp.php index f60f5922160..bc48feb076f 100644 --- a/htdocs/admin/modulehelp.php +++ b/htdocs/admin/modulehelp.php @@ -35,7 +35,8 @@ if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is n require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $langs->load("errors"); $langs->load("admin"); @@ -269,7 +270,7 @@ if ($objMod->isCoreOrExternalModule() == 'external') $modulename=$objMod->getName(); $moduledesc=$objMod->getDesc(); $moduleauthor=$objMod->getPublisher(); - +$moduledir=strtolower(preg_replace('/^mod/i','',get_class($objMod))); print '
'; @@ -371,18 +372,20 @@ if ($mode == 'feature') if (count($objMod->requiredby)) $text.=join(',', $objMod->requiredby); else $text.=$langs->trans("None"); - $text.='


'; + $text.='

'; - $text.=''.$langs->trans("AddRemoveTabs").': '; - if (isset($objMod->tabs) && is_array($objMod->tabs) && count($objMod->tabs)) + $text.='
'.$langs->trans("AddDataTables").': '; + $sqlfiles = dol_dir_list(dol_buildpath($moduledir.'/sql/'), 'files', 0, 'llx.*\.sql', array('\.key\.sql')); + if (count($sqlfiles) > 0) { - $i=0; - foreach($objMod->tabs as $val) - { - $tmp=explode(':',$val,3); - $text.=($i?', ':'').$tmp[0].':'.$tmp[1]; - $i++; - } + $text.=$langs->trans("Yes").' ('; + $i=0; + foreach($sqlfiles as $val) + { + $text.=($i?', ':'').preg_replace('/\.sql$/','',preg_replace('/llx_/','',$val['name'])); + $i++; + } + $text.=')'; } else $text.=$langs->trans("No"); @@ -402,14 +405,29 @@ if ($mode == 'feature') $text.='
'; - $text.='
'.$langs->trans("AddBoxes").': '; - if (isset($objMod->boxes) && is_array($objMod->boxes) && count($objMod->boxes)) + $text.='
'.$langs->trans("AddData").': '; + $filedata = dol_buildpath($moduledir.'/sql/data.sql'); + if (dol_is_file($filedata)) + { + $text.=$langs->trans("Yes").' ('.$moduledir.'/sql/data.sql'.')'; + } + else $text.=$langs->trans("No"); + + $text.='
'; + + $text.='
'.$langs->trans("AddRemoveTabs").': '; + if (isset($objMod->tabs) && is_array($objMod->tabs) && count($objMod->tabs)) { $i=0; - foreach($objMod->boxes as $val) + foreach($objMod->tabs as $val) { - $text.=($i?', ':'').($val['file']?$val['file']:$val[0]); - $i++; + if (is_array($val)) $val=$val['data']; + if (is_string($val)) + { + $tmp=explode(':',$val,3); + $text.=($i?', ':'').$tmp[0].':'.$tmp[1]; + $i++; + } } } else $text.=$langs->trans("No"); @@ -449,9 +467,40 @@ if ($mode == 'feature') $text.='
'; $text.='
'.$langs->trans("AddTriggers").': '; + $moreinfoontriggerfile=''; if (isset($objMod->module_parts) && isset($objMod->module_parts['triggers']) && $objMod->module_parts['triggers']) { - $text.=$langs->trans("Yes"); + $yesno='Yes'; + } + else + { + $yesno='No'; + } + require_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; + $interfaces = new Interfaces($db); + $triggers = $interfaces->getTriggersList(array((($objMod->isCoreOrExternalModule() == 'external')?'/'.$moduledir:'').'/core/triggers')); + foreach($triggers as $triggercursor) + { + if ($triggercursor['module'] == $moduledir) + { + $yesno='Yes'; + $moreinfoontriggerfile=' ('.$triggercursor['relpath'].')'; + } + } + + $text.=$langs->trans($yesno).$moreinfoontriggerfile; + + $text.='
'; + + $text.='
'.$langs->trans("AddBoxes").': '; + if (isset($objMod->boxes) && is_array($objMod->boxes) && count($objMod->boxes)) + { + $i=0; + foreach($objMod->boxes as $val) + { + $text.=($i?', ':'').($val['file']?$val['file']:$val[0]); + $i++; + } } else $text.=$langs->trans("No"); @@ -463,10 +512,10 @@ if ($mode == 'feature') $i=0; foreach($objMod->module_parts['hooks'] as $key => $val) { - if ($key == 'entity') continue; + if ($key === 'entity') continue; // For special values - if ($key == 'data') + if ($key === 'data') { if (is_array($val)) { diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php index 6b290ab8f07..ce5d4ec55eb 100644 --- a/htdocs/admin/modules.php +++ b/htdocs/admin/modules.php @@ -32,6 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/admin/dolistore/class/dolistore.class.php'; $langs->load("errors"); $langs->load("admin"); @@ -46,6 +47,17 @@ $search_status=GETPOST('search_status','alpha'); $search_nature=GETPOST('search_nature','alpha'); $search_version=GETPOST('search_version','alpha'); + +// For dolistore search +$options = array(); +$options['per_page'] = 20; +$options['categorie'] = ((GETPOST('categorie', 'int')?GETPOST('categorie', 'int'):0) + 0); +$options['start'] = ((GETPOST('start', 'int')?GETPOST('start', 'int'):0) + 0); +$options['end'] = ((GETPOST('end', 'int')?GETPOST('end', 'int'):0) + 0); +$options['search'] = GETPOST('search_keyword', 'alpha'); +$dolistore = new Dolistore(); + + if (! $user->admin) accessforbidden(); @@ -240,6 +252,11 @@ if ($action == 'reset' && $user->admin) * View */ +$form = new Form($db); + +//$morejs = array("/admin/dolistore/js/dolistore.js.php"); +$morecss = array("/admin/dolistore/css/dolistore.css"); + // Set dir where external modules are installed if (! dol_is_dir($dirins)) { @@ -247,10 +264,8 @@ if (! dol_is_dir($dirins)) } $dirins_ok=(dol_is_dir($dirins)); -$form = new Form($db); - $help_url='EN:First_setup|FR:Premiers_paramétrages|ES:Primeras_configuraciones'; -llxHeader('',$langs->trans("Setup"),$help_url); +llxHeader('',$langs->trans("Setup"),$help_url, '', '', '', $morejs, $morecss, 0, 0); $arrayofnatures=array('core'=>$langs->transnoentitiesnoconv("Core"), 'external'=>$langs->transnoentitiesnoconv("External").' - '.$langs->trans("AllPublishers")); $arrayofwarnings=array(); // Array of warning each module want to show when activated @@ -423,24 +438,9 @@ print load_fiche_titre($langs->trans("ModulesSetup"),$moreinfo,'title_setup'); if ($mode=='common') print ''.$langs->trans("ModulesDesc")."
\n"; if ($mode=='marketplace') print ''.$langs->trans("ModulesMarketPlaceDesc")."
\n"; if ($mode=='deploy') print ''.$langs->trans("ModulesDeployDesc", $langs->transnoentitiesnoconv("AvailableModules"))."
\n"; +if ($mode=='develop') print ''.$langs->trans("ModulesDevelopDesc")."
\n"; - -$h = 0; - -$head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=common"; -$head[$h][1] = $langs->trans("AvailableModules"); -$head[$h][2] = 'common'; -$h++; - -$head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=marketplace"; -$head[$h][1] = $langs->trans("ModulesMarketPlaces"); -$head[$h][2] = 'marketplace'; -$h++; - -$head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=deploy"; -$head[$h][1] = $langs->trans("AddExtensionThemeModuleOrOther"); -$head[$h][2] = 'deploy'; -$h++; +$head = modules_prepare_head(); print "
\n"; @@ -623,7 +623,7 @@ if ($mode == 'common') $imginfo="info_black"; } - print '
'; @@ -817,7 +817,6 @@ if ($mode == 'marketplace') print ''.$langs->trans("URL").'
'.$url.'
'.$langs->trans("DoliPartnersDesc").''.$url.'
\n"; dol_fiche_end(); + + print '
'; + + if (empty($conf->global->MAIN_DISABLE_DOLISTORE_SEARCH) && $conf->global->MAIN_FEATURES_LEVEL >= 1) + { + // $options is array with filter criterias + //var_dump($options); + $dolistore->getRemoteData($options); + + print ''.$langs->trans('DOLISTOREdescriptionLong').'

'; + + $previouslink = $dolistore->get_previous_link(); + $nextlink = $dolistore->get_next_link(); + + print '
' + + ?> + + +
trans('Keyword') ?>: +
+
+
+ + trans('Reset') ?> + +   +
+
+ +
+ + +
'; + print '
'; + + ?> + +
+
    + get_categories(); ?> +
+
+
+ + + get_products($categorie); ?> + +
+
+ + \n"; + print "\n"; + //print ''.$langs->trans("Logo").''; + print ''.$langs->trans("DevelopYourModuleDesc").''; + print ''.$langs->trans("URL").''; + print ''; + + print "\n"; + $url='https://partners.dolibarr.org'; + print ''; + print ''.$langs->trans("DoliPartnersDesc").''; + print ''.$url.''; + print ''; + + print "\n"; + + dol_fiche_end(); +} + + + llxFooter(); $db->close(); diff --git a/htdocs/admin/multicurrency.php b/htdocs/admin/multicurrency.php index 0a9bd205844..52ac09074f3 100644 --- a/htdocs/admin/multicurrency.php +++ b/htdocs/admin/multicurrency.php @@ -312,7 +312,7 @@ if (!empty($conf->global->MAIN_MULTICURRENCY_ALLOW_SYNCHRONIZATION)) print ''; print ''; - print '
'; + print '
'; } diff --git a/htdocs/admin/order_extrafields.php b/htdocs/admin/order_extrafields.php index 043d6bbadd9..c2ecb2a5bc0 100644 --- a/htdocs/admin/order_extrafields.php +++ b/htdocs/admin/order_extrafields.php @@ -44,7 +44,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/orderdet_extrafields.php b/htdocs/admin/orderdet_extrafields.php index 5120fd5c931..db86f7ba2fe 100644 --- a/htdocs/admin/orderdet_extrafields.php +++ b/htdocs/admin/orderdet_extrafields.php @@ -45,7 +45,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/payment.php b/htdocs/admin/payment.php index 2ef7a500268..3246caeb411 100644 --- a/htdocs/admin/payment.php +++ b/htdocs/admin/payment.php @@ -233,7 +233,7 @@ foreach ($dirmodels as $reldir) print ''; -print "
"; +print "
"; print load_fiche_titre($langs->trans("OtherOptions"),'',''); diff --git a/htdocs/admin/pdf.php b/htdocs/admin/pdf.php index a7ed12a5336..8028c81cf04 100644 --- a/htdocs/admin/pdf.php +++ b/htdocs/admin/pdf.php @@ -110,10 +110,10 @@ $formother=new FormOther($db); $formadmin=new FormAdmin($db); $arraydetailsforpdffoot = array( - 0 => $langs->trans('NoDetails'), - 1 => $langs->trans('DisplayCompanyInfo'), - 2 => $langs->trans('DisplayCompanyManagers'), - 3 => $langs->trans('DisplayCompanyInfoAndManagers') + 0 => $langs->transnoentitiesnoconv('NoDetails'), + 1 => $langs->transnoentitiesnoconv('DisplayCompanyInfo'), + 2 => $langs->transnoentitiesnoconv('DisplayCompanyManagers'), + 3 => $langs->transnoentitiesnoconv('DisplayCompanyInfoAndManagers') ); print load_fiche_titre($langs->trans("PDF"),'','title_setup'); @@ -589,7 +589,7 @@ else // Show print ''.$langs->trans("ShowDetailsInPDFPageFoot").''; - print $arraydetailsforpdffoot[$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS]; + print $arraydetailsforpdffoot[($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS ? $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS : 0)]; print ''; print ''; diff --git a/htdocs/admin/propal.php b/htdocs/admin/propal.php index b3434d0bd7a..8d09e81e142 100644 --- a/htdocs/admin/propal.php +++ b/htdocs/admin/propal.php @@ -545,7 +545,7 @@ print "\n"; print ''; */ -$substitutionarray=pdf_getSubstitutionArray($langs); +$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; @@ -555,7 +555,7 @@ print '
'; print ''; print ''; print ''; -print $form->textwithpicto($langs->trans("FreeLegalTextOnProposal"), $langs->trans("AddCRIfTooLong").'

'.$htmltext).'
'; +print $form->textwithpicto($langs->trans("FreeLegalTextOnProposal"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='PROPOSAL_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { @@ -577,7 +577,7 @@ print ""; print ''; print ""; print ''; -print $form->textwithpicto($langs->trans("WatermarkOnDraftProposal"), $htmltext).'
'; +print $form->textwithpicto($langs->trans("WatermarkOnDraftProposal"), $htmltext, 1, 'help', '', 0, 2, 'watermarktooltip').'
'; print ''; print ''; print ''; diff --git a/htdocs/admin/resource_extrafields.php b/htdocs/admin/resource_extrafields.php index c3d90fac3e5..6f8eeaa167e 100644 --- a/htdocs/admin/resource_extrafields.php +++ b/htdocs/admin/resource_extrafields.php @@ -43,7 +43,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/security_file.php b/htdocs/admin/security_file.php index f6de54220d1..1053658b191 100644 --- a/htdocs/admin/security_file.php +++ b/htdocs/admin/security_file.php @@ -1,7 +1,7 @@ - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2013 Juanjo Menent +/* Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2013 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -54,7 +54,7 @@ if (GETPOST('sendit') && ! empty($conf->global->MAIN_UPLOAD_DOC)) if (preg_match('/set_(.*)/',$action,$reg)) { $code=$reg[1]; - $value=(GETPOST($code) ? GETPOST($code) : 1); + $value=(GETPOST($code, 'alpha') ? GETPOST($code, 'alpha') : 1); if (dolibarr_set_const($db, $code, $value, 'chaine', 0, '', $conf->entity) > 0) { Header("Location: ".$_SERVER["PHP_SELF"]); @@ -82,10 +82,10 @@ else if (preg_match('/del_(.*)/',$action,$reg)) else if ($action == 'updateform') { - $res3=dolibarr_set_const($db, 'MAIN_UPLOAD_DOC',$_POST["MAIN_UPLOAD_DOC"],'chaine',0,'',$conf->entity); - $res4=dolibarr_set_const($db, "MAIN_UMASK", $_POST["MAIN_UMASK"],'chaine',0,'',$conf->entity); - $res5=dolibarr_set_const($db, "MAIN_ANTIVIRUS_COMMAND", $_POST["MAIN_ANTIVIRUS_COMMAND"],'chaine',0,'',$conf->entity); - $res6=dolibarr_set_const($db, "MAIN_ANTIVIRUS_PARAM", $_POST["MAIN_ANTIVIRUS_PARAM"],'chaine',0,'',$conf->entity); + $res3=dolibarr_set_const($db, 'MAIN_UPLOAD_DOC',GETPOST('MAIN_UPLOAD_DOC','alpha'),'chaine',0,'',$conf->entity); + $res4=dolibarr_set_const($db, "MAIN_UMASK", GETPOST('MAIN_UMASK','alpha'),'chaine',0,'',$conf->entity); + $res5=dolibarr_set_const($db, "MAIN_ANTIVIRUS_COMMAND", trim(GETPOST('MAIN_ANTIVIRUS_COMMAND','none')),'chaine',0,'',$conf->entity); // Use GETPOST none because we must accept " + $res6=dolibarr_set_const($db, "MAIN_ANTIVIRUS_PARAM", trim(GETPOST('MAIN_ANTIVIRUS_PARAM','none')),'chaine',0,'',$conf->entity); // Use GETPOST none because we must accept " if ($res3 && $res4 && $res5 && $res6) setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); } @@ -103,6 +103,7 @@ else if ($action == 'delete') exit; } + /* * View */ @@ -177,7 +178,7 @@ if (ini_get('safe_mode') && ! empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) dol_syslog("safe_mode is on, basedir is ".$basedir.", safe_mode_exec_dir is ".ini_get('safe_mode_exec_dir'), LOG_WARNING); } } -print ''; +print ''; print ""; print ''; @@ -188,7 +189,7 @@ print ''.$langs->trans("AntiVirusParam").'
'; print $langs->trans("AntiVirusParamExample"); print ''; print ''; -print ''; +print ''; print ""; print ''; diff --git a/htdocs/admin/stock.php b/htdocs/admin/stock.php index 36a4ec697e6..a2f0a4b5346 100644 --- a/htdocs/admin/stock.php +++ b/htdocs/admin/stock.php @@ -45,6 +45,10 @@ if($action) { $db->begin(); + if ($action == 'STOCK_SUPPORTS_SERVICES') + { + $res = dolibarr_set_const($db, "STOCK_SUPPORTS_SERVICES", GETPOST('STOCK_SUPPORTS_SERVICES','alpha'),'chaine',0,'',$conf->entity); + } if ($action == 'STOCK_USERSTOCK_AUTOCREATE') { $res = dolibarr_set_const($db, "STOCK_USERSTOCK_AUTOCREATE", GETPOST('STOCK_USERSTOCK_AUTOCREATE','alpha'),'chaine',0,'',$conf->entity); @@ -164,8 +168,8 @@ $found=0; print ''; -print ''.$langs->trans("DeStockOnBill").''; -print ''; +print ''.$langs->trans("DeStockOnBill").''; +print ''; if (! empty($conf->facture->enabled)) { print ""; @@ -184,8 +188,8 @@ $found++; print ''; -print ''.$langs->trans("DeStockOnValidateOrder").''; -print ''; +print ''.$langs->trans("DeStockOnValidateOrder").''; +print ''; if (! empty($conf->commande->enabled)) { print ""; @@ -206,8 +210,8 @@ $found++; //{ print ''; -print ''.$langs->trans("DeStockOnShipment").''; -print ''; +print ''.$langs->trans("DeStockOnShipment").''; +print ''; if (! empty($conf->expedition->enabled)) { print ""; @@ -226,8 +230,8 @@ $found++; print ''; -print ''.$langs->trans("DeStockOnShipmentOnClosing").''; -print ''; +print ''.$langs->trans("DeStockOnShipmentOnClosing").''; +print ''; if (! empty($conf->expedition->enabled)) { print ""; @@ -246,7 +250,7 @@ $found++; /*if (! $found) { - + print ''; print ''.$langs->trans("NoModuleToManageStockDecrease").''; print "\n"; @@ -268,8 +272,8 @@ $found=0; print ''; -print ''.$langs->trans("ReStockOnBill").''; -print ''; +print ''.$langs->trans("ReStockOnBill").''; +print ''; if (! empty($conf->fournisseur->enabled)) { print ""; @@ -289,8 +293,8 @@ $found++; print ''; -print ''.$langs->trans("ReStockOnValidateOrder").''; -print ''; +print ''.$langs->trans("ReStockOnValidateOrder").''; +print ''; if (! empty($conf->fournisseur->enabled)) { print ""; @@ -309,8 +313,8 @@ $found++; print ''; -print ''.$langs->trans("ReStockOnDispatchOrder").''; -print ''; +print ''.$langs->trans("ReStockOnDispatchOrder").''; +print ''; if (! empty($conf->fournisseur->enabled)) { print ""; @@ -329,7 +333,7 @@ $found++; /*if (! $found) { - + print ''; print ''.$langs->trans("NoModuleToManageStockIncrease").''; print "\n"; @@ -346,8 +350,8 @@ print ''."\n"; print ''; -print ''.$langs->trans("WarehouseAllowNegativeTransfer").''; -print ''; +print ''.$langs->trans("WarehouseAllowNegativeTransfer").''; +print ''; print ""; print ''; print ""; @@ -361,8 +365,8 @@ print "\n"; if($conf->invoice->enabled) { $var = !$var; print ''; - print ''.$langs->trans("StockMustBeEnoughForInvoice").''; - print ''; + print ''.$langs->trans("StockMustBeEnoughForInvoice").''; + print ''; print ""; print ''; print ""; @@ -376,8 +380,8 @@ if($conf->invoice->enabled) { if($conf->order->enabled) { $var = !$var; print ''; - print ''.$langs->trans("StockMustBeEnoughForOrder").''; - print ''; + print ''.$langs->trans("StockMustBeEnoughForOrder").''; + print ''; print ""; print ''; print ""; @@ -391,8 +395,8 @@ if($conf->order->enabled) { if($conf->expedition->enabled) { $var = !$var; print ''; - print ''.$langs->trans("StockMustBeEnoughForShipment").''; - print ''; + print ''.$langs->trans("StockMustBeEnoughForShipment").''; + print ''; print ""; print ''; print ""; @@ -404,6 +408,9 @@ if($conf->expedition->enabled) { } print ''; + +print '
'; + $virtualdiffersfromphysical=0; if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) @@ -411,7 +418,6 @@ if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) if ($virtualdiffersfromphysical) { - print '
'; print ''; print ''; print " \n"; @@ -419,8 +425,8 @@ if ($virtualdiffersfromphysical) print ''."\n"; $var = !$var; print ''; - print ''; - print ''; + print '\n"; print "\n"; print '
".$langs->trans("RuleForStockReplenishment")." ".img_help('help',$langs->trans("VirtualDiffersFromPhysical"))."
'.$langs->trans("UseVirtualStockByDefault").''; + print ''.$langs->trans("UseVirtualStockByDefault").''; print ""; print ''; print ""; @@ -430,10 +436,71 @@ if ($virtualdiffersfromphysical) print "
'; + print '
'; } -print '
'; +print ''; + +print ''; +print " \n"; +print " \n"; +print ''."\n"; + +print ''; +print ''; +print '\n"; +print "\n"; + +print ''; +print ''; +print '\n"; +print "\n"; + +print ''; +print ''; +print '\n"; +print "\n"; + +if (! empty($conf->fournisseur->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { + + print ''; + print ''; + print '\n\n"; +} + +print '
".$langs->trans("Other")." 
'.$langs->trans("UserWarehouseAutoCreate").''; +print ""; +print ''; +print ""; +print $form->selectyesno("STOCK_USERSTOCK_AUTOCREATE",$conf->global->STOCK_USERSTOCK_AUTOCREATE,1); +print ''; +print ''; +print "
'; +print $form->textwithpicto($langs->trans("StockSupportServices"), $langs->trans("StockSupportServicesDesc")).''; +print "
"; +print ''; +print ""; +print $form->selectyesno("STOCK_SUPPORTS_SERVICES",$conf->global->STOCK_SUPPORTS_SERVICES,1); +print ''; +print '
'; +print "
'.$langs->trans("AllowAddLimitStockByWarehouse").''; +print "
"; +print ''; +print ""; +print $form->selectyesno("STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE",$conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE,1); +print ''; +print '
'; +print "
'.$langs->trans("UseDispatchStatus").''; + print "
"; + print ''; + print ""; + print $form->selectyesno("SUPPLIER_ORDER_USE_DISPATCH_STATUS",$conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS,1); + print ''; + print "
\n"; + print "
'; + +print '
'; if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { print ''; @@ -441,7 +508,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print ''."\n"; print ''; print ''."\n"; - + // Example with a yes / no select print ''; print ''; @@ -454,7 +521,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print ''; print ''; print ''; - + // Example with a yes / no select print ''; print ''; @@ -467,7 +534,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print ''; print ''; print ''; - + // Example with a yes / no select print ''; print ''; @@ -480,68 +547,19 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print ''; print ''; print ''; - + print '
'.$langs->trans("Inventory").'  
'.$langs->trans("INVENTORY_DISABLE_VIRTUAL").'
'.$langs->trans("INVENTORY_USE_MIN_PA_IF_NO_LAST_PA").'
'.$langs->trans("INVENTORY_USE_INVENTORY_DATE_FROM_DATEMVT").'
'; } -print ''; - -print ''; -print " \n"; -print " \n"; -print ''."\n"; - -if (! empty($conf->fournisseur->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { - - print ''; - print ''; - print '\n\n"; -} - -print ''; -print ''; -print '\n"; -print "\n"; - -print ''; -print ''; - -print '\n"; -print "\n"; - -print '
'; - /* I keep the option/feature, but hidden to end users for the moment. If feature is used by module, no need to have users see it. If not used by a module, I still need to understand in which case user may need this now we can set rule on product page. if ($conf->global->PRODUIT_SOUSPRODUITS) { - + print ''; - print ''; - - print ''; + print '
".$langs->trans("Other")." 
'.$langs->trans("UseDispatchStatus").''; - print "
"; - print ''; - print ""; - print $form->selectyesno("SUPPLIER_ORDER_USE_DISPATCH_STATUS",$conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS,1); - print ''; - print "
\n"; - print "
'.$langs->trans("UserWarehouseAutoCreate").''; -print "
"; -print ''; -print ""; -print $form->selectyesno("STOCK_USERSTOCK_AUTOCREATE",$conf->global->STOCK_USERSTOCK_AUTOCREATE,1); -print ''; -print '
'; -print "
'.$langs->trans("AllowAddLimitStockByWarehouse").''; -print "
"; -print ''; -print ""; -print $form->selectyesno("STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE",$conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE,1); -print ''; -print '
'; -print "
'.$langs->trans("IndependantSubProductStock").''; + print ''.$langs->trans("IndependantSubProductStock").''; print "
"; print ''; print ""; @@ -553,8 +571,6 @@ if ($conf->global->PRODUIT_SOUSPRODUITS) } */ -print '
'; - llxFooter(); diff --git a/htdocs/admin/supplier_invoice.php b/htdocs/admin/supplier_invoice.php index d3ea8b9a63e..a0b8d9e2e4f 100644 --- a/htdocs/admin/supplier_invoice.php +++ b/htdocs/admin/supplier_invoice.php @@ -471,14 +471,14 @@ print ''.$langs->trans("Value").''; print ' '; print "\n"; -$substitutionarray=pdf_getSubstitutionArray($langs); +$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; $htmltext.='
'; print ''; -print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'

'.$htmltext).'
'; +print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='SUPPLIER_INVOICE_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { diff --git a/htdocs/admin/supplier_order.php b/htdocs/admin/supplier_order.php index 6b99bb1c39c..a9dfe95a2c3 100644 --- a/htdocs/admin/supplier_order.php +++ b/htdocs/admin/supplier_order.php @@ -537,14 +537,14 @@ else } */ -$substitutionarray=pdf_getSubstitutionArray($langs); +$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; $htmltext.='
'; print ''; -print $form->textwithpicto($langs->trans("FreeLegalTextOnOrders"), $langs->trans("AddCRIfTooLong").'

'.$htmltext).'
'; +print $form->textwithpicto($langs->trans("FreeLegalTextOnOrders"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='SUPPLIER_ORDER_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { diff --git a/htdocs/admin/supplier_proposal.php b/htdocs/admin/supplier_proposal.php index 44d8b2f3627..862b90e179f 100644 --- a/htdocs/admin/supplier_proposal.php +++ b/htdocs/admin/supplier_proposal.php @@ -500,7 +500,7 @@ print ''.$langs->trans("Value")."\n"; print " \n"; print ""; -$substitutionarray=pdf_getSubstitutionArray($langs); +$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; @@ -511,7 +511,7 @@ print ''; print ''; print ''; print ''; -print $form->textwithpicto($langs->trans("FreeLegalTextOnSupplierProposal"), $langs->trans("AddCRIfTooLong").'

'.$htmltext).'
'; +print $form->textwithpicto($langs->trans("FreeLegalTextOnSupplierProposal"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='SUPPLIER_PROPOSAL_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { @@ -533,7 +533,7 @@ print ""; print ''; print ""; print ''; -print $form->textwithpicto($langs->trans("WatermarkOnDraftProposal"), $htmltext).'
'; +print $form->textwithpicto($langs->trans("WatermarkOnDraftProposal"), $htmltext, 1, 'help', '', 0, 2, 'watermarktooltip').'
'; print ''; print ''; print ''; diff --git a/htdocs/admin/supplierinvoice_extrafields.php b/htdocs/admin/supplierinvoice_extrafields.php index 4e0bd1d0dd2..ad04e1f5256 100644 --- a/htdocs/admin/supplierinvoice_extrafields.php +++ b/htdocs/admin/supplierinvoice_extrafields.php @@ -48,7 +48,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/supplierinvoicedet_extrafields.php b/htdocs/admin/supplierinvoicedet_extrafields.php index 26b3b42e970..469a00732dd 100644 --- a/htdocs/admin/supplierinvoicedet_extrafields.php +++ b/htdocs/admin/supplierinvoicedet_extrafields.php @@ -48,7 +48,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/supplierorder_extrafields.php b/htdocs/admin/supplierorder_extrafields.php index bcad8121afc..55ca530e27f 100644 --- a/htdocs/admin/supplierorder_extrafields.php +++ b/htdocs/admin/supplierorder_extrafields.php @@ -44,7 +44,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/supplierorderdet_extrafields.php b/htdocs/admin/supplierorderdet_extrafields.php index 97d505144bb..55491385027 100644 --- a/htdocs/admin/supplierorderdet_extrafields.php +++ b/htdocs/admin/supplierorderdet_extrafields.php @@ -45,7 +45,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/admin/system/dolibarr.php b/htdocs/admin/system/dolibarr.php index 36260c0a228..5daaca5e29e 100644 --- a/htdocs/admin/system/dolibarr.php +++ b/htdocs/admin/system/dolibarr.php @@ -54,7 +54,7 @@ if ($action == 'getlastversion') $sfurl = simplexml_load_string($result['content']); } - + /* * View */ @@ -107,19 +107,21 @@ if (function_exists('curl_init')) } // Show version - print $langs->trans("LastStableVersion").' : '. (($version != '0.0')?$version:$langs->trans("Unknown")) .'
'; + print $langs->trans("LastStableVersion").' : '. (($version != '0.0')?$version:$langs->trans("Unknown")) .''; } else { - print $langs->trans("LastStableVersion").' : ' .$langs->trans("UpdateServerOffline").'
'; + print $langs->trans("LastStableVersion").' : ' .$langs->trans("UpdateServerOffline").''; } } else { - print $langs->trans("LastStableVersion").' : ' .$langs->trans("Check").'
'; + print $langs->trans("LastStableVersion").' : ' .$langs->trans("Check").''; } } +print '     -     '; +print ''.$langs->trans("SeeChangeLog").''; print ''."\n"; print ''.$langs->trans("VersionLastUpgrade").' ('.$langs->trans("Database").')'.$conf->global->MAIN_VERSION_LAST_UPGRADE.''."\n"; print ''.$langs->trans("VersionLastInstall").''.$conf->global->MAIN_VERSION_LAST_INSTALL.''."\n"; @@ -343,7 +345,7 @@ foreach($configfileparameters as $key => $value) { $newkey = preg_replace('/^\?/','',$key); - if (preg_match('/^\?/',$key) && empty(${$newkey})) + if (preg_match('/^\?/',$key) && empty(${$newkey})) { if ($newkey != 'multicompany_transverse_mode' || empty($conf->multicompany->enabled)) continue; // We discard parameters starting with ? diff --git a/htdocs/admin/system/perf.php b/htdocs/admin/system/perf.php index 25079d8f185..3a8e1e42bf4 100644 --- a/htdocs/admin/system/perf.php +++ b/htdocs/admin/system/perf.php @@ -336,7 +336,7 @@ jQuery(document).ready(function() { var compjsphpstring; getjsphpurl = $.ajax({ type: "GET", - url: \''.DOL_URL_ROOT.'/core/js/datepicker.js.php\', + url: \''.DOL_URL_ROOT.'/core/js/lib_head.js.php\', cache: false, /* async: false, */ /* crossDomain: true,*/ diff --git a/htdocs/admin/system/web.php b/htdocs/admin/system/web.php index 7a5816ad3e8..ca911af97b8 100644 --- a/htdocs/admin/system/web.php +++ b/htdocs/admin/system/web.php @@ -53,11 +53,19 @@ print ''.$langs->trans("IP")."".$_SERVER["SERVE print ''.$langs->trans("Port")."" . $_SERVER["SERVER_PORT"] . "\n"; print ''.$langs->trans("DocumentRootServer")."".$_SERVER["DOCUMENT_ROOT"]."\n"; print ''.$langs->trans("DataRootServer")."" . DOL_DATA_ROOT . "\n"; +// Web user group by default $labeluser=dol_getwebuser('user'); $labelgroup=dol_getwebuser('group'); if ($labeluser && $labelgroup) { - print ''.$langs->trans("WebUserGroup")."".$labeluser.'/'.$labelgroup."\n"; + print ''.$langs->trans("WebUserGroup")." (env vars)".$labeluser.'/'.$labelgroup."\n"; +} +// Web user group real (detected by 'id' external command) +$arrayout=array(); $varout=0; +exec('id', $arrayout, $varout); +if (empty($varout)) // Test command is ok. Work only on Linux OS. +{ + print ''.$langs->trans("WebUserGroup")." (real, 'id' command)".join(',', $arrayout)."\n"; } print ''; print '
'; diff --git a/htdocs/admin/tools/listsessions.php b/htdocs/admin/tools/listsessions.php index 6106fbe8dd8..76f7debf3e7 100644 --- a/htdocs/admin/tools/listsessions.php +++ b/htdocs/admin/tools/listsessions.php @@ -47,7 +47,7 @@ $langs->load("other"); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); -if ($page == -1 || $page == null) { $page = 0 ; } +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $conf->liste_limit * $page ; $pageprev = $page - 1; $pagenext = $page + 1; diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index 651335d0a6d..d42ae4b2ade 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -1,6 +1,7 @@ * Copyright (C) 2009-2017 Regis Houssin + * Copyright (C) 2017 Frédéric France * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -64,8 +65,8 @@ $hookmanager->initHooks(array('admintranslation','globaladmin')); * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -88,7 +89,45 @@ if ($action == 'setMAIN_ENABLE_OVERWRITE_TRANSLATION') else dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 0, 'chaine', 0, '', $conf->entity); } -if ($action == 'add' || (GETPOST('add') && $action != 'update')) +if ($action == 'update') +{ + if ($transvalue == '') + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NewTranslationStringToShow")), null, 'errors'); + $error++; + } + if (! $error) + { + $db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."overwrite_trans set transvalue = '".$db->escape($transvalue)."' WHERE rowid = ".GETPOST('rowid','int'); + $result = $db->query($sql); + if ($result > 0) + { + $db->commit(); + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + $action=""; + $transkey=""; + $transvalue=""; + } + else + { + + $db->rollback(); + if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings'); + } + else + { + setEventMessages($db->lasterror(), null, 'errors'); + } + $action=''; + } + } +} + +if ($action == 'add') { $error=0; @@ -132,7 +171,7 @@ if ($action == 'add' || (GETPOST('add') && $action != 'update')) else { setEventMessages($db->lasterror(), null, 'errors'); - } + } $action=''; } } @@ -170,7 +209,8 @@ llxHeader('',$langs->trans("Setup"),$wikihelp); $param='&mode='.$mode; -$enabledisablehtml = $langs->trans("EnableOverwriteTranslation").' '; +$enabledisablehtml=''; +$enabledisablehtml.= $langs->trans("EnableOverwriteTranslation").' '; if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { // Button off, click to enable @@ -188,7 +228,9 @@ else print load_fiche_titre($langs->trans("Translation"), $enabledisablehtml, 'title_setup'); +//print ''; print $langs->trans("TranslationDesc")."
\n"; +//print '
'; print "
\n"; $current_language_code=$langs->defaultlang; @@ -209,7 +251,6 @@ print 'entity) && $debug)?'? if ($optioncss != '') print ''; print ''; print ''; -print ''; print ''; print ''; print ''; @@ -222,16 +263,18 @@ if ($mode == 'overwrite') { //print load_fiche_titre($langs->trans("TranslationOverwriteKey"), '', '')."\n"; + print '
'; print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); $urlwikitranslatordoc='https://wiki.dolibarr.org/index.php/Translator_documentation'; - print ' ('.$langs->trans("SeeAlso").': '.$urlwikitranslatordoc.')
'; + print ' ('.$langs->trans("SeeAlso").': '.$langs->trans("Here").')
'; print $langs->trans("TranslationOverwriteDesc",$langs->transnoentitiesnoconv("Language"),$langs->transnoentitiesnoconv("Key"),$langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n"; print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."
\n"; + print '
'; + print '
'; - print ''; - print ''; + print ''; print ''; print '
'; @@ -248,13 +291,16 @@ if ($mode == 'overwrite') // Line to add new record print "\n"; + $disablededit=''; + if ($action == 'edit') $disablededit=' disabled'; + print ''; - print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, 0, 'maxwidthonsmartphone', 1); + print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit?1:0, 'maxwidthonsmartphone', 1); print ''."\n"; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; // Limit to superadmin /*if (! empty($conf->multicompany->enabled) && !$user->entity) @@ -270,7 +316,7 @@ if ($mode == 'overwrite') print ''; //} $disabled=''; - if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disabled=' disabled="disabled"'; + if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disabled=' disabled="disabled"'; print ''; print "\n"; print ''; @@ -280,7 +326,7 @@ if ($mode == 'overwrite') $sql = "SELECT rowid, entity, lang, transkey, transvalue"; $sql.= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; $sql.= " WHERE 1 = 1"; - //$sql.= " AND entity IN (".$user->entity.",".$conf->entity.")"; + $sql.= " AND entity IN (".getEntity('overwrite_trans').")"; $sql.= $db->order($sortfield, $sortorder); dol_syslog("translation::select from table", LOG_DEBUG); @@ -308,11 +354,30 @@ if ($mode == 'overwrite') print ''; print ''; */ - print $obj->transvalue; + if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) + { + print ''; + } + else + { + print $obj->transvalue; + } print ''; print ''; - print ''.img_delete().''; + if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) + { + print ''; + print ''; + print '   '; + print ''; + } + else + { + print ''.img_edit().''; + print '   '; + print ''.img_delete().''; + } print ''; print "\n"; @@ -393,7 +458,6 @@ if ($mode == 'searchkey') if ($nbtotalofrecords > 0) $title.=' ('.$nbtotalofrecords.' / '.$nbtotalofrecordswithoutfilters.')'; print print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit)."\n"; - print ''; print ''; print ''; @@ -430,7 +494,7 @@ if ($mode == 'searchkey') //} print ''; // Action column - print ''; + print ''; $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); print $searchpicto; print ''; @@ -455,9 +519,36 @@ if ($mode == 'searchkey') { if ($val != $newlangfileonly->tab_translate[$key]) { + // retrieve rowid + $sql = "SELECT rowid"; + $sql.= " FROM " . MAIN_DB_PREFIX . "overwrite_trans"; + $sql.= " WHERE transkey = '".$key."'"; + $sql.= " AND entity IN (" . getEntity('overwrite_trans') . ")"; + dol_syslog("translation::select from table", LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + } + print '' . img_edit() . ''; + print '  '; + print '' . img_delete() . ''; + print '  '; $htmltext = $langs->trans("OriginalValueWas", $newlangfileonly->tab_translate[$key]); print $form->textwithpicto('', $htmltext, 1, 'info'); } + else if (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) + { + //print $key.'-'.$val; + print '' . img_edit_add($langs->trans("Overwrite")) . ''; + } + + if (! empty($conf->global->MAIN_FEATURES_LEVEL)) + { + $transifexlangfile='$'; // $ means 'All' + $transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key; + print '   '.img_picto('FixOnTransifex', 'object_globe').''; + } } else { @@ -479,6 +570,10 @@ dol_fiche_end(); print "\n"; +if (! empty($langcode)) +{ + dol_set_focus('#transvalue'); +} llxFooter(); diff --git a/htdocs/admin/websites.php b/htdocs/admin/website.php similarity index 84% rename from htdocs/admin/websites.php rename to htdocs/admin/website.php index 61fa7bc17f3..2dc8a9f1423 100644 --- a/htdocs/admin/websites.php +++ b/htdocs/admin/website.php @@ -16,7 +16,7 @@ */ /** - * \file htdocs/admin/websites.php + * \file htdocs/admin/website.php * \ingroup setup * \brief Page to administer web sites */ @@ -28,7 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; -require_once DOL_DOCUMENT_ROOT.'/websites/class/website.class.php'; +require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; $langs->load("errors"); $langs->load("admin"); @@ -73,7 +73,7 @@ $tablib[1] = "Websites"; // Requests to extract data $tabsql=array(); -$tabsql[1] = "SELECT f.rowid as rowid, f.entity, f.ref, f.description, f.status FROM ".MAIN_DB_PREFIX."website as f"; +$tabsql[1] = "SELECT f.rowid as rowid, f.entity, f.ref, f.description, f.virtualhost, f.status FROM ".MAIN_DB_PREFIX."website as f"; // Criteria to sort dictionaries $tabsqlsort=array(); @@ -81,15 +81,15 @@ $tabsqlsort[1] ="ref ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire $tabfield=array(); -$tabfield[1] = "ref,description"; +$tabfield[1] = "ref,description,virtualhost"; // Nom des champs d'edition pour modification d'un enregistrement $tabfieldvalue=array(); -$tabfieldvalue[1] = "ref,description"; +$tabfieldvalue[1] = "ref,description,virtualhost"; // Nom des champs dans la table pour insertion d'un enregistrement $tabfieldinsert=array(); -$tabfieldinsert[1] = "ref,description,entity"; +$tabfieldinsert[1] = "ref,description,virtualhost,entity"; // Nom du rowid si le champ n'est pas de type autoincrement // Example: "" if id field is "rowid" and has autoincrement on @@ -99,11 +99,11 @@ $tabrowid[1] = ""; // Condition to show dictionary in setup page $tabcond=array(); -$tabcond[1] = (! empty($conf->websites->enabled)); +$tabcond[1] = (! empty($conf->website->enabled)); // List of help for fields $tabhelp=array(); -$tabhelp[1] = array(); +$tabhelp[1] = array('ref'=>$langs->trans("EnterAnyCode"), 'virtualhost'=>$langs->trans("SetHereVirtualHost", DOL_DATA_ROOT.'/website/websiteref')); // List of check for fields (NOT USED YET) $tabfieldcheck=array(); @@ -114,7 +114,7 @@ $tabfieldcheck[1] = array(); $elementList = array(); $sourceList=array(); -// Actions add or modify an entry into a dictionary +// Actions add or modify a website if (GETPOST('actionadd','alpha') || GETPOST('actionmodify','alpha')) { $listfield=explode(',',$tabfield[$id]); @@ -126,12 +126,25 @@ if (GETPOST('actionadd','alpha') || GETPOST('actionmodify','alpha')) $ok=1; foreach ($listfield as $f => $value) { - if (! isset($_POST[$value]) || $_POST[$value]=='') // Fields that are not mandatory + if ((! isset($_POST[$value]) || $_POST[$value]=='') + && (! in_array($listfield[$f], array('virtualhost')))) // Fields that are not mandatory { $ok=0; $fieldnamekey=$listfield[$f]; setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); } + if ($value == 'ref' && ! preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value])) + { + $ok=0; + $fieldnamekey=$listfield[$f]; + setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities($fieldnamekey)), null, 'errors'); + } + } + + // Clean parameters + if (! empty($_POST['ref'])) + { + $websitekey=strtolower($_POST['ref']); } // Si verif ok et action add, on ajoute la ligne @@ -153,6 +166,12 @@ if (GETPOST('actionadd','alpha') || GETPOST('actionmodify','alpha')) } } + /* $website=new Website($db); + $website->ref= + $website->description= + $website->virtualhost= + $website->create($user); */ + // Add new entry $sql = "INSERT INTO ".$tabname[$id]." ("; // List of fields @@ -171,6 +190,9 @@ if (GETPOST('actionadd','alpha') || GETPOST('actionmodify','alpha')) if ($value == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } + if ($value == 'ref') { + $_POST[$listfieldvalue[$i]] = strtolower($_POST[$listfieldvalue[$i]]); + } if ($i) $sql.=","; if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; @@ -182,6 +204,29 @@ if (GETPOST('actionadd','alpha') || GETPOST('actionmodify','alpha')) $result = $db->query($sql); if ($result) // Add is ok { + global $dolibarr_main_data_root; + $pathofwebsite=$dolibarr_main_data_root.'/website/'.$websitekey; + $filehtmlheader=$pathofwebsite.'/htmlheader.html'; + $filecss=$pathofwebsite.'/styles.css.php'; + $filetpl=$pathofwebsite.'/page'.$pageid.'.tpl.php'; + $fileindex=$pathofwebsite.'/index.php'; + + // Css file + $csscontent = ''."\n"; + $csscontent.= ''."\n"; + $csscontent.= '"."\n"; + $csscontent.= ''."\n"; + $csscontent.= 'body { margin: 0; }'."\n"; + + dol_syslog("Save file css into ".$filecss); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filecss, $csscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filecss, octdec($conf->global->MAIN_UMASK)); + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); unset($_POST); // Clean $_POST array, we keep only } @@ -202,6 +247,8 @@ if (GETPOST('actionadd','alpha') || GETPOST('actionmodify','alpha')) if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } else { $rowidcol="rowid"; } + $db->begin(); + $website=new Website($db); $rowid=GETPOST('rowid','int'); $website->fetch($rowid); @@ -236,14 +283,41 @@ if (GETPOST('actionadd','alpha') || GETPOST('actionmodify','alpha')) $newname = dol_sanitizeFileName(GETPOST('ref','aZ09')); if ($newname != $website->ref) { - $srcfile=DOL_DATA_ROOT.'/websites/'.$website->ref; - $destfile=DOL_DATA_ROOT.'/websites/'.$newname; - @rename($srcfile, $destfile); + $srcfile=DOL_DATA_ROOT.'/website/'.$website->ref; + $destfile=DOL_DATA_ROOT.'/website/'.$newname; + + if (dol_is_dir($destfile)) + { + $error++; + setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors'); + } + else + { + @rename($srcfile, $destfile); + + // We must now rename $website->ref into $newname inside files + $arrayreplacement = array($website->ref.'/htmlheader.html' => $newname.'/htmlheader.html'); + $listofilestochange = dol_dir_list($destfile, 'files', 0, '\.php$'); + foreach ($listofilestochange as $key => $value) + { + dolReplaceInFile($value['fullname'], $arrayreplacement); + } + } } } else { - setEventMessages($db->error(), null, 'errors'); + $error++; + setEventMessages($db->lasterror(), null, 'errors'); + } + + if (! $error) + { + $db->commit(); + } + else + { + $db->rollback(); } } //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition @@ -393,7 +467,11 @@ if ($id) { print ''; if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; - else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); + elseif (! empty($tabhelp[$id][$value])) + { + if ($value == 'virtualhost') print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual'); + else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); + } else print $valuetoshow; print ''; } diff --git a/htdocs/api/admin/index.php b/htdocs/api/admin/index.php index f2c5160db38..d912c2e40df 100644 --- a/htdocs/api/admin/index.php +++ b/htdocs/api/admin/index.php @@ -77,6 +77,8 @@ if ($action == 'setproductionmode') } } +dol_mkdir(DOL_DATA_ROOT.'/api/temp'); // May have been deleted by a purge + /* * View diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index f8f8d37ce17..dede8690c06 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -134,8 +134,11 @@ class DolibarrApi unset($object->fk_element); unset($object->table_element); unset($object->table_element_line); + unset($object->class_element_line); unset($object->picto); + unset($object->facturee); // Replace with billed + unset($object->skip_update_total); unset($object->context); diff --git a/htdocs/api/class/api_access.class.php b/htdocs/api/class/api_access.class.php index 41ff488136d..d067d6e2ad6 100644 --- a/htdocs/api/class/api_access.class.php +++ b/htdocs/api/class/api_access.class.php @@ -83,10 +83,10 @@ class DolibarrApiAccess implements iAuthenticate // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx $api_key = ''; - if (isset($_GET['api_key'])) + if (isset($_GET['api_key'])) // For backward compatibility { // TODO Add option to disable use of api key on url. Return errors if used. - $api_key = $_GET['api_key']; // For backward compatibility + $api_key = $_GET['api_key']; } if (isset($_GET['DOLAPIKEY'])) { diff --git a/htdocs/api/class/api_dictionary.class.php b/htdocs/api/class/api_dictionary.class.php new file mode 100644 index 00000000000..d551f3d866f --- /dev/null +++ b/htdocs/api/class/api_dictionary.class.php @@ -0,0 +1,518 @@ + + * Copyright (C) 2016 Laurent Destailleur + * Copyright (C) 2017 Regis Houssin + * Copyright (C) 2017 Neil Orley + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +use Luracast\Restler\RestException; + +require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; + +/** + * API class for dictionaries + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class Dictionary extends DolibarrApi +{ + private $translations = null; + + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of payments types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment type is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')" + * + * @url GET payment/types + * + * @return array [List of payment types] + * + * @throws 400 RestException + * @throws 200 OK + */ + function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; + $sql.= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of countries. + * + * The names of the countries will be translated to the given language if + * the $lang parameter is provided. The value of $lang must be a language + * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. + * The returned list is sorted by country ID. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $filter To filter the countries by name + * @param string $lang Code of the language the label of the countries must be translated to + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return List of countries + * + * @url GET countries + * + * @throws RestException + */ + function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') + { + $list = array(); + + // Note: The filter is not applied in the SQL request because it must + // be applied to the translated names, not to the names in database. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; + $sql.=" WHERE 1 = 1"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $obj = $this->db->fetch_object($result); + $country = new Ccountry($this->db); + if ($country->fetch($obj->rowid) > 0) { + // Translate the name of the country if needed + // and then apply the filter if there is one. + $this->translateLabel($country, $lang); + + if (empty($filter) || stripos($country->label, $filter) !== FALSE) { + $list[] = $this->_cleanObjectDatas($country); + } + } + } + } else { + throw new RestException(503, 'Error when retrieving list of countries : '.$country->error); + } + + return $list; + } + + /** + * Get country by ID. + * + * @param int $id ID of country + * @param string $lang Code of the language the name of the + * country must be translated to + * + * @url GET countries/{id} + * + * @throws RestException + */ + function getCountryByID($id, $lang = '') + { + $country = new Ccountry($this->db); + + if ($country->fetch($id) < 0) { + throw new RestException(503, 'Error when retrieving country : '.$country->error); + } + else if ($country->fetch($id) == 0) { + throw new RestException(404, 'country not found'); + } + + $this->translateLabel($country, $lang); + + return $this->_cleanObjectDatas($country); + } + + /** + * 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->error); + unset($object->errors); + + return $object; + } + + /** + * Translate the name of the country to the given language. + * + * @param Ccountry $country Country + * @param string $lang Code of the language the name of the + * country must be translated to + */ + private function translateLabel($country, $lang) + { + if (!empty($lang)) { + // Load the translations if this is a new language. + if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { + global $conf; + $this->translations = new Translate('', $conf); + $this->translations->setDefaultLang($lang); + $this->translations->load('dict'); + } + if ($country->code) { + $key = 'Country'.$country->code; + $translation = $this->translations->trans($key); + if ($translation != $key) { + $country->label = html_entity_decode($translation); + } + } + } + } + + /** + * Get the list of events types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $type To filter on type of event + * @param string $module To filter on module events + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return List of events types + * + * @url GET events + * + * @throws RestException + */ + function getListOfEvents($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; + $sql.= " WHERE t.active = 1"; + if ($type) $sql.=" AND t.type LIKE '%" . $this->db->escape($type) . "%'"; + if ($module) $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); + } + + return $list; + } + + + /** + * Get the list of extra fields. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" + * @return List of events types + * + * @url GET extrafields + * + * @throws RestException + */ + function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') + { + $list = array(); + + if ($type == 'thirdparty') $type='societe'; + if ($type == 'contact') $type='socpeople'; + + $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed"; + $sql.= " FROM ".MAIN_DB_PREFIX."extrafields as t"; + $sql.= " WHERE t.entity IN (".getEntity('extrafields').")"; + if (! empty($type)) $sql.= " AND t.elementtype = '".$this->db->escape($type)."'"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $this->db->order($sortfield, $sortorder); + + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + while ($tab = $this->db->fetch_object($resql)) + { + // New usage + $list[$tab->elementtype][$tab->name]['type']=$tab->type; + $list[$tab->elementtype][$tab->name]['label']=$tab->label; + $list[$tab->elementtype][$tab->name]['size']=$tab->size; + $list[$tab->elementtype][$tab->name]['elementtype']=$tab->elementtype; + $list[$tab->elementtype][$tab->name]['default']=$tab->fielddefault; + $list[$tab->elementtype][$tab->name]['computed']=$tab->fieldcomputed; + $list[$tab->elementtype][$tab->name]['unique']=$tab->fieldunique; + $list[$tab->elementtype][$tab->name]['required']=$tab->fieldrequired; + $list[$tab->elementtype][$tab->name]['param']=($tab->param ? unserialize($tab->param) : ''); + $list[$tab->elementtype][$tab->name]['pos']=$tab->pos; + $list[$tab->elementtype][$tab->name]['alwayseditable']=$tab->alwayseditable; + $list[$tab->elementtype][$tab->name]['perms']=$tab->perms; + $list[$tab->elementtype][$tab->name]['list']=$tab->list; + } + } + } + else + { + throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); + } + + if (! count($list)) + { + throw new RestException(404, 'No extrafield found'); + } + + return $list; + } + + + /** + * Get the list of towns. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $zipcode To filter on zipcode + * @param string $town To filter on city name + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return List of towns + * + * @url GET towns + * + * @throws RestException + */ + function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; + $sql.= " WHERE t.active = 1"; + if ($zipcode) $sql.=" AND t.zip LIKE '%" . $this->db->escape($zipcode) . "%'"; + if ($town) $sql.=" AND t.town LIKE '%" . $this->db->escape($town) . "%'"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of payments terms. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" + * + * @url GET payment/terms + * + * @return array List of payment terms + * + * @throws 400 RestException + * @throws 200 OK + */ + function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; + $sql.= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + +} diff --git a/htdocs/api/class/api_dictionarycountries.class.php b/htdocs/api/class/api_dictionarycountries.class.php deleted file mode 100644 index 070be509a8a..00000000000 --- a/htdocs/api/class/api_dictionarycountries.class.php +++ /dev/null @@ -1,184 +0,0 @@ - - * Copyright (C) 2016 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -use Luracast\Restler\RestException; - -require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; - -/** - * API class for countries - * - * @access protected - * @class DolibarrApiAccess {@requires user,external} - */ -class DictionaryCountries extends DolibarrApi -{ - private $translations = null; - - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of countries. - * - * The names of the countries will be translated to the given language if - * the $lang parameter is provided. The value of $lang must be a language - * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. - * The returned list is sorted by country ID. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $filter To filter the countries by name - * @param string $lang Code of the language the label of the countries must be translated to - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return List of countries - * - * @throws RestException - */ - function index($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') - { - $list = array(); - - // Note: The filter is not applied in the SQL request because it must - // be applied to the translated names, not to the names in database. - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; - $sql.=" WHERE 1 = 1"; - // Add sql filters - if ($sqlfilters) - { - if (! DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql.= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $obj = $this->db->fetch_object($result); - $country = new Ccountry($this->db); - if ($country->fetch($obj->rowid) > 0) { - // Translate the name of the country if needed - // and then apply the filter if there is one. - $this->translateLabel($country, $lang); - - if (empty($filter) || stripos($country->label, $filter) !== FALSE) { - $list[] = $this->_cleanObjectDatas($country); - } - } - } - } else { - throw new RestException(503, 'Error when retrieving list of countries : '.$country->error); - } - - return $list; - } - - /** - * Get country by ID. - * - * @param int $id ID of country - * @param string $lang Code of the language the name of the - * country must be translated to - * - * @throws RestException - */ - function get($id, $lang = '') - { - $country = new Ccountry($this->db); - - if ($country->fetch($id) < 0) { - throw new RestException(503, 'Error when retrieving country : '.$country->error); - } - else if ($country->fetch($id) == 0) { - throw new RestException(404, 'country not found'); - } - - $this->translateLabel($country, $lang); - - return $this->_cleanObjectDatas($country); - } - - /** - * 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->error); - unset($object->errors); - - return $object; - } - - /** - * Translate the name of the country to the given language. - * - * @param Ccountry $country Country - * @param string $lang Code of the language the name of the - * country must be translated to - */ - private function translateLabel($country, $lang) - { - if (!empty($lang)) { - // Load the translations if this is a new language. - if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { - global $conf; - $this->translations = new Translate('', $conf); - $this->translations->setDefaultLang($lang); - $this->translations->load('dict'); - } - if ($country->code) { - $key = 'Country'.$country->code; - $translation = $this->translations->trans($key); - if ($translation != $key) { - $country->label = html_entity_decode($translation); - } - } - } - } -} diff --git a/htdocs/api/class/api_dictionaryevents.class.php b/htdocs/api/class/api_dictionaryevents.class.php deleted file mode 100644 index 23d7e8e5dba..00000000000 --- a/htdocs/api/class/api_dictionaryevents.class.php +++ /dev/null @@ -1,100 +0,0 @@ - - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -use Luracast\Restler\RestException; - -require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; - -/** - * API class for events type (content of the actioncomm dictionary) - * - * @access protected - * @class DolibarrApiAccess {@requires user,external} - */ -class DictionaryEvents extends DolibarrApi -{ - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of events types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $type To filter on type of event - * @param string $module To filter on module events - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return List of events types - * - * @throws RestException - */ - function index($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT id, code, type, libelle as label, module"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; - $sql.= " WHERE t.active = 1"; - if ($type) $sql.=" AND t.type LIKE '%" . $this->db->escape($type) . "%'"; - if ($module) $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'"; - // Add sql filters - if ($sqlfilters) - { - if (! DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql.= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); - } - - return $list; - } - -} diff --git a/htdocs/api/class/api_dictionaryextrafields.class.php b/htdocs/api/class/api_dictionaryextrafields.class.php deleted file mode 100644 index 69f574797c7..00000000000 --- a/htdocs/api/class/api_dictionaryextrafields.class.php +++ /dev/null @@ -1,112 +0,0 @@ - - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -use Luracast\Restler\RestException; - -//require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; - -/** - * API class for extra fields (content of the extrafields) - * - * @access protected - * @class DolibarrApiAccess {@requires user,external} - */ -class DictionaryExtraFields extends DolibarrApi -{ - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of extra fields. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" - * @return List of events types - * - * @throws RestException - */ - function index($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') - { - $list = array(); - - if ($type == 'thirdparty') $type='societe'; - if ($type == 'contact') $type='socpeople'; - - $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.ishidden, t.fielddefault, t.fieldcomputed"; - $sql.= " FROM ".MAIN_DB_PREFIX."extrafields as t"; - $sql.= " WHERE t.entity IN (".getEntity('extrafields').")"; - if (! empty($type)) $sql.= " AND t.elementtype = '".$this->db->escape($type)."'"; - // Add sql filters - if ($sqlfilters) - { - if (! DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql.= $this->db->order($sortfield, $sortorder); - - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - while ($tab = $this->db->fetch_object($resql)) - { - // New usage - $list[$tab->elementtype][$tab->name]['type']=$tab->type; - $list[$tab->elementtype][$tab->name]['label']=$tab->label; - $list[$tab->elementtype][$tab->name]['size']=$tab->size; - $list[$tab->elementtype][$tab->name]['elementtype']=$tab->elementtype; - $list[$tab->elementtype][$tab->name]['default']=$tab->fielddefault; - $list[$tab->elementtype][$tab->name]['computed']=$tab->fieldcomputed; - $list[$tab->elementtype][$tab->name]['unique']=$tab->fieldunique; - $list[$tab->elementtype][$tab->name]['required']=$tab->fieldrequired; - $list[$tab->elementtype][$tab->name]['param']=($tab->param ? unserialize($tab->param) : ''); - $list[$tab->elementtype][$tab->name]['pos']=$tab->pos; - $list[$tab->elementtype][$tab->name]['alwayseditable']=$tab->alwayseditable; - $list[$tab->elementtype][$tab->name]['perms']=$tab->perms; - $list[$tab->elementtype][$tab->name]['list']=$tab->list; - $list[$tab->elementtype][$tab->name]['ishidden']=$tab->ishidden; - } - } - } - else - { - throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); - } - - if (! count($list)) - { - throw new RestException(404, 'No extrafield found'); - } - - return $list; - } - -} diff --git a/htdocs/api/class/api_dictionarytowns.class.php b/htdocs/api/class/api_dictionarytowns.class.php deleted file mode 100644 index 0ebcfbe0b17..00000000000 --- a/htdocs/api/class/api_dictionarytowns.class.php +++ /dev/null @@ -1,102 +0,0 @@ - - * Copyright (C) 2016 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -use Luracast\Restler\RestException; - -require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; - -/** - * API class for towns (content of the ziptown dictionary) - * - * @access protected - * @class DolibarrApiAccess {@requires user,external} - */ -class DictionaryTowns extends DolibarrApi -{ - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of towns. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $zipcode To filter on zipcode - * @param string $town To filter on city name - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return List of towns - * - * @throws RestException - */ - function index($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; - $sql.= " WHERE t.active = 1"; - if ($zipcode) $sql.=" AND t.zip LIKE '%" . $this->db->escape($zipcode) . "%'"; - if ($town) $sql.=" AND t.town LIKE '%" . $this->db->escape($town) . "%'"; - // Add sql filters - if ($sqlfilters) - { - if (! DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql.= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); - } - - return $list; - } - -} diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index e26486981fa..92b48dfd0c6 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -22,6 +22,9 @@ use Luracast\Restler\Format\UploadFormat; require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; /** * API class for receive files @@ -32,173 +35,356 @@ require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; class Documents extends DolibarrApi { - /** - * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object - */ - static $DOCUMENT_FIELDS = array( - 'modulepart' - ); + /** + * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object + */ + static $DOCUMENT_FIELDS = array( + 'modulepart' + ); - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } - - /** - * 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 - * - * @throws RestException - */ - 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 - */ - /* + + /** + * Returns a document. Note that, this API is similar to using the wrapper link "documents.php" to download + * a file (used for internal HTML links of documents into application), but with no need to be into a logged session (no need to post the session cookie). + * + * @param string $module_part Name of module or area concerned by file download ('facture', ...) + * @param string $original_file Relative path with filename, relative to modulepart (for example: IN201701-999/IN201701-999.pdf) + * @param int $regeneratedoc If requested document is the main document of an object, setting this to 1 ask API to regenerate document before returning it (supported for some module_part only). It is no effect in other cases. + * Also, note that setting this to 1 nead write access on object. + * @return array List of documents + * + * @throws 500 + * @throws 501 + * @throws 400 + * @throws 401 + * @throws 200 + */ + public function index($module_part, $original_file='', $regeneratedoc=0) + { + global $conf, $langs; + + if (empty($module_part)) { + throw new RestException(400, 'bad value for parameter modulepart'); + } + if (empty($original_file)) { + throw new RestException(400, 'bad value for parameter ref or subdir'); + } + + //--- Finds and returns the document + $entity=$conf->entity; + + $check_access = dol_check_secure_access_document($module_part, $original_file, $entity, DolibarrApiAccess::$user, '', ($regeneratedoc ? 'write' : 'read')); + $accessallowed = $check_access['accessallowed']; + $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; + $original_file = $check_access['original_file']; + + if (preg_match('/\.\./',$original_file) || preg_match('/[<>|]/',$original_file)) + { + throw new RestException(401); + } + if (!$accessallowed) { + throw new RestException(401); + } + + // --- Generates the document + if ($regeneratedoc) + { + $hidedetails = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 0 : 1; + $hidedesc = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 0 : 1; + $hideref = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 0 : 1; + + if ($module_part == 'facture' || $module_part == 'invoice') + { + require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $this->invoice = new Facture($this->db); + $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + $result = $this->invoice->generateDocument($this->invoice->modelpdf, $langs, $hidedetails, $hidedesc, $hideref); + if( $result <= 0 ) { + throw new RestException(500, 'Error generating document'); + } + } + } + + $filename = basename($original_file); + $original_file_osencoded=dol_osencode($original_file); // New file name encoded in OS encoding charset + + if (! file_exists($original_file_osencoded)) + { + throw new RestException(404, 'File not found'); + } + + $file_content=file_get_contents($original_file_osencoded); + return array('filename'=>$filename, 'content'=>base64_encode($file_content), 'encoding'=>'MIME base64 (base64_encode php function, http://php.net/manual/en/function.base64-encode.php)' ); + } + + /** + * Return the list of documents of a dedicated element (from its ID or Ref) + * + * @param string $modulepart Name of module or area concerned ('facture', 'project', 'member', ...) + * @param int $id ID of element + * @param string $ref Ref of element + * @param string $sortfield Sort criteria ('','fullname','relativename','name','date','size') + * @param string $sortorder Sort order ('asc' or 'desc') + * @return array Array of documents with path + * + * @throws RestException + * + * @url GET list + */ + function getDocumentsListByElement($modulepart, $id=0, $ref='', $sortfield='', $sortorder='') + { + global $conf; + + if (empty($modulepart)) { + throw new RestException(400, 'bad value for parameter modulepart'); + } + + if (empty($id) && empty($ref)) { + throw new RestException(400, 'bad value for parameter id or ref'); + } + + $id = (empty($id)?0:$id); + + if ($modulepart == 'societe' || $modulepart == 'thirdparty') + { + if (!DolibarrApiAccess::$user->rights->societe->lire) { + throw new RestException(401); + } + + $object = new Societe($this->db); + $result=$object->fetch($id, $ref); + if ( ! $result ) { + throw new RestException(404, 'Thirdparty not found'); + } + + $upload_dir = $conf->societe->multidir_output[$object->entity] . "/" . $object->id; + } + else if ($modulepart == 'adherent' || $modulepart == 'member') + { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + + if (!DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } + + $object = new Adherent($this->db); + $result=$object->fetch($id, $ref); + if ( ! $result ) { + throw new RestException(404, 'Member not found'); + } + + $upload_dir = $conf->adherent->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'member'); + } + else + { + throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); + } + + $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); + if (empty($filearray)) { + throw new RestException(404, 'Modulepart '.$modulepart.' with Id '.$object->id.(! empty($object->Ref)?' and Ref '.$object->ref:'').' does not have any documents.'); + } + + return $filearray; + } + + + /** + * 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" }. - * Test sample 2: { "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "mysubdir1/mysubdir2", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. - * - * @param string $filename Name of file to create ('FA1705-0123') - * @param string $modulepart Name of module or area concerned by file upload ('facture', ...) - * @param string $ref Reference of object (This will define subdir automatically and store submited file into it) - * @param string $subdir Subdirectory (Only if ref not provided) - * @param string $filecontent File content (string with file content. An empty file will be created if this parameter is not provided) - * @param string $fileencoding File encoding (''=no encoding, 'base64'=Base 64) - * @param int $overwriteifexists Overwrite file if exists (1 by default) - * @return bool State of copy - * @throws RestException - */ - public function post($filename, $modulepart, $ref='', $subdir='', $filecontent='', $fileencoding='', $overwriteifexists=0) - { - global $db, $conf; - - /*var_dump($modulepart); + + + /** + * Push a file. + * Test sample 1: { "filename": "mynewfile.txt", "modulepart": "facture", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. + * Test sample 2: { "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "mysubdir1/mysubdir2", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. + * + * @param string $filename Name of file to create ('FA1705-0123') + * @param string $modulepart Name of module or area concerned by file upload ('facture', 'project', 'project_task', ...) + * @param string $ref Reference of object (This will define subdir automatically and store submited file into it) + * @param string $subdir Subdirectory (Only if ref not provided) + * @param string $filecontent File content (string with file content. An empty file will be created if this parameter is not provided) + * @param string $fileencoding File encoding (''=no encoding, 'base64'=Base 64) + * @param int $overwriteifexists Overwrite file if exists (1 by default) + * @return bool State of copy + * @throws RestException + */ + public function post($filename, $modulepart, $ref='', $subdir='', $filecontent='', $fileencoding='', $overwriteifexists=0) + { + global $db, $conf; + + /*var_dump($modulepart); var_dump($filename); var_dump($filecontent); exit;*/ - - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - if (!DolibarrApiAccess::$user->rights->ecm->upload) { - throw new RestException(401); - } + if(empty($modulepart)) + { + throw new RestException(400, 'Modulepart not provided.'); + } - $newfilecontent = ''; - if (empty($fileencoding)) $newfilecontent = $filecontent; - if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); + if (!DolibarrApiAccess::$user->rights->ecm->upload) { + throw new RestException(401); + } + + $newfilecontent = ''; + if (empty($fileencoding)) $newfilecontent = $filecontent; + if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); $original_file = dol_sanitizeFileName($filename); // Define $uploadir $object = null; - $entity = $user->entity; + $entity = DolibarrApiAccess::$user->entity; if ($ref) { - if ($modulepart == 'facture' || $modulepart == 'invoice') - { - $modulepart='facture'; - $object=new Facture($db); - $result = $object->fetch('', $ref); - } - - if (! ($object->id > 0)) - { - throw new RestException(500, 'The object '.$modulepart." with ref '".$ref."' was not found."); - } + $tmpreldir=''; - $tmp = dol_check_secure_access_document($modulepart, $tmpreldir.$object->ref, $entity, DolibarrApiAccess::$user, $ref, 'write'); - $upload_dir = $tmp['original_file']; - - if (empty($upload_dir) || $upload_dir == '/') - { - throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); - } + if ($modulepart == 'facture' || $modulepart == 'invoice') + { + $modulepart='facture'; + $object = new Facture($this->db); + } + elseif ($modulepart == 'project') + { + $object = new Project($this->db); + } + elseif ($modulepart == 'task' || $modulepart == 'project_task') + { + $modulepart = 'project_task'; + $object = new Task($this->db); + + $task_result = $object->fetch('', $ref); + + // Fetching the tasks project is required because its out_dir might be a subdirectory of the project + if($task_result > 0) + { + $project_result = $object->fetch_projet(); + + if($project_result >= 0) + { + $tmpreldir = dol_sanitizeFileName($object->project->ref).'/'; + } + } + else + { + throw new RestException(500, 'Error while fetching Task '.$ref); + } + } + // TODO Implement additional moduleparts + else + { + throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); + } + + if(is_object($object)) + { + $result = $object->fetch('', $ref); + + if($result == 0) + { + throw new RestException(500, "Object with ref '".$ref.'" was not found.'); + } + elseif ($result < 0) + { + throw new RestException(500, 'Error while fetching object.'); + } + } + + if (! ($object->id > 0)) + { + throw new RestException(500, 'The object '.$modulepart." with ref '".$ref."' was not found."); + } + + $tmp = dol_check_secure_access_document($modulepart, $tmpreldir.dol_sanitizeFileName($object->ref), $entity, DolibarrApiAccess::$user, $ref, 'write'); + $upload_dir = $tmp['original_file']; + + if (empty($upload_dir) || $upload_dir == '/') + { + throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); + } } else { - if ($modulepart == 'invoice') $modulepart ='facture'; - - $tmp = dol_check_secure_access_document($modulepart, $subdir, $entity, DolibarrApiAccess::$user, '', 'write'); - $upload_dir = $tmp['original_file']; + if ($modulepart == 'invoice') $modulepart ='facture'; - if (empty($upload_dir) || $upload_dir == '/') - { - throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); - } + $tmp = dol_check_secure_access_document($modulepart, $subdir, $entity, DolibarrApiAccess::$user, '', 'write'); + $upload_dir = $tmp['original_file']; + + if (empty($upload_dir) || $upload_dir == '/') + { + throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); + } } - - + + $upload_dir = dol_sanitizePathName($upload_dir); - + $destfile = $upload_dir . '/' . $original_file; $destfiletmp = DOL_DATA_ROOT.'/admin/temp/' . $original_file; dol_delete_file($destfiletmp); - - if (!dol_is_dir($upload_dir)) { - throw new RestException(401,'Directory not exists : '.$upload_dir); - } - if (! $overwriteifexists && dol_is_file($destfile)) - { - throw new RestException(500, "File with name '".$original_file."' already exists."); - } - - $fhandle = @fopen($destfiletmp, 'w'); - if ($fhandle) - { - $nbofbyteswrote = fwrite($fhandle, $newfilecontent); - fclose($fhandle); - @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK)); - } - else - { - throw new RestException(500, "Failed to open file '".$destfiletmp."' for write"); - } - - $result = dol_move($destfiletmp, $destfile, 0, $overwriteifexists, 1); - - return $result; - } + if (!dol_is_dir($upload_dir)) { + throw new RestException(401,'Directory not exists : '.$upload_dir); + } - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - function _validate_file($data) { - $result = array(); - foreach (Documents::$DOCUMENT_FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $result[$field] = $data[$field]; - } - return $result; - } + if (! $overwriteifexists && dol_is_file($destfile)) + { + throw new RestException(500, "File with name '".$original_file."' already exists."); + } + + $fhandle = @fopen($destfiletmp, 'w'); + if ($fhandle) + { + $nbofbyteswrote = fwrite($fhandle, $newfilecontent); + fclose($fhandle); + @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK)); + } + else + { + throw new RestException(500, "Failed to open file '".$destfiletmp."' for write"); + } + + $result = dol_move($destfiletmp, $destfile, 0, $overwriteifexists, 1); + + return $result; + } + + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + function _validate_file($data) { + $result = array(); + foreach (Documents::$DOCUMENT_FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $result[$field] = $data[$field]; + } + return $result; + } } diff --git a/htdocs/api/index.php b/htdocs/api/index.php index 7bb062c03df..09f5cdb7cfe 100644 --- a/htdocs/api/index.php +++ b/htdocs/api/index.php @@ -182,10 +182,15 @@ if (! empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/resources.json' | $classname = ucwords($regapi[1]); $classname = str_replace('_', '', $classname); require_once $dir_part.$file_searched; - if (class_exists($classname)) + if (class_exists($classname.'Api')) { - //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched); - $listofapis[] = $classname; + dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched); + $listofapis[strtolower($classname.'Api')] = $classname.'Api'; + } + elseif (class_exists($classname)) + { + dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched); + $listofapis[strtolower($classname)] = $classname; } else { @@ -202,10 +207,10 @@ if (! empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/resources.json' | // Sort the classes before adding them to Restler. // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted. - sort($listofapis); - foreach ($listofapis as $classname) + asort($listofapis); + foreach ($listofapis as $apiname => $classname) { - $api->r->addAPIClass($classname); + $api->r->addAPIClass($classname, $apiname); } } @@ -218,25 +223,26 @@ if (! empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/resources.json' $module = $regbis[1]; } - // Load a dedicated API file - dol_syslog("Load a dedicated API file"); - $module=strtolower($module); $moduledirforclass = getModuleDirForApiClass($module); + // Load a dedicated API file + dol_syslog("Load a dedicated API file moduledirforclass=".$moduledirforclass); + if (in_array($module, array('category','contact','customer','invoice','order','product','thirdparty','user'))) // Old Apis { $classfile = $module; if ($module == 'customer') { $classfile = 'thirdparty'; } if ($module == 'order') { $classfile = 'commande'; } - $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_deprecated_'.$classfile.'.class.php'); + $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_deprecated_'.$classfile.'.class.php', 0, 2); $classname=ucwords($module); if ($module == 'customer') { $classname='Thirdparty'; } if ($module == 'order') { $classname='Commande'; } //var_dump($classfile);var_dump($classname);exit; - $res = include_once $dir_part_file; - if (! $res) + $res = false; + if ($dir_part_file) $res = include_once $dir_part_file; + if (! $res) { print 'API not found (failed to include API file)'; header('HTTP/1.1 501 API not found (failed to include API file)'); @@ -246,20 +252,26 @@ if (! empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/resources.json' } else { - $classfile = str_replace('_', '', $module); + $tmpmodule = $module; + if ($tmpmodule != 'api') $tmpmodule = preg_replace('/api$/i','', $tmpmodule); + $classfile = str_replace('_', '', $tmpmodule); if ($module == 'supplierinvoices') $classfile = 'supplier_invoices'; if ($module == 'supplierorders') $classfile = 'supplier_orders'; - $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php'); + $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2); + $classname=ucwords($module); - $res = include_once $dir_part_file; - if (! $res) + dol_syslog('Search /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname); + + $res = false; + if ($dir_part_file) $res = include_once $dir_part_file; + if (! $res) { print 'API not found (failed to include API file)'; header('HTTP/1.1 501 API not found (failed to include API file)'); exit(0); } - + if (class_exists($classname)) $api->r->addAPIClass($classname); } } diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 2ad4582634f..fffd5cc9d80 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -21,13 +21,15 @@ class BlockedLog { - /** * Id of the log * @var int */ public $id; + public $error = ''; + public $errors = array(); + /** * Unique fingerprint of the log * @var string @@ -78,7 +80,7 @@ class BlockedLog public $object_data = null; - public $error = 0; + /** * Constructor @@ -94,7 +96,8 @@ class BlockedLog /** * try to retrieve logged object link */ - public function getObjectLink() { + public function getObjectLink() + { global $langs; if($this->element === 'facture') { @@ -148,8 +151,9 @@ class BlockedLog /** * try to retrieve user author - */ - public function getUser() { + */ + public function getUser() + { global $langs, $cachedUser; if(empty($cachedUser))$cachedUser=array(); @@ -169,16 +173,22 @@ class BlockedLog } /** - * populate log by object + * Populate properties of log from object data * - * @param payment|facture $object object to store + * @param Object $object object to store */ - public function setObjectData(&$object) { - - if($object->element=='payment' || $object->element=='payment_supplier') { + public function setObjectData(&$object) + { + // Set date + if ($object->element == 'payment' || $object->element == 'payment_supplier') + { $this->date_object = $object->datepaye; } - else{ + elseif ($object->element=='payment_salary') + { + $this->date_object = $object->datev; + } + else { $this->date_object = $object->date; } @@ -188,7 +198,23 @@ class BlockedLog $this->object_data=new stdClass(); - if($this->element === 'facture') { + if ($this->element == 'facture') + { + if(empty($object->thirdparty))$object->fetch_thirdparty(); + $this->object_data->thirdparty = new stdClass(); + + foreach($object->thirdparty as $key=>$value) { + if(!is_object($value)) $this->object_data->thirdparty->{$key} = $value; + } + + $this->object_data->total_ht = (double) $object->total_ht; + $this->object_data->total_tva = (double) $object->total_tva; + $this->object_data->total_ttc = (double) $object->total_ttc; + $this->object_data->total_localtax1= (double) $object->total_localtax1; + $this->object_data->total_localtax2= (double) $object->total_localtax2; + $this->object_data->note_public = (double) $object->note_public; + } + if($this->element == 'invoice_supplier') { if(empty($object->thirdparty))$object->fetch_thirdparty(); $this->object_data->thirdparty = new stdClass(); @@ -205,27 +231,13 @@ class BlockedLog $this->object_data->note_private= (double) $object->note_private; } - if($this->element === 'invoice_supplier') { - if(empty($object->thirdparty))$object->fetch_thirdparty(); - $this->object_data->thirdparty = new stdClass(); - - foreach($object->thirdparty as $key=>$value) { - if(!is_object($value)) $this->object_data->thirdparty->{$key} = $value; - } - - $this->object_data->total_ht = (double) $object->total_ht; - $this->object_data->total_tva = (double) $object->total_tva; - $this->object_data->total_ttc = (double) $object->total_ttc; - $this->object_data->total_localtax1= (double) $object->total_localtax1; - $this->object_data->total_localtax2= (double) $object->total_localtax2; - $this->object_data->note_public = (double) $object->note_public; - $this->object_data->note_private= (double) $object->note_private; - - } - elseif($this->element==='payment'|| $object->element=='payment_supplier'){ - + elseif ($this->element == 'payment'|| $object->element == 'payment_supplier') + { $this->object_data->amounts = $object->amounts; - + } + elseif($this->element == 'payment_salary') + { + $this->object_data->amounts = array($object->amount); } } @@ -268,7 +280,7 @@ class BlockedLog $this->action = $obj->action; $this->element = $obj->element; - $this->fk_object = trim($obj->fk_object); + $this->fk_object = $obj->fk_object; $this->date_object = $this->db->jdate($obj->date_object); $this->ref_object = $obj->ref_object; @@ -469,10 +481,10 @@ class BlockedLog /** * return log object for a element. * - * @param string $element element to search - * @param int $fk_object id of object to search - * @param int $limit max number of element, 0 for all - * @param string $order sort of query + * @param string $element element to search + * @param int $fk_object id of object to search + * @param int $limit max number of element, 0 for all + * @param string $order sort of query * @return array array of object log */ public function getLog($element, $fk_object, $limit = 0, $order = -1) { diff --git a/htdocs/bookmarks/bookmarks.lib.php b/htdocs/bookmarks/bookmarks.lib.php index eca126697cc..cb234de583f 100644 --- a/htdocs/bookmarks/bookmarks.lib.php +++ b/htdocs/bookmarks/bookmarks.lib.php @@ -35,105 +35,117 @@ function printBookmarksList($aDb, $aLangs) $db = $aDb; $langs = $aLangs; - require_once DOL_DOCUMENT_ROOT.'/bookmarks/class/bookmark.class.php'; - if (! isset($conf->global->BOOKMARKS_SHOW_IN_MENU)) $conf->global->BOOKMARKS_SHOW_IN_MENU=5; - - $langs->load("bookmarks"); - - $url= $_SERVER["PHP_SELF"]; - - if (! empty($_SERVER["QUERY_STRING"])) - { - $url.=(dol_escape_htmltag($_SERVER["QUERY_STRING"])?'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]):''); - } - else - { - global $sortfield,$sortorder; - $tmpurl=''; - // No urlencode, all param $url will be urlencoded later - if ($sortfield) $tmpurl.=($tmpurl?'&':'').'sortfield='.$sortfield; - if ($sortorder) $tmpurl.=($tmpurl?'&':'').'sortorder='.$sortorder; - if (is_array($_POST)) - { - foreach($_POST as $key => $val) - { - if (preg_match('/^search_/', $key) && $val != '') $tmpurl.=($tmpurl?'&':'').$key.'='.$val; - } - } - $url.=($tmpurl?'?'.$tmpurl:''); - } - - $ret = ''; - - // Menu bookmark $ret.= ''."\n"; - $ret.= ''."\n"; - $ret.= '
'; - $ret.= ''; + $ret.= ''; + $ret.= ''; + // Url to go on create new bookmark page + if (! empty($user->rights->bookmark->creer)) + { + //$urltoadd=DOL_URL_ROOT.'/bookmarks/card.php?action=create&urlsource='.urlencode($url).'&url='.urlencode($url); + $urltoadd=DOL_URL_ROOT.'/bookmarks/card.php?action=create&url='.urlencode($url); + $ret.= ''; + } + // Menu with all bookmarks + if (! empty($conf->global->BOOKMARKS_SHOW_IN_MENU)) + { + $sql = "SELECT rowid, title, url, target FROM ".MAIN_DB_PREFIX."bookmark"; + $sql.= " WHERE (fk_user = ".$user->id." OR fk_user is NULL OR fk_user = 0)"; + $sql.= " AND entity IN (".getEntity('bookmarks').")"; + $sql.= " ORDER BY position"; + if ($resql = $db->query($sql) ) + { + $i=0; + while ($i < $conf->global->BOOKMARKS_SHOW_IN_MENU && $obj = $db->fetch_object($resql)) + { + $ret.=''; + $i++; + } + } + else + { + dol_print_error($db); + } + } + + $ret.= ''; + $ret.= '
'; + + $ret.=ajax_combobox('boxbookmark'); + + $ret.=''; } - $ret.= ''; - $ret.= ''; - - $ret.=ajax_combobox('boxbookmark'); - - $ret.=''; - $ret .= ''; + $ret.= ''."\n"; return $ret; } diff --git a/htdocs/bookmarks/card.php b/htdocs/bookmarks/card.php index e9722669e7d..dcc6d8cdeab 100644 --- a/htdocs/bookmarks/card.php +++ b/htdocs/bookmarks/card.php @@ -63,9 +63,9 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update') $error = 0; - if (GETPOST("cancel")) + if (GETPOST('cancel','alpha')) { - if (empty($backtopage)) $backtopage=($urlsource?$urlsource:((! empty($url))?$url:DOL_URL_ROOT.'/bookmarks/list.php')); + if (empty($backtopage)) $backtopage=($urlsource?$urlsource:((! empty($url) && ! preg_match('/^http/i', $url))?$url:DOL_URL_ROOT.'/bookmarks/list.php')); header("Location: ".$backtopage); exit; } @@ -98,7 +98,7 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update') if ($res > 0) { - if (empty($backtopage)) $backtopage=($urlsource?$urlsource:((! empty($url))?$url:DOL_URL_ROOT.'/bookmarks/list.php')); + if (empty($backtopage)) $backtopage=($urlsource?$urlsource:((! empty($url) && ! preg_match('/^http/i', $url))?$url:DOL_URL_ROOT.'/bookmarks/list.php')); header("Location: ".$backtopage); exit; } diff --git a/htdocs/bookmarks/class/bookmark.class.php b/htdocs/bookmarks/class/bookmark.class.php index 26eabc5a5ed..1beb4b36871 100644 --- a/htdocs/bookmarks/class/bookmark.class.php +++ b/htdocs/bookmarks/class/bookmark.class.php @@ -30,9 +30,9 @@ class Bookmark extends CommonObject { public $element='bookmark'; public $table_element='bookmark'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto = 'bookmark'; - + var $db; var $id; @@ -111,7 +111,7 @@ class Bookmark extends CommonObject $this->url=trim($this->url); $this->title=trim($this->title); if (empty($this->position)) $this->position=0; - + $now=dol_now(); $this->db->begin(); @@ -119,14 +119,12 @@ class Bookmark extends CommonObject $sql = "INSERT INTO ".MAIN_DB_PREFIX."bookmark (fk_user,dateb,url,target"; $sql.= ",title,favicon,position"; $sql.= ",entity"; - if ($this->fk_soc) $sql.=",fk_soc"; $sql.= ") VALUES ("; - $sql.= ($this->fk_user > 0?"'".$this->fk_user."'":"0").","; + $sql.= ($this->fk_user > 0 ? $this->fk_user:"0").","; $sql.= " '".$this->db->idate($now)."',"; - $sql.= " '".$this->url."', '".$this->target."',"; - $sql.= " '".$this->db->escape($this->title)."', '".$this->favicon."', '".$this->position."'"; - $sql.= ", '".$conf->entity."'"; - if ($this->fk_soc) $sql.=",".$this->fk_soc; + $sql.= " '".$this->db->escape($this->url)."', '".$this->db->escape($this->target)."',"; + $sql.= " '".$this->db->escape($this->title)."', '".$this->db->escape($this->favicon)."', '".$this->db->escape($this->position)."'"; + $sql.= ", ".$this->db->escape($conf->entity); $sql.= ")"; dol_syslog("Bookmark::update", LOG_DEBUG); @@ -170,7 +168,7 @@ class Bookmark extends CommonObject if (empty($this->position)) $this->position=0; $sql = "UPDATE ".MAIN_DB_PREFIX."bookmark"; - $sql.= " SET fk_user = ".($this->fk_user > 0?"'".$this->fk_user."'":"0"); + $sql.= " SET fk_user = ".($this->fk_user > 0 ? $this->fk_user :"0"); $sql.= " ,dateb = '".$this->db->idate($this->datec)."'"; $sql.= " ,url = '".$this->db->escape($this->url)."'"; $sql.= " ,target = '".$this->db->escape($this->target)."'"; @@ -243,5 +241,5 @@ class Bookmark extends CommonObject { return ''; } - + } diff --git a/htdocs/bookmarks/list.php b/htdocs/bookmarks/list.php index c9387561837..0e642bdcc14 100644 --- a/htdocs/bookmarks/list.php +++ b/htdocs/bookmarks/list.php @@ -35,7 +35,7 @@ $toselect = GETPOST('toselect', 'array'); // Security check if (! $user->rights->bookmark->lire) { - restrictedArea($user, 'bookmarks'); + restrictedArea($user, 'bookmarks'); } $optioncss = GETPOST('optioncss','alpha'); @@ -50,7 +50,7 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield='position'; if (! $sortorder) $sortorder='ASC'; -$id = GETPOST("bid",'int'); +$id = GETPOST("id",'int'); /* @@ -59,17 +59,17 @@ $id = GETPOST("bid",'int'); if ($action == 'delete') { - $bookmark=new Bookmark($db); - $res=$bookmark->remove($id); - if ($res > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } - else - { - setEventMessages($bookmark->error, $bookmark->errors, 'errors'); - } + $bookmark=new Bookmark($db); + $res=$bookmark->remove($id); + if ($res > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } + else + { + setEventMessages($bookmark->error, $bookmark->errors, 'errors'); + } } @@ -83,7 +83,7 @@ llxHeader('', $langs->trans("ListOfBookmarks")); print load_fiche_titre($langs->trans("ListOfBookmarks")); -$sql = "SELECT b.fk_soc as rowid, b.dateb, b.rowid as bid, b.fk_user, b.url, b.target, b.title, b.favicon, b.position,"; +$sql = "SELECT b.rowid, b.dateb, b.fk_user, b.url, b.target, b.title, b.favicon, b.position,"; $sql.= " u.login, u.lastname, u.firstname"; $sql.= " FROM ".MAIN_DB_PREFIX."bookmark as b LEFT JOIN ".MAIN_DB_PREFIX."user as u ON b.fk_user=u.rowid"; $sql.= " WHERE 1=1"; @@ -95,126 +95,112 @@ $sql.= $db->plimit($limit, $offset); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $param = ""; - if ($optioncss != '') $param ='&optioncss='.$optioncss; + $num = $db->num_rows($resql); + $i = 0; + $param = ""; + if ($optioncss != '') $param ='&optioncss='.$optioncss; - $moreforfilter=''; + $moreforfilter=''; - print '
'; - print ''."\n"; + print '
'; + print '
'."\n"; - print ""; - //print ""; - print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"bid","", $param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Title",$_SERVER["PHP_SELF"],"title","", $param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Link",'',''); - print_liste_field_titre("Target",'','','','','align="center"'); - print_liste_field_titre("Owner",$_SERVER["PHP_SELF"],"u.lastname","", $param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"b.dateb","", $param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Position",$_SERVER["PHP_SELF"],"b.position","", $param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre(''); - print "\n"; + print ""; + //print ""; + print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"rowid","", $param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Title",$_SERVER["PHP_SELF"],"title","", $param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Link",'',''); + print_liste_field_titre("Target",'','','','','align="center"'); + print_liste_field_titre("Owner",$_SERVER["PHP_SELF"],"u.lastname","", $param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"b.dateb","", $param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre("Position",$_SERVER["PHP_SELF"],"b.position","", $param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre(''); + print "\n"; - $var=True; - while ($i < $num) - { - $obj = $db->fetch_object($resql); + $var=True; + while ($i < $num) + { + $obj = $db->fetch_object($resql); - print ''; + print ''; - // Id - print ''; + // Id + print ''; - $linkintern=0; - $title=$obj->title; - $link=$obj->url; + $linkintern=0; + $title=$obj->title; + $link=$obj->url; - // Title - print "\n"; + // Title + print "\n"; - // Url - print '\n"; + // Url + print '\n"; - // Target - print '\n"; + // Target + print '\n"; - // Author - print '\n"; + print "\n"; - // Date creation - print '"; + // Date creation + print '"; - // Position - print '"; + // Position + print '"; - // Actions - print '"; - print "\n"; - $i++; - } - print "
 
 
'; - print "bid."\">".img_object($langs->trans("ShowBookmark"),"bookmark").' '.$obj->bid.""; - print ''; + print "rowid."\">".img_object($langs->trans("ShowBookmark"),"bookmark").' '.$obj->rowid.""; + print '"; - if ($obj->rowid) - { - // Lien interne societe - $linkintern=1; - $link="Dolibarr"; - if (! $obj->title) - { - // For compatibility with old Dolibarr bookmarks - require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $societe=new Societe($db); - $societe->fetch($obj->rowid); - $obj->title=$societe->name; - } - $title=img_object($langs->trans("ShowCompany"),"company").' '.$obj->title; - } - if ($linkintern) print "url."\">"; - print $title; - if ($linkintern) print ""; - print ""; + $linkintern=1; + if ($linkintern) print "url."\">"; + print $title; + if ($linkintern) print ""; + print "'; - if (! $linkintern) print 'target?' target="newlink"':'').'>'; - print $link; - if (! $linkintern) print ''; - print "'; + if (! $linkintern) print 'target?' target="newlink"':'').'>'; + print $link; + if (! $linkintern) print ''; + print "'; - if ($obj->target == 0) print $langs->trans("BookmarkTargetReplaceWindowShort"); - if ($obj->target == 1) print $langs->trans("BookmarkTargetNewWindowShort"); - print "'; + if ($obj->target == 0) print $langs->trans("BookmarkTargetReplaceWindowShort"); + if ($obj->target == 1) print $langs->trans("BookmarkTargetNewWindowShort"); + print "'; + // Author + print ''; if ($obj->fk_user) { - $userstatic->id=$obj->fk_user; - $userstatic->lastname=$obj->login; + $userstatic->id=$obj->fk_user; + $userstatic->lastname=$obj->login; print $userstatic->getNomUrl(1); } else { print $langs->trans("Public"); } - print "'.dol_print_date($db->jdate($obj->dateb),'day')."'.dol_print_date($db->jdate($obj->dateb),'day')."'.$obj->position."'.$obj->position."'; - if ($user->rights->bookmark->creer) - { - print "bid."&backtopage=".urlencode($_SERVER["PHP_SELF"])."\">".img_edit()." "; - } - if ($user->rights->bookmark->supprimer) - { - print "bid\">".img_delete().""; - } - else - { - print " "; - } - print "
"; - print '
'; + // Actions + print ''; + if ($user->rights->bookmark->creer) + { + print "rowid."&backtopage=".urlencode($_SERVER["PHP_SELF"])."\">".img_edit()." "; + } + if ($user->rights->bookmark->supprimer) + { + print "rowid\">".img_delete().""; + } + else + { + print " "; + } + print ""; + print "\n"; + $i++; + } + print ""; + print '
'; - $db->free($resql); + $db->free($resql); } else { - dol_print_error($db); + dol_print_error($db); } @@ -223,7 +209,7 @@ print "
\n"; if ($user->rights->bookmark->creer) { - print ''.$langs->trans("NewBookmark").''; + print ''.$langs->trans("NewBookmark").''; } print '
'; diff --git a/htdocs/cashdesk/affPied.php b/htdocs/cashdesk/affPied.php index efe56ac2762..8f54dd732a7 100644 --- a/htdocs/cashdesk/affPied.php +++ b/htdocs/cashdesk/affPied.php @@ -24,17 +24,24 @@ ?>
-use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) { - print "\n\n"; + print "\n\n"; print '' . "\n"; + jQuery(".classfortooltip").tooltip({ + show: { collision: "flipfit", effect:\'toggle\', delay:50 }, + hide: { effect:\'toggle\', delay: 50 }, + tooltipClass: "mytooltip", + content: function () { + return $(this).prop(\'title\'); /* To force to get title as is */ + } + }); + }); + ' . "\n"; } printCommonFooter('private'); diff --git a/htdocs/cashdesk/class/Facturation.class.php b/htdocs/cashdesk/class/Facturation.class.php index b55524a874a..8bfd1d3082c 100644 --- a/htdocs/cashdesk/class/Facturation.class.php +++ b/htdocs/cashdesk/class/Facturation.class.php @@ -117,7 +117,7 @@ class Facturation } // Define part of HT, VAT, TTC - $resultarray=calcul_price_total($this->qte, $this->prix(), $this->remisePercent(), $txtva, -1, -1, 0, 'HT', $use_npr, $product->type, $mysoc, $localtaxarray); + $resultarray=calcul_price_total($this->qte, $this->prix(), $this->remisePercent(), $txtva, -1, -1, 0, 'HT', $vat_npr, $product->type, $mysoc, $localtaxarray); // Calcul du total ht sans remise $total_ht = $resultarray[0]; @@ -207,6 +207,9 @@ class Facturation $total_ht=0; $total_ttc=0; + $total_vat = 0; + $total_localtax1 = 0; + $total_localtax2 = 0; $tab=array(); $tab = $_SESSION['poscart']; @@ -309,7 +312,7 @@ class Facturation public function ref($aRef=null) { - if ( !$aRef ) + if (is_null($aRef)) { return $this->ref; } @@ -330,9 +333,9 @@ class Facturation * @param int $aQte Qty * @return int Qty */ - public function qte( $aQte=null ) + public function qte($aQte=null) { - if ( !$aQte ) + if (is_null($aQte)) { return $this->qte; } @@ -357,7 +360,7 @@ class Facturation public function stock($aStock=null) { - if ( !$aStock ) + if (is_null($aStock)) { return $this->stock; } @@ -381,7 +384,7 @@ class Facturation public function remisePercent($aRemisePercent=null) { - if ( !$aRemisePercent ) + if (is_null($aRemisePercent)) { return $this->remise_percent; } @@ -405,7 +408,7 @@ class Facturation public function montantRemise($aMontantRemise=null) { - if ( !$aMontantRemise ) { + if (is_null($aMontantRemise)) { return $this->montant_remise; @@ -427,10 +430,10 @@ class Facturation * @param int $aPrix Price * @return string Stock */ - public function prix ( $aPrix=null ) + public function prix($aPrix=null) { - if ( !$aPrix ) { + if (is_null($aPrix)) { return $this->prix; @@ -454,7 +457,7 @@ class Facturation */ public function tva($aTva=null) { - if ( !$aTva ) { + if (is_null($aTva)) { return $this->tva; @@ -478,7 +481,7 @@ class Facturation */ public function numInvoice($aNumFacture=null) { - if ( !$aNumFacture ) { + if (is_null($aNumFacture)) { return $this->num_facture; @@ -499,10 +502,10 @@ class Facturation * @param int $aModeReglement Payment mode * @return int Payment mode */ - public function getSetPaymentMode( $aModeReglement=null ) + public function getSetPaymentMode($aModeReglement=null) { - if ( !$aModeReglement ) { + if (is_null($aModeReglement)) { return $this->mode_reglement; @@ -524,10 +527,10 @@ class Facturation * @param int $aMontantEncaisse Amount * @return int Amount */ - public function montantEncaisse( $aMontantEncaisse=null ) + public function montantEncaisse($aMontantEncaisse=null) { - if ( !$aMontantEncaisse ) { + if (is_null($aMontantEncaisse)) { return $this->montant_encaisse; @@ -549,10 +552,10 @@ class Facturation * @param int $aMontantRendu Amount * @return int Amount */ - public function montantRendu( $aMontantRendu=null ) + public function montantRendu($aMontantRendu=null) { - if ( !$aMontantRendu ) { + if (is_null($aMontantRendu)) { return $this->montant_rendu; } else if ( $aMontantRendu == 'RESET' ) { @@ -573,9 +576,9 @@ class Facturation * @param date $aPaiementLe Date * @return date Date */ - public function paiementLe( $aPaiementLe=null ) + public function paiementLe($aPaiementLe=null) { - if ( !$aPaiementLe ) { + if (is_null($aPaiementLe)) { return $this->paiement_le; @@ -596,9 +599,9 @@ class Facturation * @param int $aTotalHt Total amount * @return int Total amount */ - public function prixTotalHt( $aTotalHt=null ) + public function prixTotalHt($aTotalHt=null) { - if ( !$aTotalHt ) { + if (is_null($aTotalHt)) { return $this->prix_total_ht; @@ -619,9 +622,9 @@ class Facturation * @param int $aMontantTva Amount vat * @return int Amount vat */ - public function montantTva( $aMontantTva=null ) + public function montantTva($aMontantTva=null) { - if ( !$aMontantTva ) { + if (is_null($aMontantTva)) { return $this->montant_tva; @@ -643,9 +646,9 @@ class Facturation * @param int $aTotalTtc Amount ttc * @return int Amount ttc */ - public function prixTotalTtc( $aTotalTtc=null ) + public function prixTotalTtc($aTotalTtc=null) { - if ( !$aTotalTtc ) + if (is_null($aTotalTtc)) { return $this->prix_total_ttc; } diff --git a/htdocs/cashdesk/css/style.css b/htdocs/cashdesk/css/style.css index c34e8596f01..d4149619aae 100644 --- a/htdocs/cashdesk/css/style.css +++ b/htdocs/cashdesk/css/style.css @@ -260,10 +260,6 @@ p.titre { padding: 0; } -.resultats_dhtml { - width: 400px; - position: absolute; -} /* --------------------- Combo lists ------------------- */ .select_design { diff --git a/htdocs/cashdesk/index.php b/htdocs/cashdesk/index.php index 8f6af8b6d4d..4269bb92199 100644 --- a/htdocs/cashdesk/index.php +++ b/htdocs/cashdesk/index.php @@ -105,7 +105,7 @@ print ''; $disabled=0; $langs->load("companies"); if (! empty($conf->global->CASHDESK_ID_THIRDPARTY)) $disabled=1; // If a particular third party is defined, we disable choice -print $form->select_company(GETPOST('socid','int')?GETPOST('socid','int'):$conf->global->CASHDESK_ID_THIRDPARTY,'socid','s.client in (1,3)',!$disabled,$disabled,1); +print $form->select_company(GETPOST('socid','int')?GETPOST('socid','int'):$conf->global->CASHDESK_ID_THIRDPARTY, 'socid', 's.client in (1,3)', !$disabled, 0, 0); //print ''; print ''; print "\n"; diff --git a/htdocs/cashdesk/javascript/dhtml.js b/htdocs/cashdesk/javascript/dhtml.js index 7f5df55a767..db05855a3b2 100644 --- a/htdocs/cashdesk/javascript/dhtml.js +++ b/htdocs/cashdesk/javascript/dhtml.js @@ -51,26 +51,14 @@ function file(fichier) { } -// Affichage des donnees aTexte dans le bloc identifie par aId -function afficheDonnees(aId, aTexte) { - - document.getElementById(aId).innerHTML = aTexte; - -} - - // aCible : id du bloc de destination; aCode : argument a passer a la page php chargee du traitement et de l'affichage function verifResultat(aCible, aCode, iLimit) { if (aCode != '' && aCode.length >= iLimit) { if (texte = file('facturation_dhtml.php?code='+escape(aCode))) { - - afficheDonnees (aCible, texte); - + document.getElementById(aCible).innerHTML = texte; } else - - afficheDonnees (aCible, ''); - + document.getElementById(aCible).innerHTML = ''; } } diff --git a/htdocs/cashdesk/tpl/facturation1.tpl.php b/htdocs/cashdesk/tpl/facturation1.tpl.php index 580012847f5..3f0a0f4c371 100644 --- a/htdocs/cashdesk/tpl/facturation1.tpl.php +++ b/htdocs/cashdesk/tpl/facturation1.tpl.php @@ -42,11 +42,10 @@ $langs->load("cashdesk"); trans("FilterRefOrLabelOrBC"); ?>trans("Designation"); ?> + + onfocus="javascript: this.select();" /> trans("Cash")."\n"; $note .= $langs->trans("Received").' : '.$obj_facturation->montantEncaisse()." ".$conf->currency."\n"; @@ -145,11 +145,11 @@ switch ($action) $note .= '--------------------------------------'."\n\n"; break; case 'CB': - $mode_reglement_id = dol_getIdFromCode($db,'CB','c_paiement'); + $mode_reglement_id = dol_getIdFromCode($db,'CB','c_paiement','code','id',1); $cond_reglement_id = 0; break; case 'CHQ': - $mode_reglement_id = dol_getIdFromCode($db,'CHQ','c_paiement'); + $mode_reglement_id = dol_getIdFromCode($db,'CHQ','c_paiement','code','id',1); $cond_reglement_id = 0; break; } diff --git a/htdocs/categories/admin/categorie_extrafields.php b/htdocs/categories/admin/categorie_extrafields.php index c72ef73e970..c20dff5db42 100644 --- a/htdocs/categories/admin/categorie_extrafields.php +++ b/htdocs/categories/admin/categorie_extrafields.php @@ -37,7 +37,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index ed10e337f7b..edbc4fa68ce 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -23,13 +23,13 @@ /** * API class for categories * - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} */ class Categories extends DolibarrApi { /** - * @var array $FIELDS Mandatory fields, checked when create and update object + * @var array $FIELDS Mandatory fields, checked when create and update object */ static $FIELDS = array( 'label', @@ -44,7 +44,7 @@ class Categories extends DolibarrApi 4 => 'contact', 5 => 'account', ); - + /** * @var Categorie $category {@type Categorie} */ @@ -67,20 +67,20 @@ class Categories extends DolibarrApi * * @param int $id ID of category * @return array|mixed data without useless information - * + * * @throws RestException */ function get($id) - { + { if(! DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } - + $result = $this->category->fetch($id); if( ! $result ) { throw new RestException(404, 'category not found'); } - + if( ! DolibarrApi::_checkAccessToResource('category',$this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -90,7 +90,7 @@ class Categories extends DolibarrApi /** * List categories - * + * * Get a list of categories * * @param string $sortfield Sort field @@ -103,15 +103,15 @@ class Categories extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $type = '', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $sqlfilters = '') { global $db, $conf; - + $obj_ret = array(); - + if(! DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } - + $sql = "SELECT t.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."categorie as t"; $sql.= ' WHERE t.entity IN ('.getEntity('category').')'; @@ -120,7 +120,7 @@ class Categories extends DolibarrApi $sql.= ' AND t.type='.array_search($type,Categories::$TYPES); } // Add sql filters - if ($sqlfilters) + if ($sqlfilters) { if (! DolibarrApi::_checkFilters($sqlfilters)) { @@ -129,93 +129,6 @@ class Categories extends DolibarrApi $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - - $sql.= $db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) - { - $page = 0; - } - $offset = $limit * $page; - - $sql.= $db->plimit($limit + 1, $offset); - } - - $result = $db->query($sql); - if ($result) - { - $i=0; - $num = $db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { - $obj = $db->fetch_object($result); - $category_static = new Categorie($db); - if($category_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($category_static); - } - $i++; - } - } - else { - throw new RestException(503, 'Error when retrieve category list : '.$db->lasterror()); - } - if( ! count($obj_ret)) { - throw new RestException(404, 'No category found'); - } - return $obj_ret; - } - - /** - * List categories of an entity - * - * Note: This method is not directly exposed in the API, it is used - * in the GET /xxx/{id}/categories requests. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @param int $item Id of the item to get categories for - * @return array Array of category objects - * - * @access private - */ - function getListForItem($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $type='customer', $item = 0) { - global $db, $conf; - - $obj_ret = array(); - - if(! DolibarrApiAccess::$user->rights->categorie->lire) { - throw new RestException(401); - } - //if ($type == "") { - //$type="product"; - //} - $sub_type = $type; - $subcol_name = "fk_".$type; - if ($type=="customer" || $type=="supplier") { - $sub_type="societe"; - $subcol_name="fk_soc"; - } - if ($type=="contact") { - $subcol_name="fk_socpeople"; - } - $sql = "SELECT s.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie as s"; - $sql.= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub "; - $sql.= ' WHERE s.entity IN ('.getEntity('category').')'; - $sql.= ' AND s.type='.array_search($type,Categories::$TYPES); - $sql.= ' AND s.rowid = sub.fk_categorie'; - $sql.= ' AND sub.'.$subcol_name.' = '.$item; - - $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - } $sql.= $db->order($sortfield, $sortorder); if ($limit) { @@ -250,13 +163,12 @@ class Categories extends DolibarrApi if( ! count($obj_ret)) { throw new RestException(404, 'No category found'); } - return $obj_ret; } /** * Create category object - * + * * @param array $request_data Request data * @return int ID of category */ @@ -268,7 +180,7 @@ class Categories extends DolibarrApi // Check mandatory fields $result = $this->_validate($request_data); - + foreach($request_data as $field => $value) { $this->category->$field = $value; } @@ -280,22 +192,22 @@ class Categories extends DolibarrApi /** * Update category - * + * * @param int $id Id of category to update - * @param array $request_data Datas - * @return int + * @param array $request_data Datas + * @return int */ function put($id, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->categorie->creer) { throw new RestException(401); } - + $result = $this->category->fetch($id); if( ! $result ) { throw new RestException(404, 'category not found'); } - + if( ! DolibarrApi::_checkAccessToResource('category',$this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -304,13 +216,13 @@ class Categories extends DolibarrApi if ($field == 'id') continue; $this->category->$field = $value; } - + if($this->category->update(DolibarrApiAccess::$user)) return $this->get ($id); - + return false; } - + /** * Delete category * @@ -326,15 +238,15 @@ class Categories extends DolibarrApi if( ! $result ) { throw new RestException(404, 'category not found'); } - + if( ! DolibarrApi::_checkAccessToResource('category',$this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + if (! $this->category->delete(DolibarrApiAccess::$user)) { throw new RestException(401,'error when delete category'); } - + return array( 'success' => array( 'code' => 200, @@ -342,8 +254,8 @@ class Categories extends DolibarrApi ) ); } - - + + /** * Clean sensible object datas * @@ -351,9 +263,9 @@ class Categories extends DolibarrApi * @return array Array of cleaned object properties */ function _cleanObjectDatas($object) { - + $object = parent::_cleanObjectDatas($object); - + // Remove fields not relevent to categories unset($object->country); unset($object->country_id); @@ -394,16 +306,16 @@ class Categories extends DolibarrApi unset($object->fk_project); unset($object->note); unset($object->statut); - + return $object; } - + /** * Validate fields before create or update object - * + * * @param array|null $data Data to validate * @return array - * + * * @throws RestException */ function _validate($data) diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 95a5629fb14..2e69626c1aa 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -42,35 +42,48 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; */ class Categorie extends CommonObject { - // Categories types - const TYPE_PRODUCT = 0; // TODO Replace with value 'product' - const TYPE_SUPPLIER = 1; // TODO Replace this value with 'supplier' - const TYPE_CUSTOMER = 2; // TODO Replace this value with 'customer' - const TYPE_MEMBER = 3; // TODO Replace this value with 'member' - const TYPE_CONTACT = 4; // TODO Replace this value with 'contact' - const TYPE_USER = 4; // categorie contact and user are same ! TODO Replace this value with 'user' - - const TYPE_ACCOUNT = 5; // TODO Replace this value with 'bank_account' - const TYPE_PROJECT = 6; // TODO Replace this value with 'project' + // Categories types (we use string because we want to accept any modules/types in a future) + const TYPE_PRODUCT = 'product'; + const TYPE_SUPPLIER = 'supplier'; + const TYPE_CUSTOMER = 'customer'; + const TYPE_MEMBER = 'member'; + const TYPE_CONTACT = 'contact'; + const TYPE_USER = 'user'; + const TYPE_PROJECT = 'project'; + const TYPE_ACCOUNT = 'bank_account'; const TYPE_BANK_LINE = 'bank_line'; + public $picto = 'category'; /** * @var array ID mapping from type string * - * @note This array should be remove in future, once previous constants are moved to the string value. + * @note This array should be remove in future, once previous constants are moved to the string value. Deprecated */ private $MAP_ID = array( - 'product' => 0, - 'supplier' => 1, - 'customer' => 2, - 'member' => 3, - 'contact' => 4, - 'user' => 4, - 'account' => 5, - 'project' => 6, + 'product' => 0, + 'supplier' => 1, + 'customer' => 2, + 'member' => 3, + 'contact' => 4, + 'bank_account' => 5, + 'project' => 6, + 'user' => 7, + 'bank_line' => 8, ); + public static $MAP_ID_TO_CODE = array( + 0 => 'product', + 1 => 'supplier', + 2 => 'customer', + 3 => 'member', + 4 => 'contact', + 5 => 'bank_account', + 6 => 'project', + 7 => 'user', + 8 => 'bank_line', + ); + /** * @var array Foreign keys mapping from type string * @@ -82,9 +95,10 @@ class Categorie extends CommonObject 'supplier' => 'soc', 'member' => 'member', 'contact' => 'socpeople', - 'user' => 'user', - 'account' => 'account', - 'project' => 'project', + 'user' => 'user', + 'account' => 'account', // old for bank_account + 'bank_account' => 'account', + 'project' => 'project', ); /** * @var array Category tables mapping from type string @@ -97,9 +111,10 @@ class Categorie extends CommonObject 'supplier' => 'fournisseur', 'member' => 'member', 'contact' => 'contact', - 'user' => 'user', - 'account' => 'account', - 'project' => 'project', + 'user' => 'user', + 'account' => 'account', // old for bank_account + 'bank_account'=> 'account', + 'project' => 'project', ); /** * @var array Object class mapping from type string @@ -113,8 +128,9 @@ class Categorie extends CommonObject 'member' => 'Adherent', 'contact' => 'Contact', 'user' => 'User', - 'account' => 'Account', - 'project' => 'Project', + 'account' => 'Account', // old for bank account + 'bank_account' => 'Account', + 'project' => 'Project', ); /** * @var array Object table mapping from type string @@ -128,8 +144,8 @@ class Categorie extends CommonObject 'member' => 'adherent', 'contact' => 'socpeople', 'user' => 'user', - 'account' => 'bank_account', - 'project' => 'projet', + 'account' => 'bank_account', + 'project' => 'projet', ); public $element='category'; @@ -147,7 +163,7 @@ class Categorie extends CommonObject */ public $socid; /** - * @var int Category type + * @var string Category type * * @see Categorie::TYPE_PRODUCT * @see Categorie::TYPE_SUPPLIER @@ -178,15 +194,16 @@ class Categorie extends CommonObject * * @param int $id Id of category * @param string $label Label of category - * @param string $type Type of category + * @param string $type Type of category ('product', '...') or (0, 1, ...) * @return int <0 if KO, >0 if OK */ - function fetch($id,$label='',$type='') + function fetch($id, $label='', $type=null) { global $conf; // Check parameters if (empty($id) && empty($label)) return -1; + if (! is_numeric($type)) $type=$this->MAP_ID[$type]; $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type"; $sql.= " FROM ".MAIN_DB_PREFIX."categorie"; @@ -197,7 +214,7 @@ class Categorie extends CommonObject else { $sql.= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")"; - if ($type) $sql.= " AND type = '".$this->db->escape($type)."'"; + if (! is_null($type)) $sql.= " AND type = ".$this->db->escape($type); } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -254,6 +271,10 @@ class Categorie extends CommonObject global $conf,$langs,$hookmanager; $langs->load('categories'); + $type=$this->type; + + if (! is_numeric($type)) $type=$this->MAP_ID[$type]; + $error=0; dol_syslog(get_class($this).'::create', LOG_DEBUG); @@ -290,7 +311,7 @@ class Categorie extends CommonObject $sql.= " import_key,"; $sql.= " entity"; $sql.= ") VALUES ("; - $sql.= $this->fk_parent.","; + $sql.= $this->db->escape($this->fk_parent).","; $sql.= "'".$this->db->escape($this->label)."',"; $sql.= "'".$this->db->escape($this->description)."',"; $sql.= "'".$this->db->escape($this->color)."',"; @@ -298,10 +319,10 @@ class Categorie extends CommonObject { $sql.= ($this->socid != -1 ? $this->socid : 'null').","; } - $sql.= "'".$this->visible."',"; - $sql.= $this->type.","; + $sql.= "'".$this->db->escape($this->visible)."',"; + $sql.= $this->db->escape($type).","; $sql.= (! empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":'null').","; - $sql.= $conf->entity; + $sql.= $this->db->escape($conf->entity); $sql.= ")"; $res = $this->db->query($sql); @@ -618,12 +639,11 @@ class Categorie extends CommonObject /** * Link an object to the category * - * @param CommonObject $obj Object to link to category - * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') - * - * @return int 1 : OK, -1 : erreur SQL, -2 : id not defined, -3 : Already linked + * @param CommonObject $obj Object to link to category + * @param string $type Type of category ('product', ...) + * @return int 1 : OK, -1 : erreur SQL, -2 : id not defined, -3 : Already linked */ - function add_type($obj,$type) + function add_type($obj, $type) { global $user,$langs,$conf; @@ -746,12 +766,10 @@ class Categorie extends CommonObject // For backward compatibility if ($type == 'societe') { $type = 'customer'; - dol_syslog( get_class( $this ) . "::del_type(): type 'societe' is deprecated, please use 'customer' instead", - LOG_WARNING ); + dol_syslog( get_class( $this ) . "::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING); } elseif ($type == 'fournisseur') { $type = 'supplier'; - dol_syslog( get_class( $this ) . "::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", - LOG_WARNING ); + dol_syslog( get_class( $this ) . "::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING); } $this->db->begin(); @@ -840,13 +858,12 @@ class Categorie extends CommonObject /** * Check for the presence of an object in a category * - * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') - * @param int $object_id id of the object to search - * - * @return int number of occurrences + * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') + * @param int $object_id Id of the object to search + * @return int Number of occurrences * @see getObjectsInCateg */ - function containsObject($type, $object_id ) + function containsObject($type, $object_id) { $sql = "SELECT COUNT(*) as nb FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type]; $sql .= " WHERE fk_categorie = " . $this->id . " AND fk_" . $this->MAP_CAT_FK[$type] . " = " . $object_id; @@ -860,6 +877,100 @@ class Categorie extends CommonObject } } + /** + * List categories of an element id + * + * @param int $id Id of element + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @return array Array of categories + */ + function getListForItem($id, $type='customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) + { + global $conf; + + $categories = array(); + + $sub_type = $type; + $subcol_name = "fk_".$type; + if ($type=="customer" || $type=="supplier") { + $sub_type="societe"; + $subcol_name="fk_soc"; + } + if ($type=="contact") { + $subcol_name="fk_socpeople"; + } + $sql = "SELECT s.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."categorie as s"; + $sql.= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub "; + $sql.= ' WHERE s.entity IN ('.getEntity('category').')'; + $sql.= ' AND s.type='.array_search($type, self::$MAP_ID_TO_CODE); + $sql.= ' AND s.rowid = sub.fk_categorie'; + $sql.= ' AND sub.'.$subcol_name.' = '.$id; + + $nbtotalofrecords = ''; + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + { + $result = $this->db->query($sql); + $nbtotalofrecords = $this->db->num_rows($result); + } + + $sql.= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $this->db->plimit($limit + 1, $offset); + } + + $result = $this->db->query($sql); + if ($result) + { + $i=0; + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + $category_static = new Categorie($this->db); + if ($category_static->fetch($obj->rowid)) + { + $categories[$i]['id'] = $category_static->id; + $categories[$i]['fk_parent'] = $category_static->fk_parent; + $categories[$i]['label'] = $category_static->label; + $categories[$i]['description'] = $category_static->description; + $categories[$i]['color'] = $category_static->color; + $categories[$i]['socid'] = $category_static->socid; + $categories[$i]['visible'] = $category_static->visible; + $categories[$i]['type'] = $category_static->type; + $categories[$i]['entity'] = $category_static->entity; + $categories[$i]['array_options'] = $category_static->array_options; + + // multilangs + if (! empty($conf->global->MAIN_MULTILANGS)) { + $categories[$i]['multilangs'] = $category_static->multilangs; + } + } + $i++; + } + } + else { + $this->error = $this->db->lasterror(); + return -1; + } + if ( ! count($categories)) { + return 0; + } + + return $categories; + } + /** * Return childs of a category * @@ -933,24 +1044,16 @@ class Categorie extends CommonObject * fulllabel = nom avec chemin complet de la categorie * fullpath = chemin complet compose des id * - * @param string $type Type of categories ('customer', 'supplier', 'contact', 'product', 'member'). - * Old mode (0, 1, 2, ...) is deprecated. - * @param int $markafterid Removed all categories including the leaf $markafterid in category tree. + * @param string $type Type of categories ('customer', 'supplier', 'contact', 'product', 'member') or (0, 1, 2, ...). + * @param int $markafterid Removed all categories including the leaf $markafterid in category tree. * - * @return array Array of categories. this->cats and this->motherof are set. + * @return array Array of categories. this->cats and this->motherof are set. */ function get_full_arbo($type, $markafterid=0) { global $conf, $langs; - // For backward compatibility - if (is_numeric($type)) - { - // We want to reverse lookup - $map_type = array_flip($this->MAP_ID); - $type = $map_type[$type]; - dol_syslog( get_class( $this ) . "::get_full_arbo(): numeric types are deprecated, please use string instead", LOG_WARNING); - } + if (! is_numeric($type)) $type = $this->MAP_ID[$type]; $this->cats = array(); @@ -964,7 +1067,7 @@ class Categorie extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."categorie as c"; if (! empty($conf->global->MAIN_MULTILANGS)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$current_lang."'"; $sql .= " WHERE c.entity IN (" . getEntity( 'category', 1 ) . ")"; - $sql .= " AND c.type = " . $this->MAP_ID[$type]; + $sql .= " AND c.type = " . $type; dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG); $resql = $this->db->query($sql); @@ -1088,7 +1191,7 @@ class Categorie extends CommonObject /** * Returns all categories * - * @param int $type Type of category + * @param int $type Type of category (0, 1, ...) * @param boolean $parent Just parent categories if true * @return array Table of Object Category */ @@ -1151,13 +1254,17 @@ class Categorie extends CommonObject */ function already_exists() { + $type=$this->type; + + if (! is_numeric($type)) $type=$this->MAP_ID[$type]; + /* We have to select any rowid from llx_categorie which category's mother and label * are equals to those of the calling category */ $sql = "SELECT c.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."categorie as c "; $sql.= " WHERE c.entity IN (".getEntity('category').")"; - $sql.= " AND c.type = ".$this->type; + $sql.= " AND c.type = ".$type; $sql.= " AND c.fk_parent = ".$this->fk_parent; $sql.= " AND c.label = '".$this->db->escape($this->label)."'"; @@ -1192,7 +1299,7 @@ class Categorie extends CommonObject /** * Returns the top level categories (which are not girls) * - * @param int $type Type of category + * @param int $type Type of category (0, 1, ...) * @return array */ function get_main_categories($type=null) @@ -1218,6 +1325,7 @@ class Categorie extends CommonObject { $w = array(); $i = 0; + $forced_color=''; foreach ($way as $cat) { $i++; @@ -1231,12 +1339,7 @@ class Categorie extends CommonObject $forced_color='categtextwhite'; if ($cat->color) { - $hex=$cat->color; - $r = hexdec($hex[0].$hex[1]); - $g = hexdec($hex[2].$hex[3]); - $b = hexdec($hex[4].$hex[5]); - $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm - if ($bright >= 0.5) $forced_color='categtextblack'; // Higher than 60% + if (colorIsLight($cat->color)) $forced_color='categtextblack'; } } } @@ -1330,26 +1433,19 @@ class Categorie extends CommonObject * Return list of categories (object instances or labels) linked to element of id $id and type $type * Should be named getListOfCategForObject * - * @param int $id Id of element - * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. - * @param string $mode 'id'=Get array of category ids, 'object'=Get array of fetched category instances, 'label'=Get array of category - * labels, 'id'= Get array of category IDs - * @return mixed Array of category objects or < 0 if KO + * @param int $id Id of element + * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') or (0, 1, 2, ...) + * @param string $mode 'id'=Get array of category ids, 'object'=Get array of fetched category instances, 'label'=Get array of category + * labels, 'id'= Get array of category IDs + * @return mixed Array of category objects or < 0 if KO */ function containing($id, $type, $mode='object') { $cats = array(); - // For backward compatibility - if (is_numeric($type)) - { - dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); - // We want to reverse lookup - $map_type = array_flip($this->MAP_ID); - $type = $map_type[$type]; - } + if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; - if ($type == Categorie::TYPE_BANK_LINE) // TODO Remove this with standard category code + if ($type === Categorie::TYPE_BANK_LINE) // TODO Remove this with standard category code { // Load bank groups $sql = "SELECT c.label, c.rowid"; @@ -1500,12 +1596,7 @@ class Categorie extends CommonObject $forced_color='categtextwhite'; if ($this->color) { - $hex=$this->color; - $r = hexdec($hex[0].$hex[1]); - $g = hexdec($hex[2].$hex[3]); - $b = hexdec($hex[4].$hex[5]); - $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm - if ($bright >= 0.5) $forced_color='categtextblack'; // Higher than 60% + if (colorIsLight($this->color)) $forced_color='categtextblack'; } $link = ''; @@ -1541,7 +1632,8 @@ class Categorie extends CommonObject } if (file_exists($dir)) { - if (is_array($file['name']) && count($file['name']) > 0) { + if (is_array($file['name']) && count($file['name']) > 0) + { $nbfile = count($file['name']); for ($i = 0; $i <= $nbfile; $i ++) { diff --git a/htdocs/categories/edit.php b/htdocs/categories/edit.php index 59bee88b75b..4ccd9116d74 100644 --- a/htdocs/categories/edit.php +++ b/htdocs/categories/edit.php @@ -36,7 +36,7 @@ $ref=GETPOST('ref'); $type=GETPOST('type'); $action=GETPOST('action','aZ09'); $confirm=GETPOST('confirm'); -$cancel=GETPOST('cancel'); +$cancel=GETPOST('cancel','alpha'); $socid=GETPOST('socid','int'); $label=GETPOST('label'); diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index ea4d60e9b5b..149eb160a78 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -39,6 +39,8 @@ $id=GETPOST('id','int'); $type=(GETPOST('type','aZ09') ? GETPOST('type','aZ09') : Categorie::TYPE_PRODUCT); $catname=GETPOST('catname','alpha'); +if (is_numeric($type)) $type=Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility + /* * View @@ -52,9 +54,9 @@ elseif ($type == Categorie::TYPE_SUPPLIER) { $title=$langs->trans("SuppliersCat elseif ($type == Categorie::TYPE_CUSTOMER) { $title=$langs->trans("CustomersCategoriesArea"); $typetext='customer'; } elseif ($type == Categorie::TYPE_MEMBER) { $title=$langs->trans("MembersCategoriesArea"); $typetext='member'; } elseif ($type == Categorie::TYPE_CONTACT) { $title=$langs->trans("ContactsCategoriesArea"); $typetext='contact'; } -elseif ($type == Categorie::TYPE_ACCOUNT) { $title=$langs->trans("AccountsCategoriesArea"); $typetext='account'; } -elseif ($type == Categorie::TYPE_USER) { $title=$langs->trans("UsersCategoriesArea"); $typetext='user'; } +elseif ($type == Categorie::TYPE_ACCOUNT) { $title=$langs->trans("AccountsCategoriesArea"); $typetext='bank_account'; } elseif ($type == Categorie::TYPE_PROJECT) { $title=$langs->trans("ProjectsCategoriesArea"); $typetext='project'; } +elseif ($type == Categorie::TYPE_USER) { $title=$langs->trans("UsersCategoriesArea"); $typetext='user'; } else { $title=$langs->trans("CategoriesArea"); $typetext='unknown'; } $arrayofjs=array('/includes/jquery/plugins/jquerytreeview/jquery.treeview.js', '/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js'); diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index e99e081e015..e6047ed2149 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -42,6 +42,8 @@ $type=GETPOST('type'); $action=GETPOST('action','aZ09'); $confirm=GETPOST('confirm'); +if (is_numeric($type)) $type=Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility + if ($id == "") { dol_print_error('','Missing parameter id'); @@ -100,15 +102,16 @@ if ($object->id) elseif ($type == Categorie::TYPE_CONTACT) $title=$langs->trans("ContactCategoriesShort"); elseif ($type == Categorie::TYPE_ACCOUNT) $title=$langs->trans("AccountsCategoriesShort"); elseif ($type == Categorie::TYPE_PROJECT) $title=$langs->trans("ProjectsCategoriesShort"); - else $title=$langs->trans("Category"); + elseif ($type == Categorie::TYPE_USER) $title=$langs->trans("UsersCategoriesShort"); + else $title=$langs->trans("Category"); $head = categories_prepare_head($object,$type); dol_fiche_head($head, 'photos', $title, -1, 'category'); - + $linkback = ''.$langs->trans("BackToList").''; - + $object->ref = $object->label; $morehtmlref='
'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); @@ -117,9 +120,9 @@ if ($object->id) $morehtmlref.=$way."
\n"; } $morehtmlref.='
'; - + dol_banner_tab($object, 'ref', $linkback, ($user->societe_id?0:1), 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); - + /* * Confirmation de la suppression de photo */ @@ -129,7 +132,7 @@ if ($object->id) } print '
'; - + print '
'; print '
'; print ''; @@ -148,7 +151,7 @@ if ($object->id) print "
\n"; print '
'; - + print dol_fiche_end(); @@ -258,7 +261,7 @@ if ($object->id) } print ''; - + if ($nbphoto < 1) { print '
'.$langs->trans("NoPhotoYet")."
"; diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index 7dbe6325e1d..40b40eab921 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -35,11 +35,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $langs->load("categories"); $langs->load("languages"); -$id = GETPOST('id', 'int'); -$ref = GETPOST('ref', 'alpha'); -$action=GETPOST('action','alpha'); -$cancel=GETPOST('cancel','alpha'); -$type=GETPOST('type'); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action','alpha'); +$cancel = GETPOST('cancel','alpha'); +$type = GETPOST('type','aZ09'); + +if (is_numeric($type)) $type=Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility // Security check $fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); @@ -153,6 +155,7 @@ elseif ($type == Categorie::TYPE_MEMBER) $title=$langs->trans("MembersCategor elseif ($type == Categorie::TYPE_CONTACT) $title=$langs->trans("ContactCategoriesShort"); elseif ($type == Categorie::TYPE_ACCOUNT) $title=$langs->trans("AccountsCategoriesShort"); elseif ($type == Categorie::TYPE_PROJECT) $title=$langs->trans("ProjectsCategoriesShort"); +elseif ($type == Categorie::TYPE_USER) $title=$langs->trans("UsersCategoriesShort"); else $title=$langs->trans("Category"); $head = categories_prepare_head($object,$type); @@ -256,9 +259,9 @@ if ($action == 'edit') print ''; } } - + print '
'; - + print '
'; print ''; print '     '; @@ -271,7 +274,7 @@ if ($action == 'edit') else if ($action != 'add') { if ($cnt_trans) print '
'; - + if (! empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 1c6186d5df4..daa5ade05b5 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -34,13 +34,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $langs->load("categories"); -$id=GETPOST('id','int'); -$label=GETPOST('label'); -$type=GETPOST('type'); +$id = GETPOST('id','int'); +$label= GETPOST('label','alpha'); +$type = GETPOST('type','az09'); $action=GETPOST('action','aZ09'); -$confirm=GETPOST('confirm'); +$confirm = GETPOST('confirm','alpha'); $removeelem = GETPOST('removeelem','int'); -$elemid=GETPOST('elemid'); +$elemid = GETPOST('elemid','alpha'); if ($id == "" && $label == "") { @@ -61,6 +61,7 @@ if ($result <= 0) } $type=$object->type; +if (is_numeric($type)) $type=Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility $extrafields = new ExtraFields($db); $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); @@ -87,13 +88,13 @@ if ($id > 0 && $removeelem > 0) { $tmpobject = new Societe($db); $result = $tmpobject->fetch($removeelem); - $elementtype = 'fournisseur'; + $elementtype = 'supplier'; } else if ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) { $tmpobject = new Societe($db); $result = $tmpobject->fetch($removeelem); - $elementtype = 'societe'; + $elementtype = 'customer'; } else if ($type == Categorie::TYPE_MEMBER && $user->rights->adherent->creer) { @@ -187,6 +188,7 @@ elseif ($type == Categorie::TYPE_MEMBER) $title=$langs->trans("MembersCategor elseif ($type == Categorie::TYPE_CONTACT) $title=$langs->trans("ContactCategoriesShort"); elseif ($type == Categorie::TYPE_ACCOUNT) $title=$langs->trans("AccountsCategoriesShort"); elseif ($type == Categorie::TYPE_PROJECT) $title=$langs->trans("ProjectsCategoriesShort"); +elseif ($type == Categorie::TYPE_USER) $title=$langs->trans("ProjectsCategoriesShort"); else $title=$langs->trans("Category"); $head = categories_prepare_head($object,$type); @@ -317,7 +319,7 @@ else // List of products or services (type is type of category) -if ($object->type == Categorie::TYPE_PRODUCT) +if ($type == Categorie::TYPE_PRODUCT) { $prods = $object->getObjectsInCateg("product"); if ($prods < 0) @@ -389,7 +391,7 @@ if ($object->type == Categorie::TYPE_PRODUCT) } } -if ($object->type == Categorie::TYPE_SUPPLIER) +if ($type == Categorie::TYPE_SUPPLIER) { $socs = $object->getObjectsInCateg("supplier"); if ($socs < 0) @@ -438,7 +440,7 @@ if ($object->type == Categorie::TYPE_SUPPLIER) } } -if($object->type == Categorie::TYPE_CUSTOMER) +if($type == Categorie::TYPE_CUSTOMER) { $socs = $object->getObjectsInCateg("customer"); if ($socs < 0) @@ -492,7 +494,7 @@ if($object->type == Categorie::TYPE_CUSTOMER) } // List of members -if ($object->type == Categorie::TYPE_MEMBER) +if ($type == Categorie::TYPE_MEMBER) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; @@ -545,7 +547,7 @@ if ($object->type == Categorie::TYPE_MEMBER) } // Categorie contact -if($object->type == Categorie::TYPE_CONTACT) +if ($type == Categorie::TYPE_CONTACT) { $contacts = $object->getObjectsInCateg("contact"); if ($contacts < 0) @@ -598,7 +600,7 @@ if($object->type == Categorie::TYPE_CONTACT) } // List of accounts -if ($object->type == Categorie::TYPE_ACCOUNT) +if ($type == Categorie::TYPE_ACCOUNT) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -651,7 +653,7 @@ if ($object->type == Categorie::TYPE_ACCOUNT) } // List of Project -if ($object->type == Categorie::TYPE_PROJECT) +if ($type == Categorie::TYPE_PROJECT) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; diff --git a/htdocs/collab/index.php b/htdocs/collab/index.php index 7f08beff955..2c056cd0e07 100644 --- a/htdocs/collab/index.php +++ b/htdocs/collab/index.php @@ -24,49 +24,6 @@ define('NOSCANPOSTFORINJECTION',1); define('NOSTYLECHECK',1); - -/** - * Show HTML header HTML + BODY + Top menu + left menu + DIV - * - * @param string $head Optionnal head lines - * @param string $title HTML title - * @param string $help_url Url links to help page - * Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage - * For other external page: http://server/url - * @param string $target Target to use on links - * @param int $disablejs More content into html header - * @param int $disablehead More content into html header - * @param array $arrayofjs Array of complementary js files - * @param array $arrayofcss Array of complementary css files - * @param string $morequerystring Query string to add to the link "print" to get same parameters (set this only if autodetect fails) - * @return void - */ -function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='') -{ - global $conf; - - // html header - top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); - - print ''; - - // top menu and left menu area - if (empty($conf->dol_hide_topmenu)) - { - top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url); - } - if (empty($conf->dol_hide_leftmenu)) - { - left_menu('', $help_url, '', '', 1, $title, 1); - } - - // main area - //main_area($title); - print ''."\n".'
'."\n"; -} - - - require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -79,7 +36,7 @@ if (! $user->admin) accessforbidden(); if (! ((GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))) { - $conf->dol_hide_leftmenu = 1; // Force hide of left menu. + $conf->dol_hide_leftmenu = 1; // Force hide of left menu. } $error=0; @@ -114,33 +71,33 @@ if (GETPOST('refreshpage')) $action='preview'; // Add a collab page if ($action == 'add') { - $db->begin(); + $db->begin(); - $objectpage->title = GETPOST('WEBSITE_TITLE'); - $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); - $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); - $objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); + $objectpage->title = GETPOST('WEBSITE_TITLE'); + $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); + $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); + $objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); - if (empty($objectpage->title)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); - $error++; - } + if (empty($objectpage->title)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); + $error++; + } - if (! $error) - { - $res = $objectpage->create($user); - if ($res <= 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } - } + if (! $error) + { + $res = $objectpage->create($user); + if ($res <= 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } + } if (! $error) { $db->commit(); - setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); - $action=''; + setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); + $action=''; } else { @@ -154,38 +111,38 @@ if ($action == 'add') // Update page if ($action == 'delete') { - $db->begin(); + $db->begin(); - $res = $object->fetch(0, $website); + $res = $object->fetch(0, $website); - $res = $objectpage->fetch($pageid, $object->fk_website); + $res = $objectpage->fetch($pageid, $object->fk_website); - if ($res > 0) - { - $res = $objectpage->delete($user); - if (! $res > 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } + if ($res > 0) + { + $res = $objectpage->delete($user); + if (! $res > 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website); - exit; - } - else - { - $db->rollback(); - } - } - else - { - dol_print_error($db); - } + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website); + exit; + } + else + { + $db->rollback(); + } + } + else + { + dol_print_error($db); + } } @@ -198,13 +155,13 @@ $form = new Form($db); $help_url=''; -llxHeader('', $langs->trans("WebsiteSetup"), $help_url); +llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, '', '', '', '', '', ''."\n".'
'); print "\n".'
'; print ''; if ($action == 'create') { - print ''; + print ''; } @@ -217,225 +174,225 @@ print '
'; if (count($object->records) > 0) { - // ***** Part for web sites + // ***** Part for web sites - print '
'; - print $langs->trans("Website").': '; - print '
'; + print '
'; + print $langs->trans("WebSite").': '; + print '
'; - // List of websites - print '
'; - $out=''; - $out.=''; + if (empty($object->records)) $out.=''; + // Loop on each sites + $i=0; + foreach($object->records as $key => $valwebsite) + { + if (empty($website)) $website=$valwebsite->ref; - $out.=''; - $i++; - } - $out.=''; - $out.=ajax_combobox('website'); - print $out; - print ''; + $out.=''; + $i++; + } + $out.=''; + $out.=ajax_combobox('website'); + print $out; + print ''; - if ($website) - { - $virtualurl=''; - $dataroot=DOL_DATA_ROOT.'/websites/'.$website; - if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; - } + if ($website) + { + $virtualurl=''; + $dataroot=DOL_DATA_ROOT.'/collab/'.$website; + if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; + } - if ($website && $action == 'preview') - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; + if ($website && $action == 'preview') + { + $disabled=''; + if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - print '   '; + print '   '; - //print ''; - print ''; - print ''; - print ''; - } + //print ''; + print ''; + print ''; + print ''; + } - print '
'; + print '
'; - // Button for websites - print '
'; + // Button for websites + print '
'; - if ($action == 'preview') - { - print '
'; - print ''; - //print ''; - $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); - print $form->textwithpicto('', $htmltext); - print '
'; + if ($action == 'preview') + { + print '
'; + print ''; + //print ''; + $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); + print $form->textwithpicto('', $htmltext); + print '
'; - $urlext=$virtualurl; - $urlint=$urlwithroot.'/public/websites/index.php?website='.$website; - //if (! empty($object->virtualhost)) - //{ - print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - //} + $urlext=$virtualurl; + $urlint=$urlwithroot.'/public/collab/index.php?website='.$website; + //if (! empty($object->virtualhost)) + //{ + print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); + print ''; + //} - print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint, $dataroot), 1, 'preview'); - print ''; - } + print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint, $dataroot), 1, 'preview'); + print ''; + } - if (in_array($action, array('editcss','editmenu','create'))) - { - if ($action != 'preview') print ''; - if (preg_match('/^create/',$action)) print ''; - if (preg_match('/^edit/',$action)) print ''; - } + if (in_array($action, array('editcss','editmenu','create'))) + { + if ($action != 'preview') print ''; + if (preg_match('/^create/',$action)) print ''; + if (preg_match('/^edit/',$action)) print ''; + } - print '
'; + print '
'; - // ***** Part for pages + // ***** Part for pages - if ($website) - { - print '
'; + if ($website) + { + print '
'; - $array=$objectpage->fetchAll($object->id); - if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); - $atleastonepage=(is_array($array) && count($array) > 0); + $array=$objectpage->fetchAll($object->id); + if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + $atleastonepage=(is_array($array) && count($array) > 0); - print '
'; - print '
'; - print $langs->trans("Page").': '; - print '
'; - print '
'; + print '
'; + print '
'; + print $langs->trans("Page").': '; + print '
'; + print '
'; - if ($action != 'add') - { - $out=''; - $out.=''; + if ($atleastonepage) + { + if (empty($pageid) && $action != 'create') // Page id is not defined, we try to take one + { + $firstpageid=0;$homepageid=0; + foreach($array as $key => $valpage) + { + if (empty($firstpageid)) $firstpageid=$valpage->id; + if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid=$valpage->id; + } + $pageid=$homepageid?$homepageid:$firstpageid; // We choose home page and if not defined yet, we take first page + } - foreach($array as $key => $valpage) - { - $out.=''; - } - } - else $out.=''; - $out.=''; - $out.=ajax_combobox('pageid'); - print $out; - } - else - { - print $langs->trans("New"); - } + foreach($array as $key => $valpage) + { + $out.=''; + } + } + else $out.=''; + $out.=''; + $out.=ajax_combobox('pageid'); + print $out; + } + else + { + print $langs->trans("New"); + } - print ''; - //print $form->selectarray('page', $array); + print ''; + //print $form->selectarray('page', $array); - if ($action == 'preview') - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; + if ($action == 'preview') + { + $disabled=''; + if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - if ($pageid > 0) - { - print '   '; + if ($pageid > 0) + { + print '   '; - if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; - else print ''; - print ''; - print ''; - //print ''.dol_escape_htmltag($langs->trans("EditPageMeta")).''; - //print ''.dol_escape_htmltag($langs->trans("EditPageContent")).''; - print ''; - } - } + if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; + else print ''; + print ''; + print ''; + //print ''.dol_escape_htmltag($langs->trans("EditPageMeta")).''; + //print ''.dol_escape_htmltag($langs->trans("EditPageContent")).''; + print ''; + } + } - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print '
'; + print '
'; - if ($website && $pageid > 0 && $action == 'preview') - { - $websitepage = new WebSitePage($db); - $websitepage->fetch($pageid); + if ($website && $pageid > 0 && $action == 'preview') + { + $websitepage = new WebSitePage($db); + $websitepage->fetch($pageid); - $realpage=$urlwithroot.'/public/websites/index.php?website='.$website.'&page='.$pageid; - $pagealias = $websitepage->pageurl; + $realpage=$urlwithroot.'/public/collab/index.php?website='.$website.'&page='.$pageid; + $pagealias = $websitepage->pageurl; - print '
'; - print ''; - //print ''; - $htmltext=$langs->trans("WEBSITE_PAGENAME", $pagealias); - print $form->textwithpicto('', $htmltext); - print '
'; + print '
'; + print ''; + //print ''; + $htmltext=$langs->trans("WEBSITE_PAGENAME", $pagealias); + print $form->textwithpicto('', $htmltext); + print '
'; - if (! empty($object->virtualhost)) - { - $urlext=$virtualurl.'/'.$pagealias.'.php'; - print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - } - else - { - print ''; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - } + if (! empty($object->virtualhost)) + { + $urlext=$virtualurl.'/'.$pagealias.'.php'; + print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); + print ''; + } + else + { + print ''; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); + print ''; + } - print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot), 1, 'preview'); - print ''; // View page in new Tab - //print ''; + print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot), 1, 'preview'); + print ''; // View page in new Tab + //print ''; - // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext - } - if (! in_array($action, array('editcss','editmenu','create'))) - { - if ($action != 'preview') print ''; - if (preg_match('/^create/',$action)) print ''; - if (preg_match('/^edit/',$action)) print ''; - } + // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext + } + if (! in_array($action, array('editcss','editmenu','create'))) + { + if ($action != 'preview') print ''; + if (preg_match('/^create/',$action)) print ''; + if (preg_match('/^edit/',$action)) print ''; + } - print '
'; + print '
'; - if ($action == 'preview') - { - // Adding jquery code to change on the fly url of preview ext - if (! empty($conf->use_javascript_ajax)) - { - print ''; - } - } - } + } + } + } } else { - print '
'; - $langs->load("errors"); - print $langs->trans("ErrorModuleSetupNotComplete"); - print '
'; - $action=''; + print '
'; + $langs->load("errors"); + print $langs->trans("ErrorModuleSetupNotComplete"); + print '
'; + $action=''; } @@ -480,21 +437,21 @@ $head = array(); if ($action == 'editcontent') { - /* + /* * Editing global variables not related to a specific theme */ - $csscontent = @file_get_contents($filecss); + $csscontent = @file_get_contents($filecss); - $contentforedit = ''; - /*$contentforedit.=''."\n";*/ - $contentforedit .= $objectpage->content; + $contentforedit .= $objectpage->content; - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%'); - $doleditor->Create(0, '', false); + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%'); + $doleditor->Create(0, '', false); } print "
\n\n"; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index 03d73635c17..15218406a94 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -199,8 +199,8 @@ if ($action == 'add') $percentage=in_array(GETPOST('status'),array(-1,100))?GETPOST('status'):(in_array(GETPOST('complete'),array(-1,100))?GETPOST('complete'):GETPOST("percentage")); // If status is -1 or 100, percentage is not defined and we must use status // Clean parameters - $datep=dol_mktime($fulldayevent?'00':GETPOST("aphour"), $fulldayevent?'00':GETPOST("apmin"), 0, GETPOST("apmonth"), GETPOST("apday"), GETPOST("apyear")); - $datef=dol_mktime($fulldayevent?'23':GETPOST("p2hour"), $fulldayevent?'59':GETPOST("p2min"), $fulldayevent?'59':'0', GETPOST("p2month"), GETPOST("p2day"), GETPOST("p2year")); + $datep=dol_mktime($fulldayevent?'00':GETPOST("aphour",'int'), $fulldayevent?'00':GETPOST("apmin",'int'), $fulldayevent?'00':GETPOST("apsec",'int'), GETPOST("apmonth",'int'), GETPOST("apday",'int'), GETPOST("apyear",'int')); + $datef=dol_mktime($fulldayevent?'23':GETPOST("p2hour",'int'), $fulldayevent?'59':GETPOST("p2min",'int'), $fulldayevent?'59':GETPOST("apsec",'int'), GETPOST("p2month",'int'), GETPOST("p2day",'int'), GETPOST("p2year",'int')); // Check parameters if (! $datef && $percentage == 100) @@ -397,7 +397,7 @@ if ($action == 'update') $datep=dol_mktime($fulldayevent?'00':$aphour, $fulldayevent?'00':$apmin, 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]); $datef=dol_mktime($fulldayevent?'23':$p2hour, $fulldayevent?'59':$p2min, $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]); - $object->fk_action = dol_getIdFromCode($db, GETPOST("actioncode"), 'c_actioncomm'); + $object->type_id = dol_getIdFromCode($db, GETPOST("actioncode"), 'c_actioncomm'); $object->label = GETPOST("label"); $object->datep = $datep; $object->datef = $datef; @@ -407,8 +407,6 @@ if ($action == 'update') $object->location = GETPOST('location'); $object->socid = GETPOST("socid"); $object->contactid = GETPOST("contactid",'int'); - //$object->societe->id = $_POST["socid"]; // deprecated - //$object->contact->id = $_POST["contactid"]; // deprecated $object->fk_project = GETPOST("projectid",'int'); $object->note = GETPOST("note"); $object->pnote = GETPOST("note"); @@ -773,9 +771,9 @@ if ($action == 'create') $events[]=array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1',1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); //For external user force the company to user company if (!empty($user->societe_id)) { - print $form->select_thirdparty_list($user->societe_id, 'socid', '', 1, 1, 0, $events); + print $form->select_company($user->societe_id, 'socid', '', 1, 1, 0, $events); } else { - print $form->select_thirdparty_list('', 'socid', '', 'SelectThirdParty', 1, 0, $events); + print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, $events); } } @@ -783,7 +781,7 @@ if ($action == 'create') // Related contact print ''.$langs->trans("ActionOnContact").''; - $form->select_contacts(GETPOST('socid','int'), GETPOST('contactid'), 'contactid', 1, '', '', 0, 'minwidth200'); + $form->selectcontacts(GETPOST('socid','int'), GETPOST('contactid'), 'contactid', 1, '', '', 0, 'minwidth200'); print ''; @@ -826,7 +824,7 @@ if ($action == 'create') // Description print ''.$langs->trans("Description").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('note',(GETPOST('note')?GETPOST('note'):$object->note),'',180,'dolibarr_notes','In',true,true,$conf->fckeditor->enabled,ROWS_5,'90%'); + $doleditor=new DolEditor('note',(GETPOST('note','none')?GETPOST('note','none'):$object->note),'',180,'dolibarr_notes','In',true,true,$conf->fckeditor->enabled,ROWS_5,'90%'); $doleditor->Create(); print ''; @@ -869,7 +867,7 @@ if ($id > 0) $datep=dol_mktime($fulldayevent?'00':$aphour, $fulldayevent?'00':$apmin, 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]); $datef=dol_mktime($fulldayevent?'23':$p2hour, $fulldayevent?'59':$p2min, $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]); - $object->fk_action = dol_getIdFromCode($db, GETPOST("actioncode"), 'c_actioncomm'); + $object->type_id = dol_getIdFromCode($db, GETPOST("actioncode"), 'c_actioncomm'); $object->label = GETPOST("label"); $object->datep = $datep; $object->datef = $datef; @@ -879,8 +877,6 @@ if ($id > 0) $object->location = GETPOST('location'); $object->socid = GETPOST("socid"); $object->contactid = GETPOST("contactid",'int'); - //$object->societe->id = $_POST["socid"]; // deprecated - //$object->contact->id = $_POST["contactid"]; // deprecated $object->fk_project = GETPOST("projectid",'int'); $object->note = GETPOST("note"); @@ -1206,14 +1202,13 @@ if ($id > 0) // Link to other agenda views $out=''; - $out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewPerUser").''; - $out.='
    '; - $out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewCal").''; - $out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewWeek").''; - $out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewDay").''; $linkback.=$out; diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 00561fcd3b0..a66a4635281 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -36,7 +36,7 @@ class ActionComm extends CommonObject public $element='action'; public $table_element = 'actioncomm'; public $table_rowid = 'id'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='action'; /** @@ -296,23 +296,23 @@ class ActionComm extends CommonObject $sql.= "elementtype,"; $sql.= "entity"; $sql.= ") VALUES ("; - $sql.= "'".$this->db->idate($now)."',"; - $sql.= (strval($this->datep)!=''?"'".$this->db->idate($this->datep)."'":"null").","; - $sql.= (strval($this->datef)!=''?"'".$this->db->idate($this->datef)."'":"null").","; - $sql.= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '')?"'".$this->durationp."'":"null").","; // deprecated + $sql.= "'".$this->db->idate($now)."', "; + $sql.= (strval($this->datep)!=''?"'".$this->db->idate($this->datep)."'":"null").", "; + $sql.= (strval($this->datef)!=''?"'".$this->db->idate($this->datef)."'":"null").", "; + $sql.= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '')?"'".$this->db->escape($this->durationp)."'":"null").", "; // deprecated $sql.= (isset($this->type_id)?$this->type_id:"null").","; - $sql.= (isset($this->type_code)?" '".$this->type_code."'":"null").","; - $sql.= ((isset($this->socid) && $this->socid > 0)?" '".$this->socid."'":"null").","; - $sql.= ((isset($this->fk_project) && $this->fk_project > 0)?" '".$this->fk_project."'":"null").","; - $sql.= " '".$this->db->escape($this->note)."',"; - $sql.= ((isset($this->contactid) && $this->contactid > 0)?"'".$this->contactid."'":"null").","; - $sql.= (isset($user->id) && $user->id > 0 ? "'".$user->id."'":"null").","; - $sql.= ($userownerid>0?"'".$userownerid."'":"null").","; - $sql.= ($userdoneid>0?"'".$userdoneid."'":"null").","; - $sql.= "'".$this->db->escape($this->label)."','".$this->percentage."','".$this->priority."','".$this->fulldayevent."','".$this->db->escape($this->location)."','".$this->punctual."',"; - $sql.= "'".$this->transparency."',"; - $sql.= (! empty($this->fk_element)?$this->fk_element:"null").","; - $sql.= (! empty($this->elementtype)?"'".$this->elementtype."'":"null").","; + $sql.= (isset($this->type_code)?" '".$this->db->escape($this->type_code)."'":"null").", "; + $sql.= ((isset($this->socid) && $this->socid > 0) ? $this->socid:"null").", "; + $sql.= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project:"null").", "; + $sql.= " '".$this->db->escape($this->note)."', "; + $sql.= ((isset($this->contactid) && $this->contactid > 0) ? $this->contactid:"null").", "; + $sql.= (isset($user->id) && $user->id > 0 ? $user->id:"null").", "; + $sql.= ($userownerid>0 ? $userownerid:"null").", "; + $sql.= ($userdoneid>0 ? $userdoneid:"null").", "; + $sql.= "'".$this->db->escape($this->label)."','".$this->db->escape($this->percentage)."','".$this->db->escape($this->priority)."','".$this->db->escape($this->fulldayevent)."','".$this->db->escape($this->location)."','".$this->db->escape($this->punctual)."', "; + $sql.= "'".$this->db->escape($this->transparency)."', "; + $sql.= (! empty($this->fk_element)?$this->fk_element:"null").", "; + $sql.= (! empty($this->elementtype)?"'".$this->db->escape($this->elementtype)."'":"null").", "; $sql.= $conf->entity; $sql.= ")"; @@ -754,15 +754,15 @@ class ActionComm extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm "; $sql.= " SET percent = '".$this->db->escape($this->percentage)."'"; - if ($this->fk_action > 0) $sql.= ", fk_action = '".$this->db->escape($this->fk_action)."'"; + if ($this->type_id > 0) $sql.= ", fk_action = '".$this->db->escape($this->type_id)."'"; $sql.= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'":"null"); $sql.= ", datep = ".(strval($this->datep)!='' ? "'".$this->db->idate($this->datep)."'" : 'null'); $sql.= ", datep2 = ".(strval($this->datef)!='' ? "'".$this->db->idate($this->datef)."'" : 'null'); - $sql.= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != ''?"'".$this->durationp."'":"null"); // deprecated + $sql.= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != ''?"'".$this->db->escape($this->durationp)."'":"null"); // deprecated $sql.= ", note = ".($this->note ? "'".$this->db->escape($this->note)."'":"null"); - $sql.= ", fk_project =". ($this->fk_project > 0 ? "'".$this->fk_project."'":"null"); - $sql.= ", fk_soc =". ($socid > 0 ? "'".$socid."'":"null"); - $sql.= ", fk_contact =". ($contactid > 0 ? "'".$contactid."'":"null"); + $sql.= ", fk_project =". ($this->fk_project > 0 ? $this->fk_project:"null"); + $sql.= ", fk_soc =". ($socid > 0 ? $socid:"null"); + $sql.= ", fk_contact =". ($contactid > 0 ? $contactid:"null"); $sql.= ", priority = '".$this->db->escape($this->priority)."'"; $sql.= ", fulldayevent = '".$this->db->escape($this->fulldayevent)."'"; $sql.= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'":"null"); @@ -770,8 +770,8 @@ class ActionComm extends CommonObject $sql.= ", fk_user_mod = ".$user->id; $sql.= ", fk_user_action=".($userownerid > 0 ? "'".$userownerid."'":"null"); $sql.= ", fk_user_done=".($userdoneid > 0 ? "'".$userdoneid."'":"null"); - if (! empty($this->fk_element)) $sql.= ", fk_element=".($this->fk_element?$this->fk_element:"null"); - if (! empty($this->elementtype)) $sql.= ", elementtype=".($this->elementtype?"'".$this->elementtype."'":"null"); + if (! empty($this->fk_element)) $sql.= ", fk_element=".($this->fk_element?$this->db->escape($this->fk_element):"null"); + if (! empty($this->elementtype)) $sql.= ", elementtype=".($this->elementtype?"'".$this->db->escape($this->elementtype)."'":"null"); $sql.= " WHERE id=".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); @@ -851,7 +851,8 @@ class ActionComm extends CommonObject } /** - * Load all objects with filters + * Load all objects with filters. + * WARNING: This make a fetch on all records instead of making one request with a join. * * @param DoliDb $db Database handler * @param int $socid Filter by thirdparty @@ -863,7 +864,7 @@ class ActionComm extends CommonObject * @param string $limit Limit number of answers * @return array or string Error string if KO, array with actions if OK */ - static function getActions($db, $socid=0, $fk_element=0, $elementtype='', $filter='', $sortfield='datep', $sortorder='DESC', $limit=0) + static function getActions($db, $socid=0, $fk_element=0, $elementtype='', $filter='', $sortfield='a.datep', $sortorder='DESC', $limit=0) { global $conf, $langs; @@ -880,7 +881,7 @@ class ActionComm extends CommonObject } if (! empty($filter)) $sql.= $filter; if ($sortorder && $sortfield) $sql.=$db->order($sortfield, $sortorder); - if ($limit) $sql.=$db->plimit($limit); + $sql.=$db->plimit($limit, 0); dol_syslog(get_class()."::getActions", LOG_DEBUG); $resql=$db->query($sql); @@ -910,55 +911,62 @@ class ActionComm extends CommonObject /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * - * @param User $user Objet user + * @param User $user Objet user + * @param int $load_state_board Charge indicateurs this->nb de tableau de bord * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ - function load_board($user) + function load_board($user, $load_state_board=0) { - global $conf, $langs; + global $conf, $langs; - $sql = "SELECT a.id, a.datep as dp"; - $sql.= " FROM (".MAIN_DB_PREFIX."actioncomm as a"; - $sql.= ")"; - if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; - $sql.= " WHERE a.percent >= 0 AND a.percent < 100"; - $sql.= " AND a.entity IN (".getEntity('agenda').")"; - if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")"; - if ($user->societe_id) $sql.=" AND a.fk_soc = ".$user->societe_id; - if (! $user->rights->agenda->allactions->read) $sql.= " AND (a.fk_user_author = ".$user->id . " OR a.fk_user_action = ".$user->id . " OR a.fk_user_done = ".$user->id . ")"; + if(empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp"; + else { + $this->nb=array(); + $sql = "SELECT count(a.id) as nb"; + } + $sql.= " FROM (".MAIN_DB_PREFIX."actioncomm as a"; + $sql.= ")"; + if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; + $sql.= " WHERE 1 = 1"; + if(empty($load_state_board)) $sql.= " AND a.percent >= 0 AND a.percent < 100"; + $sql.= " AND a.entity IN (".getEntity('agenda').")"; + if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")"; + if ($user->societe_id) $sql.=" AND a.fk_soc = ".$user->societe_id; + if (! $user->rights->agenda->allactions->read) $sql.= " AND (a.fk_user_author = ".$user->id . " OR a.fk_user_action = ".$user->id . " OR a.fk_user_done = ".$user->id . ")"; - $resql=$this->db->query($sql); - if ($resql) - { - $agenda_static = new ActionComm($this->db); + $resql=$this->db->query($sql); + if ($resql) + { + if(empty($load_state_board)) { + $agenda_static = new ActionComm($this->db); + $response = new WorkboardResponse(); + $response->warning_delay = $conf->agenda->warning_delay/60/60/24; + $response->label = $langs->trans("ActionsToDo"); + $response->url = DOL_URL_ROOT.'/comm/action/listactions.php?status=todo&mainmenu=agenda'; + if ($user->rights->agenda->allactions->read) $response->url.='&filtert=-1'; + $response->img = img_object('',"action",'class="inline-block valigntextmiddle"'); + } + // This assignment in condition is not a bug. It allows walking the results. + while ($obj=$this->db->fetch_object($resql)) + { + if(empty($load_state_board)) { + $response->nbtodo++; + $agenda_static->datep = $this->db->jdate($obj->dp); + if ($agenda_static->hasDelay()) $response->nbtodolate++; + } else $this->nb["actionscomm"]=$obj->nb; + } - $response = new WorkboardResponse(); - $response->warning_delay = $conf->agenda->warning_delay/60/60/24; - $response->label = $langs->trans("ActionsToDo"); - $response->url = DOL_URL_ROOT.'/comm/action/listactions.php?status=todo&mainmenu=agenda'; - if ($user->rights->agenda->allactions->read) $response->url.='&filtert=-1'; - $response->img = img_object('',"action"); - - // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) - { - $response->nbtodo++; - - $agenda_static->datep = $this->db->jdate($obj->dp); - - if ($agenda_static->hasDelay()) { - $response->nbtodolate++; - } - } - - return $response; - } - else - { - $this->error=$this->db->error(); - return -1; - } + $this->db->free($resql); + if(empty($load_state_board)) return $response; + else return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } } @@ -1127,7 +1135,6 @@ class ActionComm extends CommonObject if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL'); } - $tooltip = '' . $langs->trans('ShowAction'.$objp->code) . ''; if (! empty($this->ref)) $tooltip .= '
    ' . $langs->trans('Ref') . ': ' . $this->ref; @@ -1196,10 +1203,13 @@ class ActionComm extends CommonObject { $libelle.=(($this->type_code && $libelle!=$langs->transnoentities("Action".$this->type_code) && $langs->transnoentities("Action".$this->type_code)!="Action".$this->type_code)?' ('.$langs->transnoentities("Action".$this->type_code).')':''); } - $result.=$linkstart.img_object(($notooltip?'':$langs->trans("ShowAction").': '.$libelle), ($overwritepicto?$overwritepicto:'action'), ($notooltip?'class="valigntextbottom"':'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1).$linkend; } - if ($withpicto==1) $result.=' '; - $result.=$linkstart.$libelleshort.$linkend; + + $result.=$linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$langs->trans("ShowAction").': '.$libelle), ($overwritepicto?$overwritepicto:'action'), ($notooltip?'class="'.(($withpicto != 2) ? 'paddingright ' : '').'valigntextbottom"':'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1); + $result.=$libelleshort; + $result.=$linkend; + return $result; } @@ -1368,7 +1378,7 @@ class ActionComm extends CommonObject if ($qualified && $datestart) { - $eventarray[$datestart+$diff]=$event; + $eventarray[]=$event; } $diff++; } @@ -1502,5 +1512,40 @@ class ActionComm extends CommonObject return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay)); } + + /** + * Send reminders by emails + * CAN BE A CRON TASK + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function sendEmailsReminder() + { + global $conf, $langs; + + $this->output = ''; + $this->error=''; + + if (empty($conf->global->AGENDA_REMINDER_EMAIL)) + { + $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda")); + return 0; + } + + $now = dol_now(); + + dol_syslog(__METHOD__, LOG_DEBUG); + + // TODO Scan events of type 'email' into table llx_actioncomm_reminder with status todo, send email, then set status to done + + + + // Delete also very old past events (we do not keep more than 1 month record in past) + $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder WHERE dateremind < '".$this->db->jdate($now - (3600 * 24 * 32))."'"; + $this->db->query($sql); + + return 0; + } + } diff --git a/htdocs/comm/action/class/actioncommreminder.class.php b/htdocs/comm/action/class/actioncommreminder.class.php new file mode 100644 index 00000000000..4873db461f6 --- /dev/null +++ b/htdocs/comm/action/class/actioncommreminder.class.php @@ -0,0 +1,229 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file class/actioncommreminder.class.php + * \ingroup agenda + * \brief This file is a CRUD class file for ActionCommReminder (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; + + +/** + * Class for ActionCommReminder + */ +class ActionCommReminder extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'actioncomm_reminder'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'actioncomm_reminder'; + /** + * @var array Does actioncommreminder support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 0; + /** + * @var string String with name of icon for actioncommreminder. Must be the part after the 'object_' into object_actioncommreminder.png + */ + public $picto = 'generic'; + + + /** + * 'type' if the field format. + * 'label' the translation key. + * 'enabled' is a condition when the field must be managed. + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only. Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'position' is the sort order of field. + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'help' is a string visible as a tooltip on field + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'default' is a default value for creation (can still be replaced by the global setup of default values) + * 'showoncombobox' if field must be shown into the label of combobox + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",), + 'dateremind' => array('type'=>'datetime', 'label'=>'DateRemind', 'visible'=>1, 'enabled'=>1, 'position'=>60, 'notnull'=>1, 'index'=>1,), + 'typeremind' => array('type'=>'varchar(32)', 'label'=>'TypeRemind', 'visible'=>-1, 'enabled'=>1, 'position'=>55, 'notnull'=>1, 'comment'=>"email, browser, sms",), + 'fk_user' => array('type'=>'integer', 'label'=>'User', 'visible'=>-1, 'enabled'=>1, 'position'=>65, 'notnull'=>1, 'index'=>1,), + 'offsetvalue' => array('type'=>'integer', 'label'=>'OffsetValue', 'visible'=>1, 'enabled'=>1, 'position'=>56, 'notnull'=>1,), + 'offsetunit' => array('type'=>'varchar(1)', 'label'=>'OffsetUnit', 'visible'=>1, 'enabled'=>1, 'position'=>57, 'notnull'=>1, 'comment'=>"m, h, d, w",), + 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'default'=>0, 'index'=>0, 'arrayofkeyval'=>array('0'=>'ToDo', '1'=>'Done')), + ); + public $rowid; + public $dateremind; + public $typeremind; + public $fk_user; + public $offsetvalue; + public $offsetunit; + public $status; + // END MODULEBUILDER PROPERTIES + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + return $result; + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + } + + /** + * 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, 6=Long label + Picto + * @return string Label of status + */ + static function LibStatut($status,$mode=0) + { + global $langs; + + if ($mode == 0) + { + $prefix=''; + if ($status == 1) return $langs->trans('Done'); + if ($status == 0) return $langs->trans('ToDo'); + } + if ($mode == 1) + { + if ($status == 1) return $langs->trans('Done'); + if ($status == 0) return $langs->trans('ToDo'); + } + if ($mode == 2) + { + if ($status == 1) return img_picto($langs->trans('Done'),'statut4').' '.$langs->trans('Done'); + if ($status == 0) return img_picto($langs->trans('ToDo'),'statut5').' '.$langs->trans('ToDo'); + } + if ($mode == 3) + { + if ($status == 1) return img_picto($langs->trans('Done'),'statut4'); + if ($status == 0) return img_picto($langs->trans('ToDo'),'statut5'); + } + if ($mode == 4) + { + if ($status == 1) return img_picto($langs->trans('Done'),'statut4').' '.$langs->trans('Done'); + if ($status == 0) return img_picto($langs->trans('ToDo'),'statut5').' '.$langs->trans('ToDo'); + } + if ($mode == 5) + { + if ($status == 1) return $langs->trans('Done').' '.img_picto($langs->trans('Done'),'statut4'); + if ($status == 0) return $langs->trans('ToDo').' '.img_picto($langs->trans('ToDo'),'statut5'); + } + if ($mode == 6) + { + if ($status == 1) return $langs->trans('Done').' '.img_picto($langs->trans('Done'),'statut4'); + if ($status == 0) return $langs->trans('ToDo').' '.img_picto($langs->trans('ToDo'),'statut5'); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } + +} + diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index 493236b5ddf..981ae1025cf 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -128,14 +128,13 @@ if ($object->id > 0) // Link to other agenda views $out=''; - $out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewPerUser").''; - $out.='
    '; - $out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewCal").''; - $out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewWeek").''; - $out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewDay").''; $linkback.=$out; diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index e2bb57c3ce4..431ac1b5569 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -1375,7 +1375,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '>'; print 'trans("Agenda"),$help_url); @@ -66,14 +68,13 @@ $linkback.= ''.$langs->trans("B // Link to other agenda views $out=''; -$out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); +$out.='
  • '.img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewPerUser").''; -$out.='
    '; -$out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); +$out.='
  • '.img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewCal").''; -$out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); +$out.='
  • '.img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewWeek").''; -$out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); +$out.='
  • '.img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewDay").''; $linkback.=$out; diff --git a/htdocs/comm/action/listactions.php b/htdocs/comm/action/listactions.php index 4540580fed8..faa7cef8ed9 100644 --- a/htdocs/comm/action/listactions.php +++ b/htdocs/comm/action/listactions.php @@ -368,7 +368,7 @@ if ($resql) //$param='month='.$monthshown.'&year='.$year; $hourminsec='100000'; $link = ''; - $link.= $langs->trans("NewAction"); + $link.= $langs->trans("AddAction"); $link.= ''; } @@ -382,9 +382,10 @@ if ($resql) print '
  • '; print ''; + print ''; + print ''; print ''; - print ''; - print ''; print ''; print ''; if (! empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) print ''; - print ''; print ''; @@ -406,15 +406,15 @@ if ($resql) print ''; print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"a.id",$param,"","",$sortfield,$sortorder); - print_liste_field_titre("Title",$_SERVER["PHP_SELF"],"a.label",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("ActionsOwnedByShort",$_SERVER["PHP_SELF"],"",$param,"","",$sortfield,$sortorder); //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) - print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"c.libelle",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"c.libelle",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("Label",$_SERVER["PHP_SELF"],"a.label",$param,"","",$sortfield,$sortorder); print_liste_field_titre("DateStart",$_SERVER["PHP_SELF"],"a.datep",$param,'','align="center"',$sortfield,$sortorder); print_liste_field_titre("DateEnd",$_SERVER["PHP_SELF"],"a.datep2",$param,'','align="center"',$sortfield,$sortorder); print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"s.nom",$param,"","",$sortfield,$sortorder); print_liste_field_titre("Contact",$_SERVER["PHP_SELF"],"a.fk_contact",$param,"","",$sortfield,$sortorder); if (! empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) print_liste_field_titre("LinkedObject",$_SERVER["PHP_SELF"],"a.fk_element",$param,"","",$sortfield,$sortorder); - print_liste_field_titre("ActionsOwnedByShort",$_SERVER["PHP_SELF"],"",$param,"","",$sortfield,$sortorder); print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"a.percent",$param,"",'align="center"',$sortfield,$sortorder); print_liste_field_titre(""); print "\n"; @@ -448,14 +448,19 @@ if ($resql) print ''; - // Action (type) + // Ref print ''; - // Action (type) - print ''; // Type @@ -476,6 +481,11 @@ if ($resql) print dol_trunc($labeltype,28); print ''; + // Label + print ''; + // Start date print ''; // Third party - print ''; } - // User owner - print ''; - // Status/Percent $datep=$db->jdate($obj->datep); print ''; diff --git a/htdocs/comm/action/rapport/index.php b/htdocs/comm/action/rapport/index.php index dcda4e0cf04..5994f692cc8 100644 --- a/htdocs/comm/action/rapport/index.php +++ b/htdocs/comm/action/rapport/index.php @@ -116,7 +116,7 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans("Actions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_agenda', 0, '', '', $limit); + print_barre_liste($langs->trans("EventReports"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_agenda', 0, '', '', $limit); $moreforfilter=''; diff --git a/htdocs/comm/address.php b/htdocs/comm/address.php index 72e2dbadff4..6547f453b21 100644 --- a/htdocs/comm/address.php +++ b/htdocs/comm/address.php @@ -52,7 +52,7 @@ $object = new Address($db); */ // Cancel -if (GETPOST("cancel") && ! empty($backtopage)) +if (GETPOST('cancel','alpha') && ! empty($backtopage)) { header("Location: ".$backtopage); exit; diff --git a/htdocs/comm/admin/propal_extrafields.php b/htdocs/comm/admin/propal_extrafields.php index 8d2ecd88277..33c38282847 100644 --- a/htdocs/comm/admin/propal_extrafields.php +++ b/htdocs/comm/admin/propal_extrafields.php @@ -38,7 +38,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); @@ -87,7 +87,7 @@ if ($action != 'create' && $action != 'edit') /* ************************************************************************** */ /* */ -/* Creation of an optional field */ +/* Creation of an optional field */ /* */ /* ************************************************************************** */ diff --git a/htdocs/comm/admin/propaldet_extrafields.php b/htdocs/comm/admin/propaldet_extrafields.php index 80f5afdaeed..270274327e6 100644 --- a/htdocs/comm/admin/propaldet_extrafields.php +++ b/htdocs/comm/admin/propaldet_extrafields.php @@ -45,7 +45,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index 2da33334a92..8fb590d61b4 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -35,8 +35,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; -require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; if (! empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +if (! empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; if (! empty($conf->expedition->enabled)) require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; @@ -72,7 +73,7 @@ $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="nom"; -$cancelbutton = GETPOST('cancel'); +$cancelbutton = GETPOST('cancel','alpha'); $object = new Client($db); $extrafields = new ExtraFields($db); @@ -185,8 +186,12 @@ if (empty($reshook)) if ($ret < 0) $error++; if (! $error) { - $result = $object->insertExtraFields(); - if ($result < 0) $error++; + $result = $object->insertExtraFields(); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } if ($error) $action = 'edit_extras'; } @@ -206,7 +211,7 @@ if ($id > 0 && empty($object->id)) { // Load data of third party $res=$object->fetch($id); - if ($object->id <= 0) dol_print_error($db,$object->error); + if ($object->id <= 0) dol_print_error($db,$object->error,$object->errors); } $title=$langs->trans("CustomerCard"); @@ -605,11 +610,17 @@ if ($id > 0) if ($link) $boxstat.=''; } + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreBoxStatsCustomer', $parameters, $object, $action); + if(empty($reshook)){ + $boxstat.= $hookmanager->resPrint; + } + $boxstat.=''; $boxstat.='
    '; + print ''; print $form->select_date($datestart, 'datestart', 0, 0, 1, '', 1, 0, 1); print ''; @@ -393,7 +394,6 @@ if ($resql) print ''; print $formactions->form_select_status_action('formaction',$status,1,'status',1,2); print '
    '; print $actionstatic->getNomUrl(1,-1); print ''; - print $actionstatic->label; + // User owner + print ''; + if ($obj->fk_user_action > 0) + { + $userstatic->fetch($obj->fk_user_action); + print $userstatic->getNomUrl(-1); + } + else print ' '; print ''; + print $actionstatic->label; + print ''; print dol_print_date($db->jdate($obj->dp),"dayhour"); @@ -493,7 +503,7 @@ if ($resql) print ''; + print ''; if ($obj->socid) { $societestatic->id=$obj->socid; @@ -531,16 +541,6 @@ if ($resql) print ''; - if ($obj->fk_user_action > 0) - { - $userstatic->fetch($obj->fk_user_action); - print $userstatic->getNomUrl(-1); - } - else print ' '; - print ''.$actionstatic->LibStatut($obj->percent,3,0,$datep).'
    '; $boxstat.='
  • '; - print $boxstat; + print $boxstat; $now=dol_now(); @@ -947,6 +958,107 @@ if ($id > 0) } } + /* + * Last invoices templates + */ + if (! empty($conf->facture->enabled) && $user->rights->facture->lire) + { + $invoicetemplate = new FactureRec($db); + + $sql = 'SELECT f.rowid as id, f.titre as ref, f.amount'; + $sql.= ', f.total as total_ht'; + $sql.= ', f.tva as total_tva'; + $sql.= ', f.total_ttc'; + $sql.= ', f.datec as dc'; + $sql.= ', f.date_last_gen'; + $sql.= ', f.frequency'; + $sql.= ', f.unit_frequency'; + $sql.= ', f.suspended as suspended'; + $sql.= ', s.nom, s.rowid as socid'; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f"; + $sql.= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= ' GROUP BY f.rowid, f.titre, f.amount, f.total, f.tva, f.total_ttc,'; + $sql.= ' f.date_last_gen, f.datec, f.frequency, f.unit_frequency,'; + $sql.= ' f.suspended,'; + $sql.= ' s.nom, s.rowid'; + $sql.= " ORDER BY f.date_last_gen, f.datec DESC"; + + $resql=$db->query($sql); + if ($resql) + { + $var=true; + $num = $db->num_rows($resql); + $i = 0; + if ($num > 0) + { + print ''; + + print ''; + print ''; + print ''; + } + + while ($i < $num && $i < $MAXLIST) + { + $objp = $db->fetch_object($resql); + + print ''; + print ''; + if ($objp->frequency && $objp->date_last_gen > 0) + { + print ''; + } + else + { + if ($objp->dc > 0) + { + print ''; + } + else + { + print ''; + } + } + print ''; + + if (! empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES)) + { + print ''; + } + + print ''; + print "\n"; + $i++; + } + $db->free($resql); + + if ($num > 0) print "
    '; + print '
    '.$langs->trans("LatestCustomerTemplateInvoices",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllCustomerTemplateInvoices").' '.$num.'
    '; + $invoicetemplate->id = $objp->id; + $invoicetemplate->ref = $objp->ref; + $invoicetemplate->suspended = $objp->suspended; + $invoicetemplate->frequency = $objp->frequency; + $invoicetemplate->unit_frequency = $objp->unit_frequency; + $invoicetemplate->total_ht = $objp->total_ht; + $invoicetemplate->total_tva = $objp->total_tva; + $invoicetemplate->total_ttc = $objp->total_ttc; + print $invoicetemplate->getNomUrl(1); + print ''.dol_print_date($db->jdate($objp->date_last_gen),'day').''.dol_print_date($db->jdate($objp->dc),'day').'!!!'; + print price($objp->total_ht); + print ''; + print price($objp->total_ttc); + print ''; + print $langs->trans('FrequencyPer_'.$invoicetemplate->unit_frequency, $invoicetemplate->frequency).' - '; + print ($invoicetemplate->LibStatut($invoicetemplate->frequency,$invoicetemplate->suspended,5,0)); + print '
    "; + } + else + { + dol_print_error($db); + } + } + /* * Last invoices */ diff --git a/htdocs/comm/mailing/advtargetemailing.php b/htdocs/comm/mailing/advtargetemailing.php index 39d1b7c8d8d..cfafdaa725b 100644 --- a/htdocs/comm/mailing/advtargetemailing.php +++ b/htdocs/comm/mailing/advtargetemailing.php @@ -45,13 +45,13 @@ if (! empty($conf->categorie->enabled)) { if (! $user->rights->mailing->lire || $user->societe_id > 0) accessforbidden(); -$sortfield = GETPOST("sortfield", 'alpha'); -$sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); -if ($page == - 1) { - $page = 0; -} -$offset = $conf->liste_limit * $page; +// Load variable for pagination +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php index 14c8bf81510..c8338d22379 100644 --- a/htdocs/comm/mailing/card.php +++ b/htdocs/comm/mailing/card.php @@ -57,24 +57,17 @@ $hookmanager->initHooks(array('mailingcard','globalcard')); // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) $object->substitutionarray=FormMail::getAvailableSubstitKey('emailing'); -$object->substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); -$object->substitutionarrayfortest=array( - '__ID__' => 'TESTIdRecord', - //'__EMAIL__' => 'TESTEMail', // Done into "send" action - '__LASTNAME__' => 'TESTLastname', - '__FIRSTNAME__' => 'TESTFirstname', - '__MAILTOEMAIL__' => 'TESTMailtoEmail', - '__OTHER1__' => 'TESTOther1', - '__OTHER2__' => 'TESTOther2', - '__OTHER3__' => 'TESTOther3', - '__OTHER4__' => 'TESTOther4', - '__OTHER5__' => 'TESTOther5', - '__SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''), - '__CHECK_READ__' => 'TagCheckMail', - '__UNSUBSCRIBE__' => 'TagUnsubscribe' - //,'__PERSONALIZED__' => 'TESTPersonalized' // Not used yet -); + +// Set $object->substitutionarrayfortest +$signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''); + +$targetobject = null; // Not defined with mass emailing + +$parameters=array('mode'=>'emailing'); +$substitutionarray=FormMail::getAvailableSubstitKey('emailing', $targetobject); + +$object->substitutionarrayfortest = $substitutionarray; // List of sending methods $listofmethods=array(); @@ -189,8 +182,9 @@ if (empty($reshook)) while ($i < $num && $i < $conf->global->MAILING_LIMIT_SENDBYWEB) { - + // Here code is common with same loop ino mailing-send.php $res=1; + $now=dol_now(); $obj = $db->fetch_object($resql); @@ -204,24 +198,52 @@ if (empty($reshook)) $tmpfield=explode('=',$other[2],2); $other3=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); $tmpfield=explode('=',$other[3],2); $other4=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); $tmpfield=explode('=',$other[4],2); $other5=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''); - // Array of possible substitutions (See also fie mailing-send.php that should manage same substitutions) - $substitutionarray=array( - '__ID__' => $obj->source_id, - '__EMAIL__' => $obj->email, - '__LASTNAME__' => $obj->lastname, - '__FIRSTNAME__' => $obj->firstname, - '__MAILTOEMAIL__' => ''.$obj->email.'', - '__OTHER1__' => $other1, - '__OTHER2__' => $other2, - '__OTHER3__' => $other3, - '__OTHER4__' => $other4, - '__OTHER5__' => $other5, - '__SIGNATURE__' => $signature, // Signature is empty when ran from command line or taken from user in parameter) - '__CHECK_READ__' => '', - '__UNSUBSCRIBE__' => ''.$langs->trans("MailUnsubcribe").'' - ); + $targetobject = null; // Not defined with mass emailing + $parameters=array('mode'=>'emailing'); + $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount'), $targetobject); // Note: On mass emailing, this is null because be don't know object + + // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) + $substitutionarray['__ID__'] = $obj->source_id; + $substitutionarray['__EMAIL__'] = $obj->email; + $substitutionarray['__LASTNAME__'] = $obj->lastname; + $substitutionarray['__FIRSTNAME__'] = $obj->firstname; + $substitutionarray['__MAILTOEMAIL__'] = ''.$obj->email.''; + $substitutionarray['__OTHER1__'] = $other1; + $substitutionarray['__OTHER2__'] = $other2; + $substitutionarray['__OTHER3__'] = $other3; + $substitutionarray['__OTHER4__'] = $other4; + $substitutionarray['__OTHER5__'] = $other5; + $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) + $substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility + $substitutionarray['__CHECK_READ__'] = ''; + $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").''; + + $onlinepaymentenabled = 0; + if (! empty($conf->paypal->enabled)) $onlinepaymentenabled++; + if (! empty($conf->paybox->enabled)) $onlinepaymentenabled++; + if (! empty($conf->stripe->enabled)) $onlinepaymentenabled++; + if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN)) + { + $substitutionarray['__SECUREKEYPAYMENT__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) + { + $substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + } + else + { + $substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'order' . $obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2); + } + } + /* For backward compatibility */ if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN)) { $substitutionarray['__SECUREKEYPAYPAL__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); @@ -239,6 +261,7 @@ if (empty($reshook)) else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2); } //$substitutionisok=true; + complete_substitutions_array($substitutionarray, $langs); $newsubject=make_substitutions($subject,$substitutionarray); $newmessage=make_substitutions($message,$substitutionarray); @@ -409,9 +432,12 @@ if (empty($reshook)) $msgishtml=-1; // Inconnu par defaut if (preg_match('/[\s\t]*/i',$object->body)) $msgishtml=1; - $object->substitutionarrayfortest['__EMAIL__'] = $object->sendto; // other are set at begin of page + // other are set at begin of page + $object->substitutionarrayfortest['__EMAIL__'] = $object->sendto; + $object->substitutionarrayfortest['__MAILTOEMAIL__'] = ''.$object->sendto.''; // Pratique les substitutions sur le sujet et message + complete_substitutions_array($object->substitutionarrayfortest, $langs); $tmpsujet=make_substitutions($object->sujet,$object->substitutionarrayfortest); $tmpbody=make_substitutions($object->body,$object->substitutionarrayfortest); @@ -463,7 +489,7 @@ if (empty($reshook)) $object->email_errorsto = trim($_POST["errorsto"]); $object->titre = trim($_POST["titre"]); $object->sujet = trim($_POST["sujet"]); - $object->body = trim($_POST["body"]); + $object->body = trim($_POST["bodyemail"]); $object->bgcolor = trim($_POST["bgcolor"]); $object->bgimage = trim($_POST["bgimage"]); @@ -560,7 +586,7 @@ if (empty($reshook)) $mesgs = array(); $object->sujet = trim($_POST["sujet"]); - $object->body = trim($_POST["body"]); + $object->body = trim($_POST["bodyemail"]); $object->bgcolor = trim($_POST["bgcolor"]); $object->bgimage = trim($_POST["bgimage"]); @@ -686,7 +712,13 @@ $form = new Form($db); $htmlother = new FormOther($db); $help_url='EN:Module_EMailing|FR:Module_Mailing|ES:Módulo_Mailing'; -llxHeader('',$langs->trans("Mailing"),$help_url); +llxHeader('', $langs->trans("Mailing"), $help_url, '', 0, 0, + array( + '/includes/ace/ace.js', + '/includes/ace/ext-statusbar.js', + '/includes/ace/ext-language_tools.js', + //'/includes/ace/ext-chromevox.js' + ), array()); if ($action == 'create') { @@ -732,7 +764,7 @@ if ($action == 'create') print ''; print ''; print ''; print '
    '.$langs->trans("MailTopic").'
    '.$langs->trans("BackgroundColorByDefault").''; - print $htmlother->selectColor($_POST['bgcolor'],'bgcolor','new_mailing',0); + print $htmlother->selectColor($_POST['bgcolor'],'bgcolor','',0); print '
    '; @@ -740,7 +772,7 @@ if ($action == 'create') print '
    '; // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('body',$_POST['body'],'',600,'dolibarr_mailings','',true,true,$conf->global->FCKEDITOR_ENABLE_MAILING,20,'90%'); + $doleditor=new DolEditor('bodyemail',GETPOST('bodyemail','none'),'',600,'dolibarr_mailings','',true,true,$conf->global->FCKEDITOR_ENABLE_MAILING,20,'90%'); $doleditor->Create(); print '
    '; @@ -780,7 +812,7 @@ else } - if ($action != 'edit') + if ($action != 'edit' && $action != 'edithtml') { dol_fiche_head($head, 'card', $langs->trans("Mailing"), -1, 'email'); @@ -924,7 +956,7 @@ else * Boutons d'action */ - if (GETPOST("cancel") || $confirm=='no' || $action == '' || in_array($action,array('settodraft', 'valid','delete','sendall','clone'))) + if (GETPOST('cancel','alpha') || $confirm=='no' || $action == '' || in_array($action,array('settodraft', 'valid','delete','sendall','clone'))) { print "\n\n
    \n"; @@ -935,7 +967,16 @@ else if (($object->statut == 0 || $object->statut == 1) && $user->rights->mailing->creer) { - print ''.$langs->trans("EditMailing").''; + if (! empty($conf->fckeditor->enabled) && ! empty($conf->global->FCKEDITOR_ENABLE_MAILING)) + { + print ''.$langs->trans("EditWithEditor").''; + } + else + { + print ''.$langs->trans("EditWithTextEditor").''; + } + + if (! empty($conf->use_javascript_ajax)) print ''.$langs->trans("EditHTMLSource").''; } //print ''.$langs->trans("PreviewMailing").''; @@ -1036,7 +1077,7 @@ else $formmail->substit=$object->substitutionarrayfortest; // Tableau des parametres complementaires du post $formmail->param["action"]="send"; - $formmail->param["models"]="body"; + $formmail->param["models"]='none'; $formmail->param["mailid"]=$object->id; $formmail->param["returnurl"]=$_SERVER['PHP_SELF']."?id=".$object->id; @@ -1083,19 +1124,19 @@ else // Background color /*print ''.$langs->trans("BackgroundColorByDefault").''; - print $htmlother->selectColor($object->bgcolor,'bgcolor','edit_mailing',0); + print $htmlother->selectColor($object->bgcolor,'bgcolor','',0); print '';*/ print ''; // Message - print '
    '; - if (empty($object->bgcolor) || strtolower($object->bgcolor) == 'ffffff') + print '
    '; + if (empty($object->bgcolor) || strtolower($object->bgcolor) == 'ffffff') // CKEditor does not apply the color of the div into its content area { $readonly=1; // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('body',$object->body,'',600,'dolibarr_mailings','',false,true,empty($conf->global->FCKEDITOR_ENABLE_MAILING)?0:1,20,120,$readonly); + $doleditor=new DolEditor('bodyemail',$object->body,'',600,'dolibarr_mailings','',false,true,empty($conf->global->FCKEDITOR_ENABLE_MAILING)?0:1,20,'90%',$readonly); $doleditor->Create(); } else print dol_htmlentitiesbr($object->body); @@ -1107,7 +1148,7 @@ else else { /* - * Mailing en mode edition + * Mailing en mode edition (CKeditor or HTML source) */ dol_fiche_head($head, 'card', $langs->trans("Mailing"), -1, 'email'); @@ -1187,7 +1228,7 @@ else // Print mail content print load_fiche_titre($langs->trans("EMail"), $form->textwithpicto($langs->trans("AvailableVariables"), $htmltext, 1, 'help', '', 0, 2, 'emailsubstitionhelp'), 'title_generic'); - dol_fiche_head(); + dol_fiche_head(null, '', '', -1); print ''; @@ -1203,6 +1244,7 @@ else print ''; } print '' . "\n"; @@ -1424,12 +1432,12 @@ if ($action == 'create') $form->select_types_paiements($soc->mode_reglement_id, 'mode_reglement_id'); print ''; - // Bank Account - if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { - print ''; - } + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { + print ''; + } // What trigger creation print ''; - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + } // Delivery date (or manufacturing) print ''; @@ -1482,8 +1490,8 @@ if ($action == 'create') { print ''; print ''; - print ''; } @@ -1500,8 +1508,8 @@ if ($action == 'create') { print ''; print ''; - print ''; } @@ -1519,7 +1527,7 @@ if ($action == 'create') print ''; print ''; print ''; print ''; - print ''; + print ''; print "
    '; // List of files $listofpaths=dol_dir_list($upload_dir,'all',0,'','','name',SORT_ASC,0); + // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript $out.= ''."\n"; $out.= ''; } + print ' '.$langs->trans("AddThirdParty").''; print '
    ' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print '
    ' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print '
    ' . $langs->trans('Source') . ''; @@ -1441,12 +1449,12 @@ if ($action == 'create') $form->selectAvailabilityDelay('', 'availability_id', '', 1); print '
    ' . $langs->trans('SendingMethod') . ''; - print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); - print '
    ' . $langs->trans('SendingMethod') . ''; + print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); + print '
    ' . $langs->trans("DeliveryDate") . '
    '; - print $form->select_incoterms((!empty($soc->fk_incoterms) ? $soc->fk_incoterms : ''), (!empty($soc->location_incoterms)?$soc->location_incoterms:'')); + print ''; + print $form->select_incoterms((!empty($soc->fk_incoterms) ? $soc->fk_incoterms : ''), (!empty($soc->location_incoterms)?$soc->location_incoterms:'')); print '
    '.fieldLabel('Currency','multicurrency_code').''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code', 0); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code', 0); print '
    ' . $langs->trans('NotePrivate') . ''; - $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null)); + $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null)); $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); // print ' @@ -1527,13 +1535,7 @@ if ($action == 'create') } // Other attributes - $parameters = array(); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) { - print $object->showOptionals($extrafields, 'edit'); - } - + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; // Lines from source if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) @@ -1590,7 +1592,7 @@ if ($action == 'create') if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) { - print '
    '; + print '
    '; // For backward compatibility print ''; @@ -1685,6 +1687,26 @@ if ($action == 'create') $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ClonePropal'), $langs->trans('ConfirmClonePropal', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } + if ($action == 'statut') + { + //Form to close proposal (signed or not) + $formquestion = array( + array('type' => 'select','name' => 'statut','label' => $langs->trans("CloseAs"),'values' => array(2=>$object->labelstatut [2],3=>$object->labelstatut [3])), + array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"),'value' => '') // Field to complete private note (not replace) + ); + + if (! empty($conf->notification->enabled)) { + require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; + $notify = new Notify($db); + $formquestion = array_merge($formquestion, array( + array('type' => 'onecolumn', 'value' => $notify->confirmMessage('PROPAL_CLOSE_SIGNED', $object->socid, $object)), + )); + } + + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('SetAcceptedRefused'), $text, 'setstatut', $formquestion, '', 1, 250); + + } + // Confirm delete else if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteProp'), $langs->trans('ConfirmDeleteProp', $object->ref), 'confirm_delete', '', 0, 1); @@ -1748,50 +1770,50 @@ if ($action == 'create') // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherProposals").')'; - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->propal->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - } - $morehtmlref.=''; + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->propal->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.=''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; print '
    '; @@ -1924,24 +1946,24 @@ if ($action == 'create') print ''; print ''; - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + print ''; + } // Origin of demand print ''; - print ''; + // Bank Account + print ''; + print ''; } // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; - print ''; + print ''; + print ''; } // Other attributes @@ -2088,25 +2110,25 @@ if ($action == 'create') print '
    '; print '
    '; - print '
    '; - print ''; - if ($action != 'editshippingmethod' && $user->rights->propal->creer) - print ''; - print '
    '; - print $langs->trans('SendingMethod'); - print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
    '; - print '
    '; - if ($action == 'editshippingmethod') { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); - } else { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); - } - print '
    '; + print ''; + if ($action != 'editshippingmethod' && $user->rights->propal->creer) + print ''; + print '
    '; + print $langs->trans('SendingMethod'); + print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
    '; + print '
    '; + if ($action == 'editshippingmethod') { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); + } else { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); + } + print '
    '; @@ -2037,36 +2059,36 @@ if ($action == 'create') if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { - // Bank Account - print '
    '; - print ''; - if ($action != 'editbankaccount' && $user->rights->propal->creer) - print ''; - print '
    '; - print $langs->trans('BankAccount'); - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; - print '
    '; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print '
    '; + print ''; + if ($action != 'editbankaccount' && $user->rights->propal->creer) + print ''; + print '
    '; + print $langs->trans('BankAccount'); + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; + print '
    '; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print '
    '; - print '
    '; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->propal->creer) print ''.img_edit().''; - else print ' '; - print '
    '; - print '
    '; + print '
    '; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->propal->creer) print ''.img_edit().''; + else print ' '; + print '
    '; + print '
    '; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2075,7 +2097,7 @@ if ($action == 'create') { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print '
    '; + print '
    '; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) - { - // Multicurrency Amount HT - print ''; - print ''; - print ''; + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) + { + // Multicurrency Amount HT + print ''; + print ''; + print ''; - // Multicurrency Amount VAT - print ''; - print ''; - print ''; + // Multicurrency Amount VAT + print ''; + print ''; + print ''; - // Multicurrency Amount TTC - print ''; - print ''; - print ''; - } + // Multicurrency Amount TTC + print ''; + print ''; + print ''; + } // Amount HT print ''; @@ -2121,15 +2143,15 @@ if ($action == 'create') // Amount Local Taxes if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } // Amount TTC @@ -2145,7 +2167,7 @@ if ($action == 'create') // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } print ''; @@ -2184,7 +2206,7 @@ if ($action == 'create') include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
    '; + print '
    '; print '
    ' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . $langs->trans('AmountHT') . '
    ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '
    '; if (! empty($object->lines)) @@ -2206,41 +2228,12 @@ if ($action == 'create') } print '
    '; - print ''; + print ''; print "\n"; dol_fiche_end(); - if ($action == 'statut') - { - /* - * Form to close proposal (signed or not) - */ - $form_close = '
    '; - $form_close .= ''; - $form_close .= ''; - $form_close .= ''; - $form_close .= ''; - $form_close .= ''; - $form_close .= '
    ' . $langs->trans("CloseAs") . ''; - $form_close .= ''; - $form_close .= ''; - $form_close .= '
    ' . $langs->trans('Note') . '
    '; - $form_close .= ''; - $form_close .= '   '; - $form_close .= ' '; - $form_close .= '
    '; - - print $form_close; - } - /* * Boutons Actions */ @@ -2249,20 +2242,20 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { - if ($action != 'statut' && $action != 'editline') + if ($action != 'editline') { // Validate if ($object->statut == Propal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) - { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) + { print ''; - } - else + } + else print ''; } // Create event @@ -2296,6 +2289,14 @@ if ($action == 'create') } } + // Create an intervention + if (! empty($conf->service->enabled) && ! empty($conf->ficheinter->enabled) && $object->statut == Propal::STATUS_SIGNED) { + if ($user->rights->ficheinter->creer) { + $langs->load("interventions"); + print ''; + } + } + // Create contract if ($conf->contrat->enabled && $object->statut == Propal::STATUS_SIGNED) { $langs->load("contracts"); @@ -2366,134 +2367,39 @@ if ($action == 'create') $linktoelem = $form->showLinkToObjectBlock($object, null, array('propal')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show online signature link + $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok + + if ($object->statut != Propal::STATUS_DRAFT && $useonlinesignature) + { + print '
    '; + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + print showOnlineSignatureUrl('proposal', $object->ref).'
    '; + } + + if ($object->statut != Propal::STATUS_DRAFT && ! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) + { + print '
    '."\n"; + print showDirectDownloadLink($object).'
    '; + } 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, 'propal', $socid); + $somethingshown = $formactions->showactions($object, 'propal', $socid, 1); print '
    '; } - /* - * Action presend - */ - if ($action == 'presend') - { - $object->fetch_projet(); + // Presend form + $modelmail='propal_send'; + $defaulttopic='SendPropalRef'; + $diroutput = $conf->propal->dir_output; + $trackid = 'pro'.$object->id; - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($conf->propal->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - - if (!empty($newlang)) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($newlang); - $outputlangs->load('commercial'); - } - - // Build document if it not exists - if (! $file || ! is_readable($file)) { - $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) { - dol_print_error($db, $object->error, $object->errors); - exit(); - } - $fileparams = dol_most_recent_file($conf->propal->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - } - - print '
    '; - print '
    '; - print '
    '; - print load_fiche_titre($langs->trans('SendPropalByMail')); - - dol_fiche_head(''); - - // Create form object - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - $formmail->trackid='pro'.$object->id; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'pro'.$object->id); - } - $formmail->withfrom = 1; - $liste = array(); - foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) - $liste [$key] = $value; - $formmail->withto = GETPOST("sendto") ? GETPOST("sendto") : $liste; - $formmail->withtocc = $liste; - $formmail->withtoccc = (! empty($conf->global->MAIN_EMAIL_USECCC) ? $conf->global->MAIN_EMAIL_USECCC : false); - if (empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->trans('SendPropalRef', '__PROPREF__'); - } else if (! empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->trans('SendPropalRef', '__PROPREF__ (__REFCLIENT__)'); - } - $formmail->withfile = 2; - $formmail->withbody = 1; - $formmail->withdeliveryreceipt = 1; - $formmail->withcancel = 1; - - // Tableau des substitutions - $formmail->setSubstitFromObject($object); - $formmail->substit['__PROPREF__'] = $object->ref; // For backward compatibility - - // Find the good contact adress - $custcontact = ''; - $contactarr = array(); - $contactarr = $object->liste_contact(- 1, 'external'); - - if (is_array($contactarr) && count($contactarr) > 0) { - foreach ($contactarr as $contact) { - if ($contact ['libelle'] == $langs->trans('TypeContact_propal_external_CUSTOMER')) { // TODO Use code and not label - $contactstatic = new Contact($db); - $contactstatic->fetch($contact ['id']); - $custcontact = $contactstatic->getFullName($langs, 1); - } - } - - if (! empty($custcontact)) { - $formmail->substit['__CONTACTCIVNAME__'] = $custcontact; - } - } - - // Tableau des parametres complementaires - $formmail->param['action'] = 'send'; - $formmail->param['models'] = 'propal_send'; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['id'] = $object->id; - $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; - // Init list of files - if (GETPOST("mode") == 'init') { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file, basename($file), dol_mimetype($file)); - } - - print $formmail->get_form(); - - dol_fiche_end(); - } + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } // End of page diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 2c3afba030f..364f63bd4e4 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -30,225 +30,225 @@ require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; class Proposals extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'socid' - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid' + ); - /** - * @var propal $propal {@type propal} - */ - public $propal; + /** + * @var propal $propal {@type propal} + */ + public $propal; - /** - * Constructor - */ - function __construct() - { + /** + * Constructor + */ + function __construct() + { global $db, $conf; $this->db = $db; - $this->propal = new Propal($this->db); - } + $this->propal = new Propal($this->db); + } - /** - * Get properties of a commercial proposal object - * - * Return an array with commercial proposal informations - * - * @param int $id ID of commercial proposal - * @return array|mixed data without useless information + /** + * Get properties of a commercial proposal object * - * @throws RestException - */ - function get($id) - { + * Return an array with commercial proposal informations + * + * @param int $id ID of commercial proposal + * @return array|mixed data without useless information + * + * @throws RestException + */ + function get($id) + { if(! DolibarrApiAccess::$user->rights->propal->lire) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Commercial Proposal not found'); + } if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $this->propal->fetchObjectLinked(); + $this->propal->fetchObjectLinked(); return $this->_cleanObjectDatas($this->propal); - } + } - /** - * List commercial proposals - * - * Get a list of commercial proposals - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $thirdparty_ids Thirdparty ids to filter commercial proposal of. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')" - * @return array Array of order objects - */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { - global $db, $conf; + /** + * List commercial proposals + * + * Get a list of commercial proposals + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $thirdparty_ids Thirdparty ids to filter commercial proposal of. Example: '1' or '1,2,3' {@pattern /^2|3$/i} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')" + * @return array Array of order objects + */ + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - // case of external user, $thirdparty_ids param is ignored and replaced by user's socid - $socids = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $thirdparty_ids; + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $thirdparty_ids; - // If the internal user must only see his customers, force searching by him - $search_sale = 0; - if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + // If the internal user must only see his customers, force searching by him + $search_sale = 0; + if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; - $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - $sql.= " FROM ".MAIN_DB_PREFIX."propal as t"; + $sql = "SELECT t.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + $sql.= " FROM ".MAIN_DB_PREFIX."propal as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale - $sql.= ' WHERE t.entity IN ('.getEntity('propal').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - // Insert sale filter - if ($search_sale > 0) - { - $sql .= " AND sc.fk_user = ".$search_sale; - } - // Add sql filters - if ($sqlfilters) - { - if (! DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + $sql.= ' WHERE t.entity IN ('.getEntity('propal').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc"; + if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")"; + if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + // Insert sale filter + if ($search_sale > 0) + { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $sql.= $db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) - { - $page = 0; - } - $offset = $limit * $page; + $sql.= $db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; - $sql.= $db->plimit($limit + 1, $offset); - } + $sql.= $db->plimit($limit + 1, $offset); + } - $result = $db->query($sql); + $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { - $obj = $db->fetch_object($result); - $propal_static = new Propal($db); - if($propal_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($propal_static); - } - $i++; - } - } - else { - throw new RestException(503, 'Error when retrieve propal list : '.$db->lasterror()); - } - if( ! count($obj_ret)) { - throw new RestException(404, 'No order found'); - } + if ($result) + { + $num = $db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $db->fetch_object($result); + $propal_static = new Propal($db); + if($propal_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($propal_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve propal list : '.$db->lasterror()); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No order found'); + } return $obj_ret; - } + } - /** - * Create commercial proposal object - * - * @param array $request_data Request data - * @return int ID of propal - */ - function post($request_data = NULL) - { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + /** + * Create commercial proposal object + * + * @param array $request_data Request data + * @return int ID of propal + */ + function post($request_data = NULL) + { + if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401, "Insuffisant rights"); } - // Check mandatory fields - $result = $this->_validate($request_data); + // Check mandatory fields + $result = $this->_validate($request_data); - foreach($request_data as $field => $value) { - $this->propal->$field = $value; - } - /*if (isset($request_data["lines"])) { + foreach($request_data as $field => $value) { + $this->propal->$field = $value; + } + /*if (isset($request_data["lines"])) { $lines = array(); foreach ($request_data["lines"] as $line) { array_push($lines, (object) $line); } $this->propal->lines = $lines; }*/ - if ($this->propal->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating order", array_merge(array($this->propal->error), $this->propal->errors)); - } + if ($this->propal->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating order", array_merge(array($this->propal->error), $this->propal->errors)); + } - return $this->propal->id; - } + return $this->propal->id; + } - /** - * Get lines of a commercial proposal - * - * @param int $id Id of commercial proposal - * - * @url GET {id}/lines - * - * @return int - */ - function getLines($id) { - if(! DolibarrApiAccess::$user->rights->propal->lire) { + /** + * Get lines of a commercial proposal + * + * @param int $id Id of commercial proposal + * + * @url GET {id}/lines + * + * @return int + */ + function getLines($id) { + if(! DolibarrApiAccess::$user->rights->propal->lire) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Commercial Proposal not found'); + } if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->propal->getLinesArray(); - $result = array(); - foreach ($this->propal->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } + } + $this->propal->getLinesArray(); + $result = array(); + foreach ($this->propal->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } - /** - * Add a line to given commercial proposal - * - * @param int $id Id of commercial proposal to update - * @param array $request_data Commercial proposal line data - * - * @url POST {id}/lines - * - * @return int - */ - function postLine($id, $request_data = NULL) - { + /** + * Add a line to given commercial proposal + * + * @param int $id Id of commercial proposal to update + * @param array $request_data Commercial proposal line data + * + * @url POST {id}/lines + * + * @return int + */ + function postLine($id, $request_data = NULL) + { if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if (! $result) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $result = $this->propal->fetch($id); + if (! $result) { + throw new RestException(404, 'Commercial Proposal not found'); + } if (! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { @@ -288,257 +288,304 @@ class Proposals extends DolibarrApi if ($updateRes > 0) { return $updateRes; + } - } - return false; - } + return false; + } - /** - * Update a line of given commercial proposal - * - * @param int $id Id of commercial proposal to update - * @param int $lineid Id of line to update - * @param array $request_data Commercial proposal line data - * - * @url PUT {id}/lines/{lineid} - * - * @return object - */ - function putLine($id, $lineid, $request_data = NULL) - { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + /** + * Update a line of given commercial proposal + * + * @param int $id Id of commercial proposal to update + * @param int $lineid Id of line to update + * @param array $request_data Commercial proposal line data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + */ + function putLine($id, $lineid, $request_data = NULL) + { + if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if($result <= 0) { - throw new RestException(404, 'Proposal not found'); - } + $result = $this->propal->fetch($id); + if($result <= 0) { + throw new RestException(404, 'Proposal not found'); + } if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + } - $request_data = (object) $request_data; + $request_data = (object) $request_data; - $propalline = new PropaleLigne($this->db); - $result = $propalline->fetch($lineid); - if ($result <= 0) { - throw new RestException(404, 'Proposal line not found'); - } + $propalline = new PropaleLigne($this->db); + $result = $propalline->fetch($lineid); + if ($result <= 0) { + throw new RestException(404, 'Proposal line not found'); + } - $updateRes = $this->propal->updateline( - $lineid, - isset($request_data->subprice)?$request_data->subprice:$propalline->subprice, - isset($request_data->qty)?$request_data->qty:$propalline->qty, - isset($request_data->remise_percent)?$request_data->remise_percent:$propalline->remise_percent, - isset($request_data->tva_tx)?$request_data->tva_tx:$propalline->tva_tx, - isset($request_data->localtax1_tx)?$request_data->localtax1_tx:$propalline->localtax1_tx, - isset($request_data->localtax2_tx)?$request_data->localtax2_tx:$propalline->localtax2_tx, - isset($request_data->desc)?$request_data->desc:$propalline->desc, - 'HT', - isset($request_data->info_bits)?$request_data->info_bits:$propalline->info_bits, - isset($request_data->special_code)?$request_data->special_code:$propalline->special_code, - isset($request_data->fk_parent_line)?$request_data->fk_parent_line:$propalline->fk_parent_line, - 0, - isset($request_data->fk_fournprice)?$request_data->fk_fournprice:$propalline->fk_fournprice, - isset($request_data->pa_ht)?$request_data->pa_ht:$propalline->pa_ht, - isset($request_data->label)?$request_data->label:$propalline->label, - isset($request_data->product_type)?$request_data->product_type:$propalline->product_type, - isset($request_data->date_start)?$request_data->date_start:$propalline->date_start, - isset($request_data->date_end)?$request_data->date_end:$propalline->date_end, - isset($request_data->array_options)?$request_data->array_options:$propalline->array_options, - isset($request_data->fk_unit)?$request_data->fk_unit:$propalline->fk_unit, - isset($request_data->multicurrency_subprice)?$request_data->multicurrency_subprice:$propalline->subprice - ); + $updateRes = $this->propal->updateline( + $lineid, + isset($request_data->subprice)?$request_data->subprice:$propalline->subprice, + isset($request_data->qty)?$request_data->qty:$propalline->qty, + isset($request_data->remise_percent)?$request_data->remise_percent:$propalline->remise_percent, + isset($request_data->tva_tx)?$request_data->tva_tx:$propalline->tva_tx, + isset($request_data->localtax1_tx)?$request_data->localtax1_tx:$propalline->localtax1_tx, + isset($request_data->localtax2_tx)?$request_data->localtax2_tx:$propalline->localtax2_tx, + isset($request_data->desc)?$request_data->desc:$propalline->desc, + 'HT', + isset($request_data->info_bits)?$request_data->info_bits:$propalline->info_bits, + isset($request_data->special_code)?$request_data->special_code:$propalline->special_code, + isset($request_data->fk_parent_line)?$request_data->fk_parent_line:$propalline->fk_parent_line, + 0, + isset($request_data->fk_fournprice)?$request_data->fk_fournprice:$propalline->fk_fournprice, + isset($request_data->pa_ht)?$request_data->pa_ht:$propalline->pa_ht, + isset($request_data->label)?$request_data->label:$propalline->label, + isset($request_data->product_type)?$request_data->product_type:$propalline->product_type, + isset($request_data->date_start)?$request_data->date_start:$propalline->date_start, + isset($request_data->date_end)?$request_data->date_end:$propalline->date_end, + isset($request_data->array_options)?$request_data->array_options:$propalline->array_options, + isset($request_data->fk_unit)?$request_data->fk_unit:$propalline->fk_unit, + isset($request_data->multicurrency_subprice)?$request_data->multicurrency_subprice:$propalline->subprice + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; - } + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + } - /** - * Delete a line of given commercial proposal - * - * - * @param int $id Id of commercial proposal to update - * @param int $lineid Id of line to delete - * - * @url DELETE {id}/lines/{lineid} - * - * @return int - */ - function delLine($id, $lineid) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + /** + * Delete a line of given commercial proposal + * + * + * @param int $id Id of commercial proposal to update + * @param int $lineid Id of line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return int + * @throws 401 + * @throws 404 + */ + function deleteLine($id, $lineid) { + if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Proposal not found'); - } + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Proposal not found'); + } if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->propal->deleteline($lineid); - if ($updateRes == 1) { - return $this->get($id); - } - return false; - } + } - /** - * Update commercial proposal general fields (won't touch lines of commercial proposal) - * - * @param int $id Id of commercial proposal to update - * @param array $request_data Datas - * - * @return int - */ - function put($id, $request_data = NULL) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + $request_data = (object) $request_data; + $updateRes = $this->propal->deleteline($lineid); + if ($updateRes > 0) { + return $this->get($id); + } + return false; + } + + /** + * Update commercial proposal general fields (won't touch lines of commercial proposal) + * + * @param int $id Id of commercial proposal to update + * @param array $request_data Datas + * + * @return int + */ + function put($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Proposal not found'); - } + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Proposal not found'); + } if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - foreach($request_data as $field => $value) { - if ($field == 'id') continue; - $this->propal->$field = $value; - } + foreach($request_data as $field => $value) { + if ($field == 'id') continue; + $this->propal->$field = $value; + } - if($this->propal->update($id, DolibarrApiAccess::$user,1,'','','update')) - return $this->get($id); + if($this->propal->update($id, DolibarrApiAccess::$user,1,'','','update')) + return $this->get($id); - return false; - } + return false; + } - /** - * Delete commercial proposal - * - * @param int $id Commercial proposal ID - * - * @return array - */ - function delete($id) - { - if(! DolibarrApiAccess::$user->rights->propal->supprimer) { + /** + * Delete commercial proposal + * + * @param int $id Commercial proposal ID + * + * @return array + */ + function delete($id) + { + if(! DolibarrApiAccess::$user->rights->propal->supprimer) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Commercial Proposal not found'); + } if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if( ! $this->propal->delete(DolibarrApiAccess::$user)) { - throw new RestException(500, 'Error when delete Commercial Proposal : '.$this->propal->error); - } + if( ! $this->propal->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete Commercial Proposal : '.$this->propal->error); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Commercial Proposal deleted' - ) - ); + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal deleted' + ) + ); - } + } - /** - * Validate a commercial proposal - * - * @param int $id Commercial proposal ID - * @param int $notrigger Use {} - * - * @url POST {id}/validate - * - * @return array - * FIXME An error 403 is returned if the request has an empty body. - * Error message: "Forbidden: Content type `text/plain` is not supported." - * Workaround: send this in the body - * { - * "notrigger": 0 - * } - */ - function validate($id, $notrigger=0) - { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + /** + * Validate a commercial proposal + * + * @param int $id Commercial proposal ID + * @param int $notrigger Use {} + * + * @url POST {id}/validate + * + * @return array + * FIXME An error 403 is returned if the request has an empty body. + * Error message: "Forbidden: Content type `text/plain` is not supported." + * Workaround: send this in the body + * { + * "notrigger": 0 + * } + */ + function validate($id, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Commercial Proposal not found'); + } if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $result = $this->propal->valid(DolibarrApiAccess::$user, $notrigger); - if ($result == 0) { - throw new RestException(500, 'Error nothing done. May be object is already validated'); - } - if ($result < 0) { - throw new RestException(500, 'Error when validating Commercial Proposal: '.$this->propal->error); - } + $result = $this->propal->valid(DolibarrApiAccess::$user, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error when validating Commercial Proposal: '.$this->propal->error); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Commercial Proposal validated (Ref='.$this->propal->ref.')' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal validated (Ref='.$this->propal->ref.')' + ) + ); + } - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - function _validate($data) - { - $propal = array(); - foreach (Proposals::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $propal[$field] = $data[$field]; + /** + * Close (Accept or refuse) a quote / commercial proposal + * + * @param int $id Commercial proposal ID + * @param int $status Must be 2 (accepted) or 3 (refused) {@min 2}{@max 3} + * @param string $note_private Add this mention at end of private note + * @param int $notrigger Disabled triggers + * + * @url POST {id}/close + * + * @return array + */ + function close($id, $status, $note_private='', $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Commercial Proposal not found'); + } - } - return $propal; - } + if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - /** - * Clean sensible object datas - * - * @param object $object Object to clean - * @return array Array of cleaned object properties - */ - function _cleanObjectDatas($object) { + $result = $this->propal->cloture(DolibarrApiAccess::$user, $status, $note_private, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already closed'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Commercial Proposal: '.$this->propal->error); + } - $object = parent::_cleanObjectDatas($object); + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal closed (Ref='.$this->propal->ref.')' + ) + ); + } - unset($object->name); - unset($object->lastname); - unset($object->firstname); - unset($object->civility_id); - unset($object->address); - return $object; - } + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + function _validate($data) + { + $propal = array(); + foreach (Proposals::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $propal[$field] = $data[$field]; + + } + return $propal; + } + + + /** + * 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->name); + unset($object->lastname); + unset($object->firstname); + unset($object->civility_id); + unset($object->address); + + return $object; + } } diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 25d488e7316..54ff5e1afc0 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -44,40 +44,40 @@ require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php'; */ class Propal extends CommonObject { - public $element='propal'; - public $table_element='propal'; - public $table_element_line='propaldet'; - public $fk_element='fk_propal'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - public $picto='propal'; + public $element='propal'; + public $table_element='propal'; + public $table_element_line='propaldet'; + public $fk_element='fk_propal'; + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $picto='propal'; - /** - * {@inheritdoc} - */ - protected $table_ref_field = 'ref'; + /** + * {@inheritdoc} + */ + protected $table_ref_field = 'ref'; /** * ID of the client * @var int */ - public $socid; + public $socid; - public $contactid; - public $author; - public $ref_client; + public $contactid; + public $author; + public $ref_client; /** * Status of the quote * @var int * @see Propal::STATUS_DRAFT, Propal::STATUS_VALIDATED, Propal::STATUS_SIGNED, Propal::STATUS_NOTSIGNED, Propal::STATUS_BILLED */ - public $statut; + public $statut; /** * @deprecated * @see date_creation */ - public $datec; + public $datec; /** * Creation date @@ -89,7 +89,7 @@ class Propal extends CommonObject * @deprecated * @see date_validation */ - public $datev; + public $datev; /** * Validation date @@ -101,62 +101,62 @@ class Propal extends CommonObject * Date of the quote * @var */ - public $date; + public $date; /** * @deprecated * @see date */ - public $datep; - public $date_livraison; - public $fin_validite; + public $datep; + public $date_livraison; + public $fin_validite; - public $user_author_id; - public $user_valid_id; - public $user_close_id; + public $user_author_id; + public $user_valid_id; + public $user_close_id; /** * @deprecated * @see total_ht */ - public $price; + public $price; /** * @deprecated * @see total_tva */ - public $tva; + public $tva; /** * @deprecated * @see total_ttc */ - public $total; + public $total; - public $cond_reglement_code; - public $mode_reglement_code; - public $remise; - public $remise_percent; - public $remise_absolue; - public $fk_address; - public $address_type; - public $address; - public $availability_id; - public $availability_code; - public $demand_reason_id; - public $demand_reason_code; + public $cond_reglement_code; + public $mode_reglement_code; + public $remise; + public $remise_percent; + public $remise_absolue; + public $fk_address; + public $address_type; + public $address; + public $availability_id; + public $availability_code; + public $demand_reason_id; + public $demand_reason_code; - public $products=array(); - public $extraparams=array(); + public $products=array(); + public $extraparams=array(); /** * @var PropaleLigne[] */ - public $lines = array(); - public $line; + public $lines = array(); + public $line; - public $labelstatut=array(); - public $labelstatut_short=array(); + public $labelstatut=array(); + public $labelstatut_short=array(); - public $specimen; + public $specimen; // Multicurrency public $fk_multicurrency; @@ -189,256 +189,256 @@ class Propal extends CommonObject */ const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ? - /** - * Constructor - * - * @param DoliDB $db Database handler - * @param int $socid Id third party - * @param int $propalid Id proposal - */ - function __construct($db, $socid="", $propalid=0) - { - global $conf,$langs; + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param int $socid Id third party + * @param int $propalid Id proposal + */ + function __construct($db, $socid="", $propalid=0) + { + global $conf,$langs; - $this->db = $db; - $this->socid = $socid; - $this->id = $propalid; - $this->products = array(); - $this->remise = 0; - $this->remise_percent = 0; - $this->remise_absolue = 0; + $this->db = $db; + $this->socid = $socid; + $this->id = $propalid; + $this->products = array(); + $this->remise = 0; + $this->remise_percent = 0; + $this->remise_absolue = 0; - $this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION; + $this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION; - $langs->load("propal"); - $this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft")); - $this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated")); - $this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned")); - $this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned")); - $this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled")); - $this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort")); - $this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened")); - $this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort")); - $this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort")); - $this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort")); - } + $langs->load("propal"); + $this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft")); + $this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated")); + $this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned")); + $this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned")); + $this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled")); + $this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort")); + $this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened")); + $this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort")); + $this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort")); + $this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort")); + } - /** - * Add line into array products - * $this->thirdparty should be loaded - * - * @param int $idproduct Product Id to add - * @param int $qty Quantity - * @param int $remise_percent Discount effected on Product - * @return int <0 if KO, >0 if OK - * - * TODO Replace calls to this function by generation objet Ligne - * inserted into table $this->products - */ - function add_product($idproduct, $qty, $remise_percent=0) - { - global $conf, $mysoc; + /** + * Add line into array products + * $this->thirdparty should be loaded + * + * @param int $idproduct Product Id to add + * @param int $qty Quantity + * @param int $remise_percent Discount effected on Product + * @return int <0 if KO, >0 if OK + * + * TODO Replace calls to this function by generation objet Ligne + * inserted into table $this->products + */ + function add_product($idproduct, $qty, $remise_percent=0) + { + global $conf, $mysoc; - if (! $qty) $qty = 1; + if (! $qty) $qty = 1; - dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent"); - if ($idproduct > 0) - { - $prod=new Product($this->db); - $prod->fetch($idproduct); + dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent"); + if ($idproduct > 0) + { + $prod=new Product($this->db); + $prod->fetch($idproduct); - $productdesc = $prod->description; + $productdesc = $prod->description; - $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id); - $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id); - if (empty($tva_tx)) $tva_npr=0; - $vat_src_code = ''; // May be defined into tva_tx + $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id); + $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id); + if (empty($tva_tx)) $tva_npr=0; + $vat_src_code = ''; // May be defined into tva_tx - $localtax1_tx = get_localtax($tva_tx,1,$mysoc,$this->thirdparty,$tva_npr); - $localtax2_tx = get_localtax($tva_tx,2,$mysoc,$this->thirdparty,$tva_npr); + $localtax1_tx = get_localtax($tva_tx,1,$mysoc,$this->thirdparty,$tva_npr); + $localtax2_tx = get_localtax($tva_tx,2,$mysoc,$this->thirdparty,$tva_npr); - // multiprices - if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) - { - $price = $prod->multiprices[$this->thirdparty->price_level]; - } - else - { - $price = $prod->price; - } + // multiprices + if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) + { + $price = $prod->multiprices[$this->thirdparty->price_level]; + } + else + { + $price = $prod->price; + } - $line = new PropaleLigne($this->db); + $line = new PropaleLigne($this->db); - $line->fk_product=$idproduct; - $line->desc=$productdesc; - $line->qty=$qty; - $line->subprice=$price; - $line->remise_percent=$remise_percent; - $line->vat_src_code=$vat_src_code; - $line->tva_tx=$tva_tx; - $line->fk_unit=$prod->fk_unit; + $line->fk_product=$idproduct; + $line->desc=$productdesc; + $line->qty=$qty; + $line->subprice=$price; + $line->remise_percent=$remise_percent; + $line->vat_src_code=$vat_src_code; + $line->tva_tx=$tva_tx; + $line->fk_unit=$prod->fk_unit; if ($tva_npr) $line->info_bits = 1; - $this->lines[]=$line; - } - } + $this->lines[]=$line; + } + } - /** - * Adding line of fixed discount in the proposal in DB - * - * @param int $idremise Id of fixed discount - * @return int >0 if OK, <0 if KO - */ - function insert_discount($idremise) - { - global $langs; + /** + * Adding line of fixed discount in the proposal in DB + * + * @param int $idremise Id of fixed discount + * @return int >0 if OK, <0 if KO + */ + function insert_discount($idremise) + { + global $langs; - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - $this->db->begin(); + $this->db->begin(); - $remise=new DiscountAbsolute($this->db); - $result=$remise->fetch($idremise); + $remise=new DiscountAbsolute($this->db); + $result=$remise->fetch($idremise); - if ($result > 0) - { - if ($remise->fk_facture) // Protection against multiple submission - { - $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); - $this->db->rollback(); - return -5; - } + if ($result > 0) + { + if ($remise->fk_facture) // Protection against multiple submission + { + $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); + $this->db->rollback(); + return -5; + } - $line=new PropaleLigne($this->db); + $line=new PropaleLigne($this->db); - $this->line->context = $this->context; + $this->line->context = $this->context; - $line->fk_propal=$this->id; - $line->fk_remise_except=$remise->id; - $line->desc=$remise->description; // Description ligne - $line->vat_src_code=$remise->vat_src_code; - $line->tva_tx=$remise->tva_tx; - $line->subprice=-$remise->amount_ht; - $line->fk_product=0; // Id produit predefined - $line->qty=1; - $line->remise=0; - $line->remise_percent=0; - $line->rang=-1; - $line->info_bits=2; + $line->fk_propal=$this->id; + $line->fk_remise_except=$remise->id; + $line->desc=$remise->description; // Description ligne + $line->vat_src_code=$remise->vat_src_code; + $line->tva_tx=$remise->tva_tx; + $line->subprice=-$remise->amount_ht; + $line->fk_product=0; // Id produit predefined + $line->qty=1; + $line->remise=0; + $line->remise_percent=0; + $line->rang=-1; + $line->info_bits=2; - // TODO deprecated - $line->price=-$remise->amount_ht; + // TODO deprecated + $line->price=-$remise->amount_ht; - $line->total_ht = -$remise->amount_ht; - $line->total_tva = -$remise->amount_tva; - $line->total_ttc = -$remise->amount_ttc; + $line->total_ht = -$remise->amount_ht; + $line->total_tva = -$remise->amount_tva; + $line->total_ttc = -$remise->amount_ttc; - $result=$line->insert(); - if ($result > 0) - { - $result=$this->update_price(1); - if ($result > 0) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } - else - { - $this->error=$line->error; - $this->db->rollback(); - return -2; - } - } - else - { - $this->db->rollback(); - return -2; - } - } + $result=$line->insert(); + if ($result > 0) + { + $result=$this->update_price(1); + if ($result > 0) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } + else + { + $this->error=$line->error; + $this->db->rollback(); + return -2; + } + } + else + { + $this->db->rollback(); + return -2; + } + } - /** - * Add a proposal line into database (linked to product/service or not) - * The parameters are already supposed to be appropriate and with final values to the call - * of this method. Also, for the VAT rate, it must have already been defined - * by whose calling the method get_default_tva (societe_vendeuse, societe_acheteuse, '' product) - * and desc must already have the right value (it's up to the caller to manage multilanguage) - * - * @param string $desc Description de la ligne - * @param float $pu_ht Prix unitaire - * @param float $qty Quantite - * @param float $txtva Taux de tva - * @param float $txlocaltax1 Local tax 1 rate - * @param float $txlocaltax2 Local tax 2 rate - * @param int $fk_product Id du produit/service predefini - * @param float $remise_percent Pourcentage de remise de la ligne - * @param string $price_base_type HT or TTC - * @param float $pu_ttc Prix unitaire TTC - * @param int $info_bits Bits de type de lignes - * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used. - * @param int $rang Position of line - * @param int $special_code Special code (also used by externals modules!) - * @param int $fk_parent_line Id of parent line - * @param int $fk_fournprice Id supplier price - * @param int $pa_ht Buying price without tax - * @param string $label ??? - * @param int $date_start Start date of the line - * @param int $date_end End date of the line - * @param array $array_options extrafields array - * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param string $origin 'order', ... - * @param int $origin_id Id of origin object - * @param double $pu_ht_devise Unit price in currency - * @param int $fk_remise_except Id discount if line is from a discount - * @return int >0 if OK, <0 if KO - * @see add_product - */ + /** + * Add a proposal line into database (linked to product/service or not) + * The parameters are already supposed to be appropriate and with final values to the call + * of this method. Also, for the VAT rate, it must have already been defined + * by whose calling the method get_default_tva (societe_vendeuse, societe_acheteuse, '' product) + * and desc must already have the right value (it's up to the caller to manage multilanguage) + * + * @param string $desc Description de la ligne + * @param float $pu_ht Prix unitaire + * @param float $qty Quantite + * @param float $txtva Taux de tva + * @param float $txlocaltax1 Local tax 1 rate + * @param float $txlocaltax2 Local tax 2 rate + * @param int $fk_product Id du produit/service predefini + * @param float $remise_percent Pourcentage de remise de la ligne + * @param string $price_base_type HT or TTC + * @param float $pu_ttc Prix unitaire TTC + * @param int $info_bits Bits de type de lignes + * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used. + * @param int $rang Position of line + * @param int $special_code Special code (also used by externals modules!) + * @param int $fk_parent_line Id of parent line + * @param int $fk_fournprice Id supplier price + * @param int $pa_ht Buying price without tax + * @param string $label ??? + * @param int $date_start Start date of the line + * @param int $date_end End date of the line + * @param array $array_options extrafields array + * @param string $fk_unit Code of the unit to use. Null to use the default one + * @param string $origin 'order', ... + * @param int $origin_id Id of origin object + * @param double $pu_ht_devise Unit price in currency + * @param int $fk_remise_except Id discount if line is from a discount + * @return int >0 if OK, <0 if KO + * @see add_product + */ function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=0, $pa_ht=0, $label='',$date_start='', $date_end='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise=0, $fk_remise_except=0) - { - global $mysoc, $conf, $langs; + { + global $mysoc, $conf, $langs; - dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type, fk_remise_except=".$fk_remise_except); - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type, fk_remise_except=".$fk_remise_except); + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - // Clean parameters - if (empty($remise_percent)) $remise_percent=0; - if (empty($qty)) $qty=0; - if (empty($info_bits)) $info_bits=0; - if (empty($rang)) $rang=0; - if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0; + // Clean parameters + if (empty($remise_percent)) $remise_percent=0; + if (empty($qty)) $qty=0; + if (empty($info_bits)) $info_bits=0; + if (empty($rang)) $rang=0; + if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0; - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); - $pu_ht=price2num($pu_ht); - $pu_ttc=price2num($pu_ttc); - $txtva=price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); - $pa_ht=price2num($pa_ht); - if ($price_base_type=='HT') - { - $pu=$pu_ht; - } - else - { - $pu=$pu_ttc; - } + $remise_percent=price2num($remise_percent); + $qty=price2num($qty); + $pu_ht=price2num($pu_ht); + $pu_ttc=price2num($pu_ttc); + $txtva=price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' + $txlocaltax1=price2num($txlocaltax1); + $txlocaltax2=price2num($txlocaltax2); + $pa_ht=price2num($pa_ht); + if ($price_base_type=='HT') + { + $pu=$pu_ht; + } + else + { + $pu=$pu_ttc; + } - // Check parameters - if ($type < 0) return -1; + // Check parameters + if ($type < 0) return -1; - if ($this->statut == self::STATUS_DRAFT) - { - $this->db->begin(); + if ($this->statut == self::STATUS_DRAFT) + { + $this->db->begin(); - $product_type=$type; + $product_type=$type; if (!empty($fk_product)) { $product=new Product($this->db); @@ -446,128 +446,128 @@ class Propal extends CommonObject $product_type=$product->type; if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL) && $product_type == 0 && $product->stock_reel < $qty) { - $langs->load("errors"); - $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref); + $langs->load("errors"); + $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref); $this->db->rollback(); return -3; } } // Calcul du total TTC et de la TVA pour la ligne a partir de - // qty, pu, remise_percent et txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + // qty, pu, remise_percent et txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); - // Clean vat code - $vat_src_code=''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + // Clean vat code + $vat_src_code=''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } - $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; $pu_ht = $tabprice[3]; $pu_tva = $tabprice[4]; $pu_ttc = $tabprice[5]; // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - // Rang to use - $rangtouse = $rang; - if ($rangtouse == -1) - { - $rangmax = $this->line_max($fk_parent_line); - $rangtouse = $rangmax + 1; - } + // Rang to use + $rangtouse = $rang; + if ($rangtouse == -1) + { + $rangmax = $this->line_max($fk_parent_line); + $rangtouse = $rangmax + 1; + } - // TODO A virer - // Anciens indicateurs: $price, $remise (a ne plus utiliser) - $price = $pu; - $remise = 0; - if ($remise_percent > 0) - { - $remise = round(($pu * $remise_percent / 100), 2); - $price = $pu - $remise; - } + // TODO A virer + // Anciens indicateurs: $price, $remise (a ne plus utiliser) + $price = $pu; + $remise = 0; + if ($remise_percent > 0) + { + $remise = round(($pu * $remise_percent / 100), 2); + $price = $pu - $remise; + } - // Insert line - $this->line=new PropaleLigne($this->db); + // Insert line + $this->line=new PropaleLigne($this->db); - $this->line->context = $this->context; + $this->line->context = $this->context; - $this->line->fk_propal=$this->id; - $this->line->label=$label; - $this->line->desc=$desc; - $this->line->qty=$qty; + $this->line->fk_propal=$this->id; + $this->line->label=$label; + $this->line->desc=$desc; + $this->line->qty=$qty; $this->line->vat_src_code=$vat_src_code; - $this->line->tva_tx=$txtva; - $this->line->localtax1_tx=$txlocaltax1; - $this->line->localtax2_tx=$txlocaltax2; + $this->line->tva_tx=$txtva; + $this->line->localtax1_tx=$txlocaltax1; + $this->line->localtax2_tx=$txlocaltax2; $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->fk_product=$fk_product; - $this->line->product_type=$type; - $this->line->fk_remise_except=$fk_remise_except; - $this->line->remise_percent=$remise_percent; - $this->line->subprice=$pu_ht; - $this->line->rang=$rangtouse; - $this->line->info_bits=$info_bits; - $this->line->total_ht=$total_ht; - $this->line->total_tva=$total_tva; - $this->line->total_localtax1=$total_localtax1; - $this->line->total_localtax2=$total_localtax2; - $this->line->total_ttc=$total_ttc; - $this->line->special_code=$special_code; - $this->line->fk_parent_line=$fk_parent_line; - $this->line->fk_unit=$fk_unit; + $this->line->fk_product=$fk_product; + $this->line->product_type=$type; + $this->line->fk_remise_except=$fk_remise_except; + $this->line->remise_percent=$remise_percent; + $this->line->subprice=$pu_ht; + $this->line->rang=$rangtouse; + $this->line->info_bits=$info_bits; + $this->line->total_ht=$total_ht; + $this->line->total_tva=$total_tva; + $this->line->total_localtax1=$total_localtax1; + $this->line->total_localtax2=$total_localtax2; + $this->line->total_ttc=$total_ttc; + $this->line->special_code=$special_code; + $this->line->fk_parent_line=$fk_parent_line; + $this->line->fk_unit=$fk_unit; - $this->line->date_start=$date_start; - $this->line->date_end=$date_end; + $this->line->date_start=$date_start; + $this->line->date_end=$date_end; $this->line->fk_fournprice = $fk_fournprice; $this->line->pa_ht = $pa_ht; - $this->line->origin_id = $origin_id; - $this->line->origin = $origin; + $this->line->origin_id = $origin_id; + $this->line->origin = $origin; // Multicurrency $this->line->fk_multicurrency = $this->fk_multicurrency; $this->line->multicurrency_code = $this->multicurrency_code; $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - // Mise en option de la ligne - if (empty($qty) && empty($special_code)) $this->line->special_code=3; + // Mise en option de la ligne + if (empty($qty) && empty($special_code)) $this->line->special_code=3; - // TODO deprecated - $this->line->price=$price; - $this->line->remise=$remise; + // TODO deprecated + $this->line->price=$price; + $this->line->remise=$remise; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; - } + if (is_array($array_options) && count($array_options)>0) { + $this->line->array_options=$array_options; + } - $result=$this->line->insert(); - if ($result > 0) - { - // Reorder if child line - if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); + $result=$this->line->insert(); + if ($result > 0) + { + // Reorder if child line + if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); // Mise a jour informations denormalisees au niveau de la propale meme $result=$this->update_price(1,'auto',0,$mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. @@ -598,246 +598,247 @@ class Propal extends CommonObject } - /** - * Update a proposal line - * - * @param int $rowid Id de la ligne - * @param float $pu Prix unitaire (HT ou TTC selon price_base_type) - * @param float $qty Quantity - * @param float $remise_percent Remise effectuee sur le produit - * @param float $txtva Taux de TVA - * @param float $txlocaltax1 Local tax 1 rate - * @param float $txlocaltax2 Local tax 2 rate - * @param string $desc Description - * @param string $price_base_type HT ou TTC - * @param int $info_bits Miscellaneous informations - * @param int $special_code Special code (also used by externals modules!) - * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines). - * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules) - * @param int $fk_fournprice Id of origin supplier price - * @param int $pa_ht Price (without tax) of product when it was bought - * @param string $label ??? - * @param int $type 0/1=Product/service - * @param int $date_start Start date of the line - * @param int $date_end End date of the line + /** + * Update a proposal line + * + * @param int $rowid Id de la ligne + * @param float $pu Prix unitaire (HT ou TTC selon price_base_type) + * @param float $qty Quantity + * @param float $remise_percent Remise effectuee sur le produit + * @param float $txtva Taux de TVA + * @param float $txlocaltax1 Local tax 1 rate + * @param float $txlocaltax2 Local tax 2 rate + * @param string $desc Description + * @param string $price_base_type HT ou TTC + * @param int $info_bits Miscellaneous informations + * @param int $special_code Special code (also used by externals modules!) + * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines). + * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules) + * @param int $fk_fournprice Id of origin supplier price + * @param int $pa_ht Price (without tax) of product when it was bought + * @param string $label ??? + * @param int $type 0/1=Product/service + * @param int $date_start Start date of the line + * @param int $date_end End date of the line * @param array $array_options extrafields array - * @param string $fk_unit Code of the unit to use. Null to use the default one + * @param string $fk_unit Code of the unit to use. Null to use the default one * @param double $pu_ht_devise Unit price in currency * @param int $notrigger disable line update trigger - * @return int 0 if OK, <0 if KO - */ + * @return int 0 if OK, <0 if KO + */ function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $desc='', $price_base_type='HT', $info_bits=0, $special_code=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=0, $pa_ht=0, $label='', $type=0, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise = 0, $notrigger=0) - { - global $mysoc; + { + global $mysoc; - dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent, + dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, desc=$desc, price_base_type=$price_base_type, info_bits=$info_bits, special_code=$special_code, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, type=$type, date_start=$date_start, date_end=$date_end"); - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - // Clean parameters - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); - $pu = price2num($pu); - $txtva = price2num($txtva); - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); - $pa_ht=price2num($pa_ht); - if (empty($qty) && empty($special_code)) $special_code=3; // Set option tag - if (! empty($qty) && $special_code == 3) $special_code=0; // Remove option tag - if (empty($type)) $type=0; + // Clean parameters + $remise_percent=price2num($remise_percent); + $qty=price2num($qty); + $pu = price2num($pu); + $txtva = price2num($txtva); + $txlocaltax1=price2num($txlocaltax1); + $txlocaltax2=price2num($txlocaltax2); + $pa_ht=price2num($pa_ht); + if (empty($qty) && empty($special_code)) $special_code=3; // Set option tag + if (! empty($qty) && $special_code == 3) $special_code=0; // Remove option tag + if (empty($type)) $type=0; - if ($this->statut == self::STATUS_DRAFT) - { - $this->db->begin(); + if ($this->statut == self::STATUS_DRAFT) + { + $this->db->begin(); - // Calcul du total TTC et de la TVA pour la ligne a partir de - // qty, pu, remise_percent et txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + // Calcul du total TTC et de la TVA pour la ligne a partir de + // qty, pu, remise_percent et txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); - // Clean vat code - $vat_src_code=''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + // Clean vat code + $vat_src_code=''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } - $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; + $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; $pu_ht = $tabprice[3]; $pu_tva = $tabprice[4]; $pu_ttc = $tabprice[5]; // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - // Anciens indicateurs: $price, $remise (a ne plus utiliser) - $price = $pu; - if ($remise_percent > 0) - { - $remise = round(($pu * $remise_percent / 100), 2); - $price = $pu - $remise; - } + // Anciens indicateurs: $price, $remise (a ne plus utiliser) + $price = $pu; + if ($remise_percent > 0) + { + $remise = round(($pu * $remise_percent / 100), 2); + $price = $pu - $remise; + } - //Fetch current line from the database and then clone the object and set it in $oldline property - $line = new PropaleLigne($this->db); - $line->fetch($rowid); + //Fetch current line from the database and then clone the object and set it in $oldline property + $line = new PropaleLigne($this->db); + $line->fetch($rowid); $line->fetch_optionals(); // Fetch extrafields for oldcopy $staticline = clone $line; - $line->oldline = $staticline; - $this->line = $line; - $this->line->context = $this->context; + $line->oldline = $staticline; + $this->line = $line; + $this->line->context = $this->context; - // Reorder if fk_parent_line change - if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) - { - $rangmax = $this->line_max($fk_parent_line); - $this->line->rang = $rangmax + 1; - } + // Reorder if fk_parent_line change + if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) + { + $rangmax = $this->line_max($fk_parent_line); + $this->line->rang = $rangmax + 1; + } - $this->line->rowid = $rowid; - $this->line->label = $label; - $this->line->desc = $desc; - $this->line->qty = $qty; - $this->line->product_type = $type; - $this->line->vat_src_code = $vat_src_code; - $this->line->tva_tx = $txtva; - $this->line->localtax1_tx = $txlocaltax1; - $this->line->localtax2_tx = $txlocaltax2; + $this->line->rowid = $rowid; + $this->line->label = $label; + $this->line->desc = $desc; + $this->line->qty = $qty; + $this->line->product_type = $type; + $this->line->vat_src_code = $vat_src_code; + $this->line->tva_tx = $txtva; + $this->line->localtax1_tx = $txlocaltax1; + $this->line->localtax2_tx = $txlocaltax2; $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->remise_percent = $remise_percent; - $this->line->subprice = $pu_ht; - $this->line->info_bits = $info_bits; + $this->line->remise_percent = $remise_percent; + $this->line->subprice = $pu_ht; + $this->line->info_bits = $info_bits; - $this->line->total_ht = $total_ht; - $this->line->total_tva = $total_tva; - $this->line->total_localtax1 = $total_localtax1; - $this->line->total_localtax2 = $total_localtax2; - $this->line->total_ttc = $total_ttc; - $this->line->special_code = $special_code; - $this->line->fk_parent_line = $fk_parent_line; - $this->line->skip_update_total = $skip_update_total; - $this->line->fk_unit = $fk_unit; + $this->line->total_ht = $total_ht; + $this->line->total_tva = $total_tva; + $this->line->total_localtax1 = $total_localtax1; + $this->line->total_localtax2 = $total_localtax2; + $this->line->total_ttc = $total_ttc; + $this->line->special_code = $special_code; + $this->line->fk_parent_line = $fk_parent_line; + $this->line->skip_update_total = $skip_update_total; + $this->line->fk_unit = $fk_unit; $this->line->fk_fournprice = $fk_fournprice; - $this->line->pa_ht = $pa_ht; + $this->line->pa_ht = $pa_ht; - $this->line->date_start=$date_start; - $this->line->date_end=$date_end; + $this->line->date_start=$date_start; + $this->line->date_end=$date_end; - // TODO deprecated - $this->line->price=$price; - $this->line->remise=$remise; + // TODO deprecated + $this->line->price=$price; + $this->line->remise=$remise; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; - } + if (is_array($array_options) && count($array_options)>0) { + $this->line->array_options=$array_options; + } // Multicurrency $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - $result=$this->line->update($notrigger); - if ($result > 0) - { - // Reorder if child line - if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); + $result=$this->line->update($notrigger); + if ($result > 0) + { + // Reorder if child line + if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); - $this->update_price(1); + $this->update_price(1); - $this->fk_propal = $this->id; - $this->rowid = $rowid; + $this->fk_propal = $this->id; + $this->rowid = $rowid; - $this->db->commit(); - return $result; - } - else - { - $this->error=$this->line->error; + $this->db->commit(); + return $result; + } + else + { + $this->error=$this->line->error; - $this->db->rollback(); - return -1; - } - } - else - { - dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action"); - return -2; - } - } + $this->db->rollback(); + return -1; + } + } + else + { + dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action"); + return -2; + } + } - /** - * Delete detail line - * - * @param int $lineid Id of line to delete - * @return int >0 if OK, <0 if KO - */ - function deleteline($lineid) - { - if ($this->statut == self::STATUS_DRAFT) - { - $line=new PropaleLigne($this->db); + /** + * Delete detail line + * + * @param int $lineid Id of line to delete + * @return int >0 if OK, <0 if KO + */ + function deleteline($lineid) + { + if ($this->statut == self::STATUS_DRAFT) + { + $line=new PropaleLigne($this->db); - // For triggers - $line->fetch($lineid); + // For triggers + $line->fetch($lineid); - if ($line->delete() > 0) - { - $this->update_price(1); + if ($line->delete() > 0) + { + $this->update_price(1); - return 1; - } - else - { - return -1; - } - } - else - { - return -2; - } - } + return 1; + } + else + { + return -1; + } + } + else + { + return -2; + } + } - /** - * Create commercial proposal into database - * this->ref can be set or empty. If empty, we will use "(PROVid)" - * - * @param User $user User that create - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >=0 if OK - */ - function create($user, $notrigger=0) - { - global $conf,$hookmanager; - $error=0; + /** + * Create commercial proposal into database + * this->ref can be set or empty. If empty, we will use "(PROVid)" + * + * @param User $user User that create + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >=0 if OK + */ + function create($user, $notrigger=0) + { + global $conf,$hookmanager; + $error=0; - $now=dol_now(); + $now=dol_now(); - // Clean parameters - if (empty($this->date)) $this->date=$this->datep; - $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600); - if (empty($this->availability_id)) $this->availability_id=0; - if (empty($this->demand_reason_id)) $this->demand_reason_id=0; + // Clean parameters + if (empty($this->date)) $this->date=$this->datep; + $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600); + if (empty($this->availability_id)) $this->availability_id=0; + if (empty($this->demand_reason_id)) $this->demand_reason_id=0; - // Multicurrency - if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); + // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate) + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); + else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; @@ -845,18 +846,18 @@ class Propal extends CommonObject $this->multicurrency_tx = 1; } - dol_syslog(get_class($this)."::create"); + dol_syslog(get_class($this)."::create"); - // Check parameters - $result=$this->fetch_thirdparty(); - if ($result < 0) - { - $this->error="Failed to fetch company"; - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -3; - } + // Check parameters + $result=$this->fetch_thirdparty(); + if ($result < 0) + { + $this->error="Failed to fetch company"; + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -3; + } - // Check parameters + // Check parameters if (! empty($this->ref)) // We check that ref is not already used { $result=self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used @@ -869,96 +870,96 @@ class Propal extends CommonObject } } - if (empty($this->date)) - { - $this->error="Date of proposal is required"; - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -4; - } + if (empty($this->date)) + { + $this->error="Date of proposal is required"; + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -4; + } - $this->db->begin(); + $this->db->begin(); - // Insert into database - $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal ("; - $sql.= "fk_soc"; - $sql.= ", price"; - $sql.= ", remise"; - $sql.= ", remise_percent"; - $sql.= ", remise_absolue"; - $sql.= ", tva"; - $sql.= ", total"; - $sql.= ", datep"; - $sql.= ", datec"; - $sql.= ", ref"; - $sql.= ", fk_user_author"; - $sql.= ", note_private"; - $sql.= ", note_public"; - $sql.= ", model_pdf"; - $sql.= ", fin_validite"; - $sql.= ", fk_cond_reglement"; - $sql.= ", fk_mode_reglement"; - $sql.= ", fk_account"; - $sql.= ", ref_client"; - $sql.= ", date_livraison"; - $sql.= ", fk_shipping_method"; - $sql.= ", fk_availability"; - $sql.= ", fk_input_reason"; - $sql.= ", fk_projet"; - $sql.= ", fk_incoterms"; - $sql.= ", location_incoterms"; - $sql.= ", entity"; - $sql.= ", fk_multicurrency"; - $sql.= ", multicurrency_code"; - $sql.= ", multicurrency_tx"; - $sql.= ") "; - $sql.= " VALUES ("; - $sql.= $this->socid; - $sql.= ", 0"; - $sql.= ", ".$this->remise; - $sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'NULL'); - $sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'NULL'); - $sql.= ", 0"; - $sql.= ", 0"; - $sql.= ", '".$this->db->idate($this->date)."'"; - $sql.= ", '".$this->db->idate($now)."'"; - $sql.= ", '(PROV)'"; - $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"NULL"); - $sql.= ", '".$this->db->escape($this->note_private)."'"; - $sql.= ", '".$this->db->escape($this->note_public)."'"; - $sql.= ", '".$this->db->escape($this->modelpdf)."'"; - $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"NULL"); - $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL'); - $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL'); - $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); - $sql.= ", '".$this->db->escape($this->ref_client)."'"; - $sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"NULL"); - $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); - $sql.= ", ".$this->availability_id; - $sql.= ", ".$this->demand_reason_id; - $sql.= ", ".($this->fk_project?$this->fk_project:"null"); - $sql.= ", ".(int) $this->fk_incoterms; - $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; - $sql.= ", ".$conf->entity; + // Insert into database + $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal ("; + $sql.= "fk_soc"; + $sql.= ", price"; + $sql.= ", remise"; + $sql.= ", remise_percent"; + $sql.= ", remise_absolue"; + $sql.= ", tva"; + $sql.= ", total"; + $sql.= ", datep"; + $sql.= ", datec"; + $sql.= ", ref"; + $sql.= ", fk_user_author"; + $sql.= ", note_private"; + $sql.= ", note_public"; + $sql.= ", model_pdf"; + $sql.= ", fin_validite"; + $sql.= ", fk_cond_reglement"; + $sql.= ", fk_mode_reglement"; + $sql.= ", fk_account"; + $sql.= ", ref_client"; + $sql.= ", date_livraison"; + $sql.= ", fk_shipping_method"; + $sql.= ", fk_availability"; + $sql.= ", fk_input_reason"; + $sql.= ", fk_projet"; + $sql.= ", fk_incoterms"; + $sql.= ", location_incoterms"; + $sql.= ", entity"; + $sql.= ", fk_multicurrency"; + $sql.= ", multicurrency_code"; + $sql.= ", multicurrency_tx"; + $sql.= ") "; + $sql.= " VALUES ("; + $sql.= $this->socid; + $sql.= ", 0"; + $sql.= ", ".$this->remise; + $sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'NULL'); + $sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'NULL'); + $sql.= ", 0"; + $sql.= ", 0"; + $sql.= ", '".$this->db->idate($this->date)."'"; + $sql.= ", '".$this->db->idate($now)."'"; + $sql.= ", '(PROV)'"; + $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"NULL"); + $sql.= ", '".$this->db->escape($this->note_private)."'"; + $sql.= ", '".$this->db->escape($this->note_public)."'"; + $sql.= ", '".$this->db->escape($this->modelpdf)."'"; + $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"NULL"); + $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL'); + $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL'); + $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); + $sql.= ", '".$this->db->escape($this->ref_client)."'"; + $sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"NULL"); + $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); + $sql.= ", ".$this->availability_id; + $sql.= ", ".$this->demand_reason_id; + $sql.= ", ".($this->fk_project?$this->fk_project:"null"); + $sql.= ", ".(int) $this->fk_incoterms; + $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql.= ", ".$conf->entity; $sql.= ", ".(int) $this->fk_multicurrency; $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; $sql.= ", ".(double) $this->multicurrency_tx; - $sql.= ")"; + $sql.= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal"); + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal"); - if ($this->id) - { - $this->ref='(PROV'.$this->id.')'; - $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + if ($this->id) + { + $this->ref='(PROV'.$this->id.')'; + $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $error++; + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) $error++; if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects { @@ -1010,12 +1011,12 @@ class Propal extends CommonObject $fk_parent_line=0; $num=count($this->lines); - for ($i=0;$i<$num;$i++) - { - // Reset fk_parent_line for line that are not child lines or special product - if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { - $fk_parent_line = 0; - } + for ($i=0;$i<$num;$i++) + { + // Reset fk_parent_line for line that are not child lines or special product + if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { + $fk_parent_line = 0; + } $result = $this->addline( $this->lines[$i]->desc, @@ -1036,161 +1037,168 @@ class Propal extends CommonObject $this->lines[$i]->fk_fournprice, $this->lines[$i]->pa_ht, $this->lines[$i]->label, - $this->lines[$i]->date_start, + $this->lines[$i]->date_start, $this->lines[$i]->date_end, $this->lines[$i]->array_options, $this->lines[$i]->fk_unit, - $this->element, - $this->lines[$i]->id + $this->element, + $this->lines[$i]->id ); - if ($result < 0) - { - $error++; - $this->error=$this->db->error; - dol_print_error($this->db); - break; - } - // Defined the new fk_parent_line - if ($result > 0 && $this->lines[$i]->product_type == 9) { - $fk_parent_line = $result; - } - } - } + if ($result < 0) + { + $error++; + $this->error=$this->db->error; + dol_print_error($this->db); + break; + } + // Defined the new fk_parent_line + if ($result > 0 && $this->lines[$i]->product_type == 9) { + $fk_parent_line = $result; + } + } + } - // Set delivery address - if (! $error && $this->fk_delivery_address) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_delivery_address = ".$this->fk_delivery_address; - $sql.= " WHERE ref = '".$this->db->escape($this->ref)."'"; - $sql.= " AND entity = ".$conf->entity; + // Add linked object + if (! $error && $this->origin && $this->origin_id) + { + $ret = $this->add_object_linked(); + if (! $ret) dol_print_error($this->db); + } - $result=$this->db->query($sql); - } + // Set delivery address + if (! $error && $this->fk_delivery_address) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; + $sql.= " SET fk_delivery_address = ".$this->fk_delivery_address; + $sql.= " WHERE ref = '".$this->db->escape($this->ref)."'"; + $sql.= " AND entity = ".$conf->entity; - if (! $error) - { - // Mise a jour infos denormalisees - $resql=$this->update_price(1); - if ($resql) - { - $action='update'; + $result=$this->db->query($sql); + } - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('propaldao')); - $parameters=array('socid'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - else if ($reshook < 0) $error++; - - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('PROPAL_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } - else + if (! $error) + { + // Mise a jour infos denormalisees + $resql=$this->update_price(1); + if ($resql) { - $this->error=$this->db->lasterror(); - $error++; - } - } - } - else + $action='update'; + + // Actions on extra fields (by external module or standard code) + // TODO le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('propaldao')); + $parameters=array('socid'=>$this->id); + $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if (empty($reshook)) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } + else if ($reshook < 0) $error++; + + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('PROPAL_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + else + { + $this->error=$this->db->lasterror(); + $error++; + } + } + } + else { - $this->error=$this->db->lasterror(); - $error++; - } + $this->error=$this->db->lasterror(); + $error++; + } - if (! $error) - { - $this->db->commit(); - dol_syslog(get_class($this)."::create done id=".$this->id); - return $this->id; - } - else - { - $this->db->rollback(); - return -2; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } + if (! $error) + { + $this->db->commit(); + dol_syslog(get_class($this)."::create done id=".$this->id); + return $this->id; + } + else + { + $this->db->rollback(); + return -2; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } - /** - * Insert into DB a proposal object completely defined by its data members (ex, results from copy). - * - * @param User $user User that create - * @return int Id of the new object if ok, <0 if ko - * @see create - */ - function create_from($user) - { - // i love this function because $this->products is not used in create function... - $this->products=$this->lines; + /** + * Insert into DB a proposal object completely defined by its data members (ex, results from copy). + * + * @param User $user User that create + * @return int Id of the new object if ok, <0 if ko + * @see create + */ + function create_from($user) + { + // i love this function because $this->products is not used in create function... + $this->products=$this->lines; - return $this->create($user); - } + return $this->create($user); + } - /** - * Load an object from its id and create a new one in database - * - * @param int $socid Id of thirdparty - * @return int New id of clone - */ - function createFromClone($socid=0) - { - global $user,$conf,$hookmanager; + /** + * Load an object from its id and create a new one in database + * + * @param int $socid Id of thirdparty + * @return int New id of clone + */ + function createFromClone($socid=0) + { + global $user,$conf,$hookmanager; dol_include_once('/projet/class/project.class.php'); - $this->context['createfromclone']='createfromclone'; + $this->context['createfromclone']='createfromclone'; - $error=0; - $now=dol_now(); + $error=0; + $now=dol_now(); - $this->db->begin(); + $this->db->begin(); // get extrafields so they will be clone foreach($this->lines as $line) $line->fetch_optionals($line->rowid); - // Load dest object - $clonedObj = clone $this; + // Load dest object + $clonedObj = clone $this; - $objsoc=new Societe($this->db); + $objsoc=new Societe($this->db); - // Change socid if needed - if (! empty($socid) && $socid != $clonedObj->socid) - { - if ($objsoc->fetch($socid) > 0) - { - $clonedObj->socid = $objsoc->id; - $clonedObj->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); - $clonedObj->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); - $clonedObj->fk_delivery_address = ''; + // Change socid if needed + if (! empty($socid) && $socid != $clonedObj->socid) + { + if ($objsoc->fetch($socid) > 0) + { + $clonedObj->socid = $objsoc->id; + $clonedObj->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + $clonedObj->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $clonedObj->fk_delivery_address = ''; - /*if (!empty($conf->projet->enabled)) + /*if (!empty($conf->projet->enabled)) { $project = new Project($db); if ($this->fk_project > 0 && $project->fetch($this->fk_project)) { @@ -1200,189 +1208,190 @@ class Propal extends CommonObject $clonedObj->fk_project = ''; } }*/ - $clonedObj->fk_project = ''; // A cloned proposal is set by default to no project. - } + $clonedObj->fk_project = ''; // A cloned proposal is set by default to no project. + } - // reset ref_client - $clonedObj->ref_client = ''; + // reset ref_client + $clonedObj->ref_client = ''; - // TODO Change product price if multi-prices - } - else - { - $objsoc->fetch($clonedObj->socid); - } + // TODO Change product price if multi-prices + } + else + { + $objsoc->fetch($clonedObj->socid); + } - $clonedObj->id=0; - $clonedObj->ref=''; - $clonedObj->statut=self::STATUS_DRAFT; + $clonedObj->id=0; + $clonedObj->ref=''; + $clonedObj->statut=self::STATUS_DRAFT; - // Clear fields - $clonedObj->user_author = $user->id; - $clonedObj->user_valid = ''; - $clonedObj->date = $now; - $clonedObj->datep = $now; // deprecated - $clonedObj->fin_validite = $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600); - if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client = ''; + // Clear fields + $clonedObj->user_author = $user->id; + $clonedObj->user_valid = ''; + $clonedObj->date = $now; + $clonedObj->datep = $now; // deprecated + $clonedObj->fin_validite = $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600); + if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client = ''; - // Create clone + // Create clone - $result=$clonedObj->create($user); - if ($result < 0) $error++; - else - { + $result=$clonedObj->create($user); + if ($result < 0) $error++; + else + { // copy internal contacts - if ($clonedObj->copy_linked_contact($this, 'internal') < 0) - $error++; + if ($clonedObj->copy_linked_contact($this, 'internal') < 0) + $error++; - // copy external contacts if same company - elseif ($this->socid == $clonedObj->socid) - { - if ($clonedObj->copy_linked_contact($this, 'external') < 0) + // copy external contacts if same company + elseif ($this->socid == $clonedObj->socid) + { + if ($clonedObj->copy_linked_contact($this, 'external') < 0) $error++; - } - } + } + } - if (! $error) - { - // Hook of thirdparty module - if (is_object($hookmanager)) - { - $parameters=array('objFrom'=>$this,'clonedObj'=>$clonedObj); - $action=''; - $reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; - } + if (! $error) + { + // Hook of thirdparty module + if (is_object($hookmanager)) + { + $parameters=array('objFrom'=>$this,'clonedObj'=>$clonedObj); + $action=''; + $reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) $error++; + } - // Call trigger - $result=$clonedObj->call_trigger('PROPAL_CLONE',$user); - if ($result < 0) { $error++; } - // End call triggers - } + // Call trigger + $result=$clonedObj->call_trigger('PROPAL_CLONE',$user); + if ($result < 0) { $error++; } + // End call triggers + } - unset($this->context['createfromclone']); + unset($this->context['createfromclone']); - // End - if (! $error) - { - $this->db->commit(); - return $clonedObj->id; - } - else - { - $this->db->rollback(); - return -1; - } - } + // End + if (! $error) + { + $this->db->commit(); + return $clonedObj->id; + } + else + { + $this->db->rollback(); + return -1; + } + } - /** - * Load a proposal from database and its ligne array - * - * @param int $rowid id of object to load - * @param string $ref Ref of proposal - * @return int >0 if OK, <0 if KO - */ - function fetch($rowid,$ref='') - { + /** + * Load a proposal from database and its ligne array + * + * @param int $rowid id of object to load + * @param string $ref Ref of proposal + * @return int >0 if OK, <0 if KO + */ + function fetch($rowid,$ref='') + { - $sql = "SELECT p.rowid, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; - $sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; - $sql.= ", p.datec"; - $sql.= ", p.date_valid as datev"; - $sql.= ", p.datep as dp"; - $sql.= ", p.fin_validite as dfv"; - $sql.= ", p.date_livraison as date_livraison"; - $sql.= ", p.model_pdf, p.ref_client, p.extraparams"; - $sql.= ", p.note_private, p.note_public"; - $sql.= ", p.fk_projet, p.fk_statut"; - $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; - $sql.= ", p.fk_delivery_address"; - $sql.= ", p.fk_availability"; - $sql.= ", p.fk_input_reason"; - $sql.= ", p.fk_cond_reglement"; - $sql.= ", p.fk_mode_reglement"; - $sql.= ', p.fk_account'; - $sql.= ", p.fk_shipping_method"; - $sql.= ", p.fk_incoterms, p.location_incoterms"; + $sql = "SELECT p.rowid, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; + $sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; + $sql.= ", p.datec"; + $sql.= ", p.date_valid as datev"; + $sql.= ", p.datep as dp"; + $sql.= ", p.fin_validite as dfv"; + $sql.= ", p.date_livraison as date_livraison"; + $sql.= ", p.model_pdf, p.last_main_doc, p.ref_client, p.extraparams"; + $sql.= ", p.note_private, p.note_public"; + $sql.= ", p.fk_projet, p.fk_statut"; + $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; + $sql.= ", p.fk_delivery_address"; + $sql.= ", p.fk_availability"; + $sql.= ", p.fk_input_reason"; + $sql.= ", p.fk_cond_reglement"; + $sql.= ", p.fk_mode_reglement"; + $sql.= ', p.fk_account'; + $sql.= ", p.fk_shipping_method"; + $sql.= ", p.fk_incoterms, p.location_incoterms"; $sql.= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc"; - $sql.= ", i.libelle as libelle_incoterms"; - $sql.= ", c.label as statut_label"; - $sql.= ", ca.code as availability_code, ca.label as availability"; - $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason"; - $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; - $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid'; + $sql.= ", i.libelle as libelle_incoterms"; + $sql.= ", c.label as statut_label"; + $sql.= ", ca.code as availability_code, ca.label as availability"; + $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason"; + $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; + $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p"; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN (' . getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid'; - $sql.= " WHERE p.fk_statut = c.id"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; - if ($ref) $sql.= " AND p.ref='".$ref."'"; - else $sql.= " AND p.rowid=".$rowid; + $sql.= " WHERE p.fk_statut = c.id"; + $sql.= " AND p.entity IN (".getEntity('propal').")"; + if ($ref) $sql.= " AND p.ref='".$ref."'"; + else $sql.= " AND p.rowid=".$rowid; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; - $this->ref = $obj->ref; - $this->ref_client = $obj->ref_client; - $this->remise = $obj->remise; - $this->remise_percent = $obj->remise_percent; - $this->remise_absolue = $obj->remise_absolue; - $this->total = $obj->total; // TODO deprecated - $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->tva; - $this->total_localtax1 = $obj->localtax1; - $this->total_localtax2 = $obj->localtax2; - $this->total_ttc = $obj->total; - $this->socid = $obj->fk_soc; - $this->fk_project = $obj->fk_projet; - $this->modelpdf = $obj->model_pdf; - $this->note = $obj->note_private; // TODO deprecated - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->statut = (int) $obj->fk_statut; - $this->statut_libelle = $obj->statut_label; + $this->ref = $obj->ref; + $this->ref_client = $obj->ref_client; + $this->remise = $obj->remise; + $this->remise_percent = $obj->remise_percent; + $this->remise_absolue = $obj->remise_absolue; + $this->total = $obj->total; // TODO deprecated + $this->total_ht = $obj->total_ht; + $this->total_tva = $obj->tva; + $this->total_localtax1 = $obj->localtax1; + $this->total_localtax2 = $obj->localtax2; + $this->total_ttc = $obj->total; + $this->socid = $obj->fk_soc; + $this->fk_project = $obj->fk_projet; + $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; + $this->note = $obj->note_private; // TODO deprecated + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->statut = (int) $obj->fk_statut; + $this->statut_libelle = $obj->statut_label; - $this->datec = $this->db->jdate($obj->datec); // TODO deprecated - $this->datev = $this->db->jdate($obj->datev); // TODO deprecated - $this->date_creation = $this->db->jdate($obj->datec); //Creation date - $this->date_validation = $this->db->jdate($obj->datev); //Validation date - $this->date = $this->db->jdate($obj->dp); // Proposal date - $this->datep = $this->db->jdate($obj->dp); // deprecated - $this->fin_validite = $this->db->jdate($obj->dfv); - $this->date_livraison = $this->db->jdate($obj->date_livraison); - $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; - $this->availability_id = $obj->fk_availability; - $this->availability_code = $obj->availability_code; - $this->availability = $obj->availability; - $this->demand_reason_id = $obj->fk_input_reason; - $this->demand_reason_code = $obj->demand_reason_code; - $this->demand_reason = $obj->demand_reason; - $this->fk_address = $obj->fk_delivery_address; + $this->datec = $this->db->jdate($obj->datec); // TODO deprecated + $this->datev = $this->db->jdate($obj->datev); // TODO deprecated + $this->date_creation = $this->db->jdate($obj->datec); //Creation date + $this->date_validation = $this->db->jdate($obj->datev); //Validation date + $this->date = $this->db->jdate($obj->dp); // Proposal date + $this->datep = $this->db->jdate($obj->dp); // deprecated + $this->fin_validite = $this->db->jdate($obj->dfv); + $this->date_livraison = $this->db->jdate($obj->date_livraison); + $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; + $this->availability_id = $obj->fk_availability; + $this->availability_code = $obj->availability_code; + $this->availability = $obj->availability; + $this->demand_reason_id = $obj->fk_input_reason; + $this->demand_reason_code = $obj->demand_reason_code; + $this->demand_reason = $obj->demand_reason; + $this->fk_address = $obj->fk_delivery_address; - $this->mode_reglement_id = $obj->fk_mode_reglement; - $this->mode_reglement_code = $obj->mode_reglement_code; - $this->mode_reglement = $obj->mode_reglement; - $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null; - $this->cond_reglement_id = $obj->fk_cond_reglement; - $this->cond_reglement_code = $obj->cond_reglement_code; - $this->cond_reglement = $obj->cond_reglement; - $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; + $this->mode_reglement_id = $obj->fk_mode_reglement; + $this->mode_reglement_code = $obj->mode_reglement_code; + $this->mode_reglement = $obj->mode_reglement; + $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null; + $this->cond_reglement_id = $obj->fk_cond_reglement; + $this->cond_reglement_code = $obj->cond_reglement_code; + $this->cond_reglement = $obj->cond_reglement; + $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; - $this->extraparams = (array) json_decode($obj->extraparams, true); + $this->extraparams = (array) json_decode($obj->extraparams, true); - $this->user_author_id = $obj->fk_user_author; - $this->user_valid_id = $obj->fk_user_valid; - $this->user_close_id = $obj->fk_user_cloture; + $this->user_author_id = $obj->fk_user_author; + $this->user_valid_id = $obj->fk_user_valid; + $this->user_close_id = $obj->fk_user_cloture; //Incoterms $this->fk_incoterms = $obj->fk_incoterms; @@ -1397,43 +1406,43 @@ class Propal extends CommonObject $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - if ($obj->fk_statut == self::STATUS_DRAFT) - { - $this->brouillon = 1; - } + if ($obj->fk_statut == self::STATUS_DRAFT) + { + $this->brouillon = 1; + } - // Retreive all extrafield for invoice - // fetch optionals attributes and labels - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + // Retreive all extrafield for invoice + // fetch optionals attributes and labels + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + $this->fetch_optionals($this->id,$extralabels); - $this->db->free($resql); + $this->db->free($resql); - $this->lines = array(); + $this->lines = array(); - /* + /* * Lines */ - $result=$this->fetch_lines(); - if ($result < 0) - { - return -3; - } + $result=$this->fetch_lines(); + if ($result < 0) + { + return -3; + } - return 1; - } + return 1; + } - $this->error="Record Not Found"; - return 0; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } + $this->error="Record Not Found"; + return 0; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } /** * Load array lines @@ -1545,103 +1554,61 @@ class Propal extends CommonObject } } - /** - * Update value of extrafields on the proposal - * - * @param User $user Object user that modify - * @return int <0 if ko, >0 if ok - */ - function update_extrafields($user) - { - global $conf, $hookmanager; + /** + * Set status to validated + * + * @param User $user Object user that validate + * @param int $notrigger 1=Does not execute triggers, 0=execute triggers + * @return int <0 if KO, 0=Nothing done, >=0 if OK + */ + function valid($user, $notrigger=0) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $action='update'; - $error = 0; + global $conf; - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('propaldao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - else if ($reshook < 0) $error++; + $error=0; - if (!$error) - { - return 1; - } - else - { - return -1; - } + // Protection + if ($this->statut == self::STATUS_VALIDATED) + { + dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); + return 0; + } - } + if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate)))) + { + $this->error='ErrorPermissionDenied'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + } - /** - * Set status to validated - * - * @param User $user Object user that validate - * @param int $notrigger 1=Does not execute triggers, 0=execute triggers - * @return int <0 if KO, 0=Nothing done, >=0 if OK - */ - function valid($user, $notrigger=0) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + $now=dol_now(); - global $conf; + $this->db->begin(); - $error=0; + // Numbering module definition + $soc = new Societe($this->db); + $soc->fetch($this->socid); - // Protection - if ($this->statut == self::STATUS_VALIDATED) - { - dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); - return 0; - } + // Define new ref + if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life + { + $num = $this->getNextNumRef($soc); + } + else + { + $num = $this->ref; + } + $this->newref = $num; - if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate)))) - { - $this->error='ErrorPermissionDenied'; - dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); - return -1; - } + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; + $sql.= " SET ref = '".$num."',"; + $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - $now=dol_now(); - - $this->db->begin(); - - // Numbering module definition - $soc = new Societe($this->db); - $soc->fetch($this->socid); - - // Define new ref - if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { - $num = $this->getNextNumRef($soc); - } - else - { - $num = $this->ref; - } - $this->newref = $num; - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET ref = '".$num."',"; - $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - - dol_syslog(get_class($this)."::valid", LOG_DEBUG); + dol_syslog(get_class($this)."::valid", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -1652,607 +1619,607 @@ class Propal extends CommonObject // Trigger calls if (! $error && ! $notrigger) { - // Call trigger - $result=$this->call_trigger('PROPAL_VALIDATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } + // Call trigger + $result=$this->call_trigger('PROPAL_VALIDATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } - if (! $error) - { - $this->oldref = $this->ref; - - // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { - // Rename of propal directory ($this->ref = old ref, $num = new ref) - // to not lose the linked files - $oldref = dol_sanitizeFileName($this->ref); - $newref = dol_sanitizeFileName($num); - $dirsource = $conf->propal->dir_output.'/'.$oldref; - $dirdest = $conf->propal->dir_output.'/'.$newref; - - if (file_exists($dirsource)) - { - dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { - dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); - foreach($listoffiles as $fileentry) - { - $dirsource=$fileentry['name']; - $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); - $dirsource=$fileentry['path'].'/'.$dirsource; - $dirdest=$fileentry['path'].'/'.$dirdest; - @rename($dirsource, $dirdest); - } - } - } - } - - $this->ref=$num; - $this->brouillon=0; - $this->statut = self::STATUS_VALIDATED; - $this->user_valid_id=$user->id; - $this->datev=$now; - - $this->db->commit(); - return 1; - } - else + if (! $error) { - $this->db->rollback(); - return -1; - } - } - - - /** - * Define proposal date - * - * @param User $user Object user that modify - * @param int $date Date - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_date($user, $date, $notrigger=0) - { - if (empty($date)) - { - $this->error='ErrorBadParameter'; - dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR); - return -1; - } - - if (! empty($user->rights->propal->creer)) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'"; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->date = $date; - $this->datep = $date; // deprecated - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - /** - * Define end validity date - * - * @param User $user Object user that modify - * @param int $date_fin_validite End of validity date - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_echeance($user, $date_fin_validite, $notrigger=0) - { - if (! empty($user->rights->propal->creer)) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite!=''?"'".$this->db->idate($date_fin_validite)."'":'null'); - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - - if (! $error) - { - $this->oldcopy= clone $this; - $this->fin_validite = $date_fin_validite; - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - /** - * Set delivery date - * - * @param User $user Object user that modify - * @param int $date_livraison Delivery date - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function set_date_livraison($user, $date_livraison, $notrigger=0) - { - if (! empty($user->rights->propal->creer)) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null'); - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->date_livraison = $date_livraison; - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - /** - * Set delivery - * - * @param User $user Object user that modify - * @param int $id Availability id - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_availability($user, $id, $notrigger=0) - { - if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET fk_availability = '".$id."'"; - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->fk_availability = $id; - $this->availability_id = $id; - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - $error_str='Propal status do not meet requirement '.$this->statut; - dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; - return -2; - } - } - - /** - * Set source of demand - * - * @param User $user Object user that modify - * @param int $id Input reason id - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_demand_reason($user, $id, $notrigger=0) - { - if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET fk_input_reason = ".$id; - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - - if (! $error) - { - $this->oldcopy= clone $this; - $this->fk_input_reason = $id; - $this->demand_reason_id = $id; - } - - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - $error_str='Propal status do not meet requirement '.$this->statut; - dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; - return -2; - } - } - - /** - * Set customer reference number - * - * @param User $user Object user that modify - * @param string $ref_client Customer reference - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function set_ref_client($user, $ref_client, $notrigger=0) - { - if (! empty($user->rights->propal->creer)) - { - $error=0; - - $this->db->begin(); - - $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\''); - $sql.= ' WHERE rowid = '.$this->id; - - dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->ref_client = $ref_client; - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - return -1; - } - } - - /** - * Set an overall discount on the proposal - * - * @param User $user Object user that modify - * @param double $remise Amount discount - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function set_remise_percent($user, $remise, $notrigger=0) - { - $remise=trim($remise)?trim($remise):0; - - if (! empty($user->rights->propal->creer)) - { - $remise = price2num($remise); - - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".$remise; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->remise_percent = $remise; - $this->update_price(1); - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - - /** - * Set an absolute overall discount on the proposal - * - * @param User $user Object user that modify - * @param double $remise Amount discount - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function set_remise_absolue($user, $remise, $notrigger=0) - { - $remise=trim($remise)?trim($remise):0; - - if (! empty($user->rights->propal->creer)) - { - $remise = price2num($remise); - - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET remise_absolue = ".$remise; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->remise_absolue = $remise; - $this->update_price(1); - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - - - /** - * Reopen the commercial proposal - * - * @param User $user Object user that close - * @param int $statut Statut - * @param string $note Comment - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function reopen($user, $statut, $note='', $notrigger=0) - { - - $this->statut = $statut; - $error=0; - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_statut = ".$this->statut.","; + $this->oldref = $this->ref; + + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) + { + // Rename of propal directory ($this->ref = old ref, $num = new ref) + // to not lose the linked files + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->propal->dir_output.'/'.$oldref; + $dirdest = $conf->propal->dir_output.'/'.$newref; + + if (file_exists($dirsource)) + { + dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); + if (@rename($dirsource, $dirdest)) + { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + + $this->ref=$num; + $this->brouillon=0; + $this->statut = self::STATUS_VALIDATED; + $this->user_valid_id=$user->id; + $this->datev=$now; + + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } + + + /** + * Define proposal date + * + * @param User $user Object user that modify + * @param int $date Date + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_date($user, $date, $notrigger=0) + { + if (empty($date)) + { + $this->error='ErrorBadParameter'; + dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR); + return -1; + } + + if (! empty($user->rights->propal->creer)) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'"; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->date = $date; + $this->datep = $date; // deprecated + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + /** + * Define end validity date + * + * @param User $user Object user that modify + * @param int $date_fin_validite End of validity date + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_echeance($user, $date_fin_validite, $notrigger=0) + { + if (! empty($user->rights->propal->creer)) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite!=''?"'".$this->db->idate($date_fin_validite)."'":'null'); + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + + if (! $error) + { + $this->oldcopy= clone $this; + $this->fin_validite = $date_fin_validite; + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + /** + * Set delivery date + * + * @param User $user Object user that modify + * @param int $date_livraison Delivery date + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function set_date_livraison($user, $date_livraison, $notrigger=0) + { + if (! empty($user->rights->propal->creer)) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; + $sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null'); + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->date_livraison = $date_livraison; + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + /** + * Set delivery + * + * @param User $user Object user that modify + * @param int $id Availability id + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_availability($user, $id, $notrigger=0) + { + if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; + $sql.= " SET fk_availability = '".$id."'"; + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->fk_availability = $id; + $this->availability_id = $id; + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + $error_str='Propal status do not meet requirement '.$this->statut; + dol_syslog(__METHOD__.$error_str, LOG_ERR); + $this->error=$error_str; + $this->errors[]= $this->error; + return -2; + } + } + + /** + * Set source of demand + * + * @param User $user Object user that modify + * @param int $id Input reason id + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_demand_reason($user, $id, $notrigger=0) + { + if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; + $sql.= " SET fk_input_reason = ".$id; + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + + if (! $error) + { + $this->oldcopy= clone $this; + $this->fk_input_reason = $id; + $this->demand_reason_id = $id; + } + + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + $error_str='Propal status do not meet requirement '.$this->statut; + dol_syslog(__METHOD__.$error_str, LOG_ERR); + $this->error=$error_str; + $this->errors[]= $this->error; + return -2; + } + } + + /** + * Set customer reference number + * + * @param User $user Object user that modify + * @param string $ref_client Customer reference + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function set_ref_client($user, $ref_client, $notrigger=0) + { + if (! empty($user->rights->propal->creer)) + { + $error=0; + + $this->db->begin(); + + $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\''); + $sql.= ' WHERE rowid = '.$this->id; + + dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->ref_client = $ref_client; + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + return -1; + } + } + + /** + * Set an overall discount on the proposal + * + * @param User $user Object user that modify + * @param double $remise Amount discount + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function set_remise_percent($user, $remise, $notrigger=0) + { + $remise=trim($remise)?trim($remise):0; + + if (! empty($user->rights->propal->creer)) + { + $remise = price2num($remise); + + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".$remise; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->remise_percent = $remise; + $this->update_price(1); + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + + /** + * Set an absolute overall discount on the proposal + * + * @param User $user Object user that modify + * @param double $remise Amount discount + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function set_remise_absolue($user, $remise, $notrigger=0) + { + $remise=trim($remise)?trim($remise):0; + + if (! empty($user->rights->propal->creer)) + { + $remise = price2num($remise); + + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; + $sql.= " SET remise_absolue = ".$remise; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->remise_absolue = $remise; + $this->update_price(1); + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + + + /** + * Reopen the commercial proposal + * + * @param User $user Object user that close + * @param int $statut Statut + * @param string $note Comment + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function reopen($user, $statut, $note='', $notrigger=0) + { + + $this->statut = $statut; + $error=0; + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; + $sql.= " SET fk_statut = ".$this->statut.","; if (! empty($note)) $sql.= " note_private = '".$this->db->escape($note)."',"; - $sql.= " date_cloture=NULL, fk_user_cloture=NULL"; - $sql.= " WHERE rowid = ".$this->id; + $sql.= " date_cloture=NULL, fk_user_cloture=NULL"; + $sql.= " WHERE rowid = ".$this->id; - $this->db->begin(); + $this->db->begin(); dol_syslog(get_class($this)."::reopen", LOG_DEBUG); $resql = $this->db->query($sql); @@ -2263,24 +2230,24 @@ class Propal extends CommonObject { if (! $notrigger) { - // Call trigger - $result=$this->call_trigger('PROPAL_REOPEN',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('PROPAL_REOPEN',$user); + if ($result < 0) { $error++; } + // End call triggers } } // Commit or rollback if ($error) { - if (!empty($this->errors)) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - } + if (!empty($this->errors)) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + } $this->db->rollback(); return -1*$error; } @@ -2289,746 +2256,748 @@ class Propal extends CommonObject $this->db->commit(); return 1; } - } + } - /** - * Close the commercial proposal - * - * @param User $user Object user that close - * @param int $statut Statut - * @param string $note Comment - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function cloture($user, $statut, $note, $notrigger=0) - { - global $langs,$conf; + /** + * Close the commercial proposal + * + * @param User $user Object user that close + * @param int $statut Statut + * @param string $note Complete private note with this note + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, >0 if OK + */ + function cloture($user, $statut, $note, $notrigger=0) + { + global $langs,$conf; - $error=0; - $now=dol_now(); + $error=0; + $now=dol_now(); - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $newprivatenote = dol_concatdesc($this->note_private, $note); - $resql=$this->db->query($sql); - if ($resql) - { - $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf; - $trigger_name='PROPAL_CLOSE_REFUSED'; + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; + $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; + $sql.= " WHERE rowid = ".$this->id; - if ($statut == self::STATUS_SIGNED) - { - $trigger_name='PROPAL_CLOSE_SIGNED'; + $resql=$this->db->query($sql); + if ($resql) + { + $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf; + $trigger_name='PROPAL_CLOSE_REFUSED'; + + if ($statut == self::STATUS_SIGNED) + { + $trigger_name='PROPAL_CLOSE_SIGNED'; $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL?$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL:$this->modelpdf; - // The connected company is classified as a client - $soc=new Societe($this->db); - $soc->id = $this->socid; - $result=$soc->set_as_client(); + // The connected company is classified as a client + $soc=new Societe($this->db); + $soc->id = $this->socid; + $result=$soc->set_as_client(); - if ($result < 0) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -2; - } - } - if ($statut == self::STATUS_BILLED) - { - $trigger_name='PROPAL_CLASSIFY_BILLED'; - } + if ($result < 0) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -2; + } + } + if ($statut == self::STATUS_BILLED) // Why this ? + { + $trigger_name='PROPAL_CLASSIFY_BILLED'; + } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - // Define output language - $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) - { - $outputlangs = new Translate("",$conf); - $newlang=(GETPOST('lang_id','aZ09') ? GETPOST('lang_id','aZ09') : $this->thirdparty->default_lang); - $outputlangs->setDefaultLang($newlang); - } - //$ret=$object->fetch($id); // Reload to get new records - $this->generateDocument($modelpdf, $outputlangs); - } + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + // Define output language + $outputlangs = $langs; + if (! empty($conf->global->MAIN_MULTILANGS)) + { + $outputlangs = new Translate("",$conf); + $newlang=(GETPOST('lang_id','aZ09') ? GETPOST('lang_id','aZ09') : $this->thirdparty->default_lang); + $outputlangs->setDefaultLang($newlang); + } + //$ret=$object->fetch($id); // Reload to get new records + $this->generateDocument($modelpdf, $outputlangs); + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->statut = $statut; - $this->date_cloture = $now; - $this->note_private = $note; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->statut = $statut; + $this->date_cloture = $now; + $this->note_private = $note; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger($trigger_name,$user); - if ($result < 0) { $error++; } - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger($trigger_name,$user); + if ($result < 0) { $error++; } + // End call triggers + } - if ( ! $error ) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } + if ( ! $error ) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } - /** - * Class invoiced the Propal - * - * @param User $user Object user - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 si ko, >0 si ok - */ - function classifyBilled(User $user, $notrigger=0) - { - $error=0; + /** + * Class invoiced the Propal + * + * @param User $user Object user + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 si ko, >0 si ok + */ + function classifyBilled(User $user, $notrigger=0) + { + $error=0; - $this->db->begin(); + $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET fk_statut = '.self::STATUS_BILLED; - $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET fk_statut = '.self::STATUS_BILLED; + $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->statut=self::STATUS_BILLED; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->statut=self::STATUS_BILLED; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } - /** - * Class invoiced the Propal - * - * @return int <0 si ko, >0 si ok - * @deprecated - * @see classifyBilled() - */ - function classer_facturee() - { - global $user; + /** + * Class invoiced the Propal + * + * @return int <0 si ko, >0 si ok + * @deprecated + * @see classifyBilled() + */ + function classer_facturee() + { + global $user; dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING); - return $this->classifyBilled($user); - } + return $this->classifyBilled($user); + } - /** - * Set draft status - * - * @param User $user Object user that modify - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_draft($user, $notrigger=0) - { - $error=0; + /** + * Set draft status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_draft($user, $notrigger=0) + { + $error=0; - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fk_statut = ".self::STATUS_DRAFT; - $sql.= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fk_statut = ".self::STATUS_DRAFT; + $sql.= " WHERE rowid = ".$this->id; - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->statut = self::STATUS_DRAFT; - $this->brouillon = 1; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->statut = self::STATUS_DRAFT; + $this->brouillon = 1; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } - /** - * Return list of proposal (eventually filtered on user) into an array - * - * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name) - * @param int $draft 0=not draft, 1=draft - * @param int $notcurrentuser 0=all user, 1=not current user - * @param int $socid Id third pary - * @param int $limit For pagination - * @param int $offset For pagination - * @param string $sortfield Sort criteria - * @param string $sortorder Sort order - * @return int -1 if KO, array with result if OK - */ - function liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datep', $sortorder='DESC') - { - global $user; + /** + * Return list of proposal (eventually filtered on user) into an array + * + * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name) + * @param int $draft 0=not draft, 1=draft + * @param int $notcurrentuser 0=all user, 1=not current user + * @param int $socid Id third pary + * @param int $limit For pagination + * @param int $offset For pagination + * @param string $sortfield Sort criteria + * @param string $sortorder Sort order + * @return int -1 if KO, array with result if OK + */ + function liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datep', $sortorder='DESC') + { + global $user; - $ga = array(); + $ga = array(); - $sql = "SELECT s.rowid, s.nom as name, s.client,"; - $sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; - $sql.= " p.datep as dp, p.fin_validite as datelimite"; - if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; + $sql = "SELECT s.rowid, s.nom as name, s.client,"; + $sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; + $sql.= " p.datep as dp, p.fin_validite as datelimite"; + if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.entity IN (".getEntity('propal').")"; - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.fk_statut = c.id"; - if (! $user->rights->societe->client->voir && ! $socid) //restriction - { - $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - } - if ($socid) $sql.= " AND s.rowid = ".$socid; - if ($draft) $sql.= " AND p.fk_statut = ".self::STATUS_DRAFT; - if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id; - $sql.= $this->db->order($sortfield,$sortorder); - $sql.= $this->db->plimit($limit,$offset); + $sql.= " WHERE p.entity IN (".getEntity('propal').")"; + $sql.= " AND p.fk_soc = s.rowid"; + $sql.= " AND p.fk_statut = c.id"; + if (! $user->rights->societe->client->voir && ! $socid) //restriction + { + $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + } + if ($socid) $sql.= " AND s.rowid = ".$socid; + if ($draft) $sql.= " AND p.fk_statut = ".self::STATUS_DRAFT; + if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id; + $sql.= $this->db->order($sortfield,$sortorder); + $sql.= $this->db->plimit($limit,$offset); - $result=$this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - if ($num) - { - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - - if ($shortlist == 1) - { - $ga[$obj->propalid] = $obj->ref; - } - else if ($shortlist == 2) - { - $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')'; - } - else - { - $ga[$i]['id'] = $obj->propalid; - $ga[$i]['ref'] = $obj->ref; - $ga[$i]['name'] = $obj->name; - } - - $i++; - } - } - return $ga; - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Returns an array with the numbers of related invoices - * - * @return array Array of invoices - */ - function getInvoiceArrayList() - { - return $this->InvoiceArrayList($this->id); - } - - /** - * Returns an array with id and ref of related invoices - * - * @param int $id Id propal - * @return array Array of invoices id - */ - function InvoiceArrayList($id) - { - $ga = array(); - $linkedInvoices = array(); - - $this->fetchObjectLinked($id,$this->element); - foreach($this->linkedObjectsIds as $objecttype => $objectid) - { - // Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n - // On parcourt donc une liste d'objets en tant qu'objet unique - foreach($objectid as $key => $object) - { - // Cas des factures liees directement - if ($objecttype == 'facture') - { - $linkedInvoices[] = $object; - } - // Cas des factures liees par un autre objet (ex: commande) - else + $result=$this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + if ($num) + { + $i = 0; + while ($i < $num) { - $this->fetchObjectLinked($object,$objecttype); - foreach($this->linkedObjectsIds as $subobjecttype => $subobjectid) - { + $obj = $this->db->fetch_object($result); + + if ($shortlist == 1) + { + $ga[$obj->propalid] = $obj->ref; + } + else if ($shortlist == 2) + { + $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')'; + } + else + { + $ga[$i]['id'] = $obj->propalid; + $ga[$i]['ref'] = $obj->ref; + $ga[$i]['name'] = $obj->name; + } + + $i++; + } + } + return $ga; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Returns an array with the numbers of related invoices + * + * @return array Array of invoices + */ + function getInvoiceArrayList() + { + return $this->InvoiceArrayList($this->id); + } + + /** + * Returns an array with id and ref of related invoices + * + * @param int $id Id propal + * @return array Array of invoices id + */ + function InvoiceArrayList($id) + { + $ga = array(); + $linkedInvoices = array(); + + $this->fetchObjectLinked($id,$this->element); + foreach($this->linkedObjectsIds as $objecttype => $objectid) + { + // Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n + // On parcourt donc une liste d'objets en tant qu'objet unique + foreach($objectid as $key => $object) + { + // Cas des factures liees directement + if ($objecttype == 'facture') + { + $linkedInvoices[] = $object; + } + // Cas des factures liees par un autre objet (ex: commande) + else + { + $this->fetchObjectLinked($object,$objecttype); + foreach($this->linkedObjectsIds as $subobjecttype => $subobjectid) + { foreach($subobjectid as $subkey => $subobject) - { - if ($subobjecttype == 'facture') - { - $linkedInvoices[] = $subobject; - } - } - } - } - } - } + { + if ($subobjecttype == 'facture') + { + $linkedInvoices[] = $subobject; + } + } + } + } + } + } - if (count($linkedInvoices) > 0) - { - $sql= "SELECT rowid as facid, facnumber, total, datef as df, fk_user_author, fk_statut, paye"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture"; - $sql.= " WHERE rowid IN (".implode(',',$linkedInvoices).")"; + if (count($linkedInvoices) > 0) + { + $sql= "SELECT rowid as facid, facnumber, total, datef as df, fk_user_author, fk_statut, paye"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture"; + $sql.= " WHERE rowid IN (".implode(',',$linkedInvoices).")"; - dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG); - $resql=$this->db->query($sql); + dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG); + $resql=$this->db->query($sql); - if ($resql) - { - $tab_sqlobj=array(); - $nump = $this->db->num_rows($resql); - for ($i = 0;$i < $nump;$i++) - { - $sqlobj = $this->db->fetch_object($resql); - $tab_sqlobj[] = $sqlobj; - } - $this->db->free($resql); + if ($resql) + { + $tab_sqlobj=array(); + $nump = $this->db->num_rows($resql); + for ($i = 0;$i < $nump;$i++) + { + $sqlobj = $this->db->fetch_object($resql); + $tab_sqlobj[] = $sqlobj; + } + $this->db->free($resql); - $nump = count($tab_sqlobj); + $nump = count($tab_sqlobj); - if ($nump) - { - $i = 0; - while ($i < $nump) - { - $obj = array_shift($tab_sqlobj); + if ($nump) + { + $i = 0; + while ($i < $nump) + { + $obj = array_shift($tab_sqlobj); - $ga[$i] = $obj; + $ga[$i] = $obj; - $i++; - } - } - return $ga; - } - else - { - return -1; - } - } - else return $ga; - } + $i++; + } + } + return $ga; + } + else + { + return -1; + } + } + else return $ga; + } - /** - * Delete proposal - * - * @param User $user Object user that delete - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int 1 if ok, otherwise if error - */ - function delete($user, $notrigger=0) - { - global $conf; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + /** + * Delete proposal + * + * @param User $user Object user that delete + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int 1 if ok, otherwise if error + */ + function delete($user, $notrigger=0) + { + global $conf; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error=0; + $error=0; - $this->db->begin(); + $this->db->begin(); - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('PROPAL_DELETE',$user); - if ($result < 0) { $error++; } - // End call triggers - } + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('PROPAL_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers + } - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal = ".$this->id; - if ($this->db->query($sql)) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { - // Delete linked object - $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal = ".$this->id; + if ($this->db->query($sql)) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE rowid = ".$this->id; + if ($this->db->query($sql)) + { + // Delete linked object + $res = $this->deleteObjectLinked(); + if ($res < 0) $error++; - // Delete linked contacts - $res = $this->delete_linked_contact(); - if ($res < 0) $error++; + // Delete linked contacts + $res = $this->delete_linked_contact(); + if ($res < 0) $error++; - if (! $error) - { - // We remove directory - $ref = dol_sanitizeFileName($this->ref); - if ($conf->propal->dir_output && !empty($this->ref)) - { - $dir = $conf->propal->dir_output . "/" . $ref ; - $file = $dir . "/" . $ref . ".pdf"; - if (file_exists($file)) - { - dol_delete_preview($this); + if (! $error) + { + // We remove directory + $ref = dol_sanitizeFileName($this->ref); + if ($conf->propal->dir_output && !empty($this->ref)) + { + $dir = $conf->propal->dir_output . "/" . $ref ; + $file = $dir . "/" . $ref . ".pdf"; + if (file_exists($file)) + { + dol_delete_preview($this); - if (! dol_delete_file($file,0,0,0,$this)) // For triggers - { - $this->error='ErrorFailToDeleteFile'; - $this->errors=array('ErrorFailToDeleteFile'); - $this->db->rollback(); - return 0; - } - } - if (file_exists($dir)) - { - $res=@dol_delete_dir_recursive($dir); - if (! $res) - { - $this->error='ErrorFailToDeleteDir'; - $this->errors=array('ErrorFailToDeleteDir'); - $this->db->rollback(); - return 0; - } - } - } - } + if (! dol_delete_file($file,0,0,0,$this)) // For triggers + { + $this->error='ErrorFailToDeleteFile'; + $this->errors=array('ErrorFailToDeleteFile'); + $this->db->rollback(); + return 0; + } + } + if (file_exists($dir)) + { + $res=@dol_delete_dir_recursive($dir); + if (! $res) + { + $this->error='ErrorFailToDeleteDir'; + $this->errors=array('ErrorFailToDeleteDir'); + $this->db->rollback(); + return 0; + } + } + } + } - // Removed extrafields - if (! $error) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->deleteExtraFields(); - if ($result < 0) - { - $error++; - $errorflag=-4; - dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); - } - } - } + // Removed extrafields + if (! $error) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $error++; + $errorflag=-4; + dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); + } + } + } - if (! $error) - { - dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return 0; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -3; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -2; - } - } - else - { - $this->db->rollback(); - return -1; - } - } + if (! $error) + { + dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return 0; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -3; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -2; + } + } + else + { + $this->db->rollback(); + return -1; + } + } - /** - * Change the delivery time - * - * @param int $availability_id Id of new delivery time - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int >0 if OK, <0 if KO - * @deprecated use set_availability - */ - function availability($availability_id, $notrigger=0) - { - global $user; + /** + * Change the delivery time + * + * @param int $availability_id Id of new delivery time + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int >0 if OK, <0 if KO + * @deprecated use set_availability + */ + function availability($availability_id, $notrigger=0) + { + global $user; - if ($this->statut >= self::STATUS_DRAFT) - { - $error=0; + if ($this->statut >= self::STATUS_DRAFT) + { + $error=0; - $this->db->begin(); + $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; - $sql .= ' SET fk_availability = '.$availability_id; - $sql .= ' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; + $sql .= ' SET fk_availability = '.$availability_id; + $sql .= ' WHERE rowid='.$this->id; - dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } + dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->availability_id = $availability_id; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->availability_id = $availability_id; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - $error_str='Propal status do not meet requirement '.$this->statut; - dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; - return -2; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + $error_str='Propal status do not meet requirement '.$this->statut; + dol_syslog(__METHOD__.$error_str, LOG_ERR); + $this->error=$error_str; + $this->errors[]= $this->error; + return -2; + } + } - /** - * Change source demand - * - * @param int $demand_reason_id Id of new source demand - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int >0 si ok, <0 si ko - * @deprecated use set_demand_reason - */ - function demand_reason($demand_reason_id, $notrigger=0) - { - if ($this->statut >= self::STATUS_DRAFT) - { - $error=0; + /** + * Change source demand + * + * @param int $demand_reason_id Id of new source demand + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int >0 si ok, <0 si ko + * @deprecated use set_demand_reason + */ + function demand_reason($demand_reason_id, $notrigger=0) + { + if ($this->statut >= self::STATUS_DRAFT) + { + $error=0; - $this->db->begin(); + $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; - $sql .= ' SET fk_input_reason = '.$demand_reason_id; - $sql .= ' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; + $sql .= ' SET fk_input_reason = '.$demand_reason_id; + $sql .= ' WHERE rowid='.$this->id; - dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } + dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->demand_reason_id = $demand_reason_id; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->demand_reason_id = $demand_reason_id; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - $error_str='Propal status do not meet requirement '.$this->statut; - dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; - return -2; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + $error_str='Propal status do not meet requirement '.$this->statut; + dol_syslog(__METHOD__.$error_str, LOG_ERR); + $this->error=$error_str; + $this->errors[]= $this->error; + return -2; + } + } - /** - * Object Proposal Information - * - * @param int $id Proposal id - * @return void - */ - function info($id) - { - $sql = "SELECT c.rowid, "; - $sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; - $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as c"; - $sql.= " WHERE c.rowid = ".$id; + /** + * Object Proposal Information + * + * @param int $id Proposal id + * @return void + */ + function info($id) + { + $sql = "SELECT c.rowid, "; + $sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; + $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; + $sql.= " FROM ".MAIN_DB_PREFIX."propal as c"; + $sql.= " WHERE c.rowid = ".$id; - $result = $this->db->query($sql); + $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; + $this->id = $obj->rowid; - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_validation = $this->db->jdate($obj->datev); - $this->date_cloture = $this->db->jdate($obj->dateo); + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_validation = $this->db->jdate($obj->datev); + $this->date_cloture = $this->db->jdate($obj->dateo); - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; - if ($obj->fk_user_valid) - { - $vuser = new User($this->db); - $vuser->fetch($obj->fk_user_valid); - $this->user_validation = $vuser; - } + if ($obj->fk_user_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } - if ($obj->fk_user_cloture) - { - $cluser = new User($this->db); - $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; - } + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } - } - $this->db->free($result); + } + $this->db->free($result); - } - else - { - dol_print_error($this->db); - } - } + } + else + { + dol_print_error($this->db); + } + } - /** - * Return label of status of proposal (draft, validated, ...) - * - * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto - * @return string Label - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->statut, $mode); - } + /** + * Return label of status of proposal (draft, validated, ...) + * + * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut, $mode); + } - /** - * Return label of a status (draft, validated, ...) - * - * @param int $statut id statut - * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto - * @return string Label - */ - function LibStatut($statut,$mode=1) - { + /** + * Return label of a status (draft, validated, ...) + * + * @param int $statut id statut + * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label + */ + function LibStatut($statut,$mode=1) + { global $langs; $langs->load("propal"); @@ -3045,436 +3014,436 @@ class Propal extends CommonObject if ($mode == 4) return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut]; if ($mode == 5) return ''.$this->labelstatut_short[$statut].' '.img_picto($this->labelstatut[$statut],$statuttrans); if ($mode == 6) return ''.$this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],$statuttrans); - } + } - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Object user - * @param int $mode "opened" for proposal to close, "signed" for proposal to invoice - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - function load_board($user,$mode) - { - global $conf, $langs; + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Object user + * @param int $mode "opened" for proposal to close, "signed" for proposal to invoice + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + function load_board($user,$mode) + { + global $conf, $langs; - $clause = " WHERE"; + $clause = " WHERE"; - $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; - if (!$user->rights->societe->client->voir && !$user->societe_id) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; - $sql.= " WHERE sc.fk_user = " .$user->id; - $clause = " AND"; - } - $sql.= $clause." p.entity IN (".getEntity('propal').")"; - if ($mode == 'opened') $sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED; - if ($mode == 'signed') $sql.= " AND p.fk_statut = ".self::STATUS_SIGNED; - if ($user->societe_id) $sql.= " AND p.fk_soc = ".$user->societe_id; - - $resql=$this->db->query($sql); - if ($resql) - { - $langs->load("propal"); - $now=dol_now(); - - if ($mode == 'opened') { - $delay_warning=$conf->propal->cloture->warning_delay; - $statut = self::STATUS_VALIDATED; - $label = $langs->trans("PropalsToClose"); - } - if ($mode == 'signed') { - $delay_warning=$conf->propal->facturation->warning_delay; - $statut = self::STATUS_SIGNED; - $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered - } - - $response = new WorkboardResponse(); - $response->warning_delay = $delay_warning/60/60/24; - $response->label = $label; - $response->url = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals'; - $response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc'; - $response->img = img_object('',"propal"); - - // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) - { - $response->nbtodo++; - if ($mode == 'opened') - { - $datelimit = $this->db->jdate($obj->datefin); - if ($datelimit < ($now - $delay_warning)) - { - $response->nbtodolate++; - } - } - // TODO Definir regle des propales a facturer en retard - // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++; - } - - return $response; - } - else - { - $this->error=$this->db->error(); - return -1; - } - } - - - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - function initAsSpecimen() - { - global $langs; - - // Load array of products prodids - $num_prods = 0; - $prodids = array(); - $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."product"; - $sql.= " WHERE entity IN (".getEntity('product').")"; - $resql = $this->db->query($sql); - if ($resql) - { - $num_prods = $this->db->num_rows($resql); - $i = 0; - while ($i < $num_prods) - { - $i++; - $row = $this->db->fetch_row($resql); - $prodids[$i] = $row[0]; - } - } - - // Initialise parametres - $this->id=0; - $this->ref = 'SPECIMEN'; - $this->ref_client='NEMICEPS'; - $this->specimen=1; - $this->socid = 1; - $this->date = time(); - $this->fin_validite = $this->date+3600*24*30; - $this->cond_reglement_id = 1; - $this->cond_reglement_code = 'RECEP'; - $this->mode_reglement_id = 7; - $this->mode_reglement_code = 'CHQ'; - $this->availability_id = 1; - $this->availability_code = 'AV_NOW'; - $this->demand_reason_id = 1; - $this->demand_reason_code = 'SRC_00'; - $this->note_public='This is a comment (public)'; - $this->note_private='This is a comment (private)'; - // Lines - $nbp = 5; - $xnbp = 0; - while ($xnbp < $nbp) - { - $line=new PropaleLigne($this->db); - $line->desc=$langs->trans("Description")." ".$xnbp; - $line->qty=1; - $line->subprice=100; - $line->price=100; - $line->tva_tx=20; - $line->localtax1_tx=0; - $line->localtax2_tx=0; - if ($xnbp == 2) - { - $line->total_ht=50; - $line->total_ttc=60; - $line->total_tva=10; - $line->remise_percent=50; - } - else - { - $line->total_ht=100; - $line->total_ttc=120; - $line->total_tva=20; - $line->remise_percent=00; - } - - if ($num_prods > 0) - { - $prodid = mt_rand(1, $num_prods); - $line->fk_product=$prodids[$prodid]; - $line->product_ref='SPECIMEN'; - } - - $this->lines[$xnbp]=$line; - - $this->total_ht += $line->total_ht; - $this->total_tva += $line->total_tva; - $this->total_ttc += $line->total_ttc; - - $xnbp++; - } - } - - /** - * Charge indicateurs this->nb de tableau de bord - * - * @return int <0 if ko, >0 if ok - */ - function load_state_board() - { - global $user; - - $this->nb=array(); - $clause = "WHERE"; - - $sql = "SELECT count(p.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->societe_id) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; - $sql.= " WHERE sc.fk_user = " .$user->id; - $clause = "AND"; - } - $sql.= " ".$clause." p.entity IN (".getEntity('propal').")"; - - $resql=$this->db->query($sql); - if ($resql) - { - // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) - { - $this->nb["proposals"]=$obj->nb; - } - $this->db->free($resql); - return 1; - } - else - { - dol_print_error($this->db); - $this->error=$this->db->error(); - return -1; - } - } - - - /** - * Returns the reference to the following non used Proposal used depending on the active numbering module - * defined into PROPALE_ADDON - * - * @param Societe $soc Object thirdparty - * @return string Reference libre pour la propale - */ - function getNextNumRef($soc) - { - global $conf,$langs; - $langs->load("propal"); - - if (! empty($conf->global->PROPALE_ADDON)) - { - $mybool=false; - - $file = $conf->global->PROPALE_ADDON.".php"; - $classname = $conf->global->PROPALE_ADDON; - - // Include file with class - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) { - - $dir = dol_buildpath($reldir."core/modules/propale/"); - - // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; - } - - if (! $mybool) - { - dol_print_error('',"Failed to include file ".$file); - return ''; - } - - $obj = new $classname(); - $numref = ""; - $numref = $obj->getNextValue($soc,$this); - - if ($numref != "") - { - return $numref; - } - else - { - $this->error=$obj->error; - //dol_print_error($db,"Propale::getNextNumRef ".$obj->error); - return ""; - } - } - else + $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin"; + $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; + if (!$user->rights->societe->client->voir && !$user->societe_id) { - $langs->load("errors"); - print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete"); - return ""; - } - } + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; + $sql.= " WHERE sc.fk_user = " .$user->id; + $clause = " AND"; + } + $sql.= $clause." p.entity IN (".getEntity('propal').")"; + if ($mode == 'opened') $sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED; + if ($mode == 'signed') $sql.= " AND p.fk_statut = ".self::STATUS_SIGNED; + if ($user->societe_id) $sql.= " AND p.fk_soc = ".$user->societe_id; - /** - * Return clicable link of object (with eventually picto) - * - * @param int $withpicto Add picto into link - * @param string $option Where point the link ('expedition', 'document', ...) - * @param string $get_params Parametres added to url - * @param int $notooltip 1=Disable tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string String with URL - */ - function getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1) - { - global $langs, $conf, $user; + $resql=$this->db->query($sql); + if ($resql) + { + $langs->load("propal"); + $now=dol_now(); - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if ($mode == 'opened') { + $delay_warning=$conf->propal->cloture->warning_delay; + $statut = self::STATUS_VALIDATED; + $label = $langs->trans("PropalsToClose"); + } + if ($mode == 'signed') { + $delay_warning=$conf->propal->facturation->warning_delay; + $statut = self::STATUS_SIGNED; + $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered + } - $result=''; - $label=''; - $url=''; + $response = new WorkboardResponse(); + $response->warning_delay = $delay_warning/60/60/24; + $response->label = $label; + $response->url = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals'; + $response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc'; + $response->img = img_object('',"propal"); - if ($user->rights->propal->lire) - { - $label = '' . $langs->trans("ShowPropal") . ''; - if (! empty($this->ref)) - $label.= '
    '.$langs->trans('Ref').': '.$this->ref; - if (! empty($this->ref_client)) - $label.= '
    '.$langs->trans('RefCustomer').': '.$this->ref_client; - if (! empty($this->total_ht)) - $label.= '
    ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_tva)) - $label.= '
    ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_ttc)) - $label.= '
    ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($option == '') { - $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; - } - if ($option == 'compta') { // deprecated - $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; - } - if ($option == 'expedition') { - $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params; - } - if ($option == 'document') { - $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params; - } + // This assignment in condition is not a bug. It allows walking the results. + while ($obj=$this->db->fetch_object($resql)) + { + $response->nbtodo++; + if ($mode == 'opened') + { + $datelimit = $this->db->jdate($obj->datefin); + if ($datelimit < ($now - $delay_warning)) + { + $response->nbtodolate++; + } + } + // TODO Definir regle des propales a facturer en retard + // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++; + } - if ($option != 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; - if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; - } - } + return $response; + } + else + { + $this->error=$this->db->error(); + return -1; + } + } - $linkclose=''; - if (empty($notooltip) && $user->rights->propal->lire) - { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label=$langs->trans("ShowPropal"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip"'; - } - $linkstart = ''; - $linkend=''; + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + global $langs; - if ($withpicto) - $result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) - $result.=' '; - $result.=$linkstart.$this->ref.$linkend; - return $result; - } + // Load array of products prodids + $num_prods = 0; + $prodids = array(); + $sql = "SELECT rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."product"; + $sql.= " WHERE entity IN (".getEntity('product').")"; + $resql = $this->db->query($sql); + if ($resql) + { + $num_prods = $this->db->num_rows($resql); + $i = 0; + while ($i < $num_prods) + { + $i++; + $row = $this->db->fetch_row($resql); + $prodids[$i] = $row[0]; + } + } - /** - * Retrieve an array of propal lines + // Initialise parametres + $this->id=0; + $this->ref = 'SPECIMEN'; + $this->ref_client='NEMICEPS'; + $this->specimen=1; + $this->socid = 1; + $this->date = time(); + $this->fin_validite = $this->date+3600*24*30; + $this->cond_reglement_id = 1; + $this->cond_reglement_code = 'RECEP'; + $this->mode_reglement_id = 7; + $this->mode_reglement_code = 'CHQ'; + $this->availability_id = 1; + $this->availability_code = 'AV_NOW'; + $this->demand_reason_id = 1; + $this->demand_reason_code = 'SRC_00'; + $this->note_public='This is a comment (public)'; + $this->note_private='This is a comment (private)'; + // Lines + $nbp = 5; + $xnbp = 0; + while ($xnbp < $nbp) + { + $line=new PropaleLigne($this->db); + $line->desc=$langs->trans("Description")." ".$xnbp; + $line->qty=1; + $line->subprice=100; + $line->price=100; + $line->tva_tx=20; + $line->localtax1_tx=0; + $line->localtax2_tx=0; + if ($xnbp == 2) + { + $line->total_ht=50; + $line->total_ttc=60; + $line->total_tva=10; + $line->remise_percent=50; + } + else + { + $line->total_ht=100; + $line->total_ttc=120; + $line->total_tva=20; + $line->remise_percent=00; + } + + if ($num_prods > 0) + { + $prodid = mt_rand(1, $num_prods); + $line->fk_product=$prodids[$prodid]; + $line->product_ref='SPECIMEN'; + } + + $this->lines[$xnbp]=$line; + + $this->total_ht += $line->total_ht; + $this->total_tva += $line->total_tva; + $this->total_ttc += $line->total_ttc; + + $xnbp++; + } + } + + /** + * Charge indicateurs this->nb de tableau de bord + * + * @return int <0 if ko, >0 if ok + */ + function load_state_board() + { + global $user; + + $this->nb=array(); + $clause = "WHERE"; + + $sql = "SELECT count(p.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$user->societe_id) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + $sql.= " WHERE sc.fk_user = " .$user->id; + $clause = "AND"; + } + $sql.= " ".$clause." p.entity IN (".getEntity('propal').")"; + + $resql=$this->db->query($sql); + if ($resql) + { + // This assignment in condition is not a bug. It allows walking the results. + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["proposals"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } + + + /** + * Returns the reference to the following non used Proposal used depending on the active numbering module + * defined into PROPALE_ADDON + * + * @param Societe $soc Object thirdparty + * @return string Reference libre pour la propale + */ + function getNextNumRef($soc) + { + global $conf,$langs; + $langs->load("propal"); + + if (! empty($conf->global->PROPALE_ADDON)) + { + $mybool=false; + + $file = $conf->global->PROPALE_ADDON.".php"; + $classname = $conf->global->PROPALE_ADDON; + + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + + $dir = dol_buildpath($reldir."core/modules/propale/"); + + // Load file with numbering class (if found) + $mybool|=@include_once $dir.$file; + } + + if (! $mybool) + { + dol_print_error('',"Failed to include file ".$file); + return ''; + } + + $obj = new $classname(); + $numref = ""; + $numref = $obj->getNextValue($soc,$this); + + if ($numref != "") + { + return $numref; + } + else + { + $this->error=$obj->error; + //dol_print_error($db,"Propale::getNextNumRef ".$obj->error); + return ""; + } + } + else + { + $langs->load("errors"); + print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete"); + return ""; + } + } + + /** + * Return clicable link of object (with eventually picto) + * + * @param int $withpicto Add picto into link + * @param string $option Where point the link ('expedition', 'document', ...) + * @param string $get_params Parametres added to url + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + function getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1) + { + global $langs, $conf, $user; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + + $result=''; + $label=''; + $url=''; + + if ($user->rights->propal->lire) + { + $label = '' . $langs->trans("ShowPropal") . ''; + if (! empty($this->ref)) + $label.= '
    '.$langs->trans('Ref').': '.$this->ref; + if (! empty($this->ref_client)) + $label.= '
    '.$langs->trans('RefCustomer').': '.$this->ref_client; + if (! empty($this->total_ht)) + $label.= '
    ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_tva)) + $label.= '
    ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_ttc)) + $label.= '
    ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + if ($option == '') { + $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; + } + if ($option == 'compta') { // deprecated + $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; + } + if ($option == 'expedition') { + $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params; + } + if ($option == 'document') { + $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params; + } + + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + } + + $linkclose=''; + if (empty($notooltip) && $user->rights->propal->lire) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowPropal"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; + } + + $linkstart = ''; + $linkend=''; + + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; + + return $result; + } + + /** + * Retrieve an array of propal lines * * @return int >0 if OK, <0 if KO - */ - function getLinesArray() - { - // TODO Duplicate with fetch_lines ? Wich one to keep ? + */ + function getLinesArray() + { + // TODO Duplicate with fetch_lines ? Wich one to keep ? - $this->lines = array(); + $this->lines = array(); - $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,'; - $sql.= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.localtax1_tx, pt.localtax2_tx, pt.localtax1_type, pt.localtax2_type, pt.remise_percent, pt.subprice, pt.info_bits,'; - $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.total_localtax1, pt.total_localtax2, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code,'; - $sql.= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,'; - $sql.= ' pt.fk_unit,'; - $sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.description as product_desc, p.tobatch as product_tobatch,'; - $sql.= ' p.entity,'; + $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,'; + $sql.= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.localtax1_tx, pt.localtax2_tx, pt.localtax1_type, pt.localtax2_type, pt.remise_percent, pt.subprice, pt.info_bits,'; + $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.total_localtax1, pt.total_localtax2, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code,'; + $sql.= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,'; + $sql.= ' pt.fk_unit,'; + $sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.description as product_desc, p.tobatch as product_tobatch,'; + $sql.= ' p.entity,'; $sql.= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; - $sql.= ' WHERE pt.fk_propal = '.$this->id; - $sql.= ' ORDER BY pt.rang ASC, pt.rowid'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; + $sql.= ' WHERE pt.fk_propal = '.$this->id; + $sql.= ' ORDER BY pt.rang ASC, pt.rowid'; - dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; + dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - $this->lines[$i] = new PropaleLigne($this->db); - $this->lines[$i]->id = $obj->rowid; // for backward compatibility - $this->lines[$i]->rowid = $obj->rowid; - $this->lines[$i]->label = $obj->custom_label; - $this->lines[$i]->desc = $obj->description; - $this->lines[$i]->description = $obj->description; - $this->lines[$i]->fk_product = $obj->fk_product; - $this->lines[$i]->ref = $obj->ref; - $this->lines[$i]->product_ref = $obj->ref; - $this->lines[$i]->entity = $obj->entity; // Product entity - $this->lines[$i]->product_label = $obj->product_label; - $this->lines[$i]->product_desc = $obj->product_desc; - $this->lines[$i]->product_tobatch = $obj->product_tobatch; - $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated - $this->lines[$i]->product_type = $obj->product_type; - $this->lines[$i]->qty = $obj->qty; - $this->lines[$i]->subprice = $obj->subprice; - $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; - $this->lines[$i]->remise_percent = $obj->remise_percent; + $this->lines[$i] = new PropaleLigne($this->db); + $this->lines[$i]->id = $obj->rowid; // for backward compatibility + $this->lines[$i]->rowid = $obj->rowid; + $this->lines[$i]->label = $obj->custom_label; + $this->lines[$i]->desc = $obj->description; + $this->lines[$i]->description = $obj->description; + $this->lines[$i]->fk_product = $obj->fk_product; + $this->lines[$i]->ref = $obj->ref; + $this->lines[$i]->product_ref = $obj->ref; + $this->lines[$i]->entity = $obj->entity; // Product entity + $this->lines[$i]->product_label = $obj->product_label; + $this->lines[$i]->product_desc = $obj->product_desc; + $this->lines[$i]->product_tobatch = $obj->product_tobatch; + $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated + $this->lines[$i]->product_type = $obj->product_type; + $this->lines[$i]->qty = $obj->qty; + $this->lines[$i]->subprice = $obj->subprice; + $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; + $this->lines[$i]->remise_percent = $obj->remise_percent; - $this->lines[$i]->vat_src_code = $obj->vat_src_code; - $this->lines[$i]->tva_tx = $obj->tva_tx; - $this->lines[$i]->localtax1_tx = $obj->localtax1_tx; - $this->lines[$i]->localtax2_tx = $obj->localtax2_tx; - $this->lines[$i]->localtax1_type = $obj->localtax1_type; - $this->lines[$i]->localtax2_type = $obj->localtax2_type; - $this->lines[$i]->info_bits = $obj->info_bits; - $this->lines[$i]->total_ht = $obj->total_ht; - $this->lines[$i]->total_tva = $obj->total_tva; - $this->lines[$i]->total_ttc = $obj->total_ttc; - $this->lines[$i]->total_localtax1 = $obj->total_localtax1; - $this->lines[$i]->total_localtax2 = $obj->total_localtax2; - $this->lines[$i]->fk_fournprice = $obj->fk_fournprice; + $this->lines[$i]->vat_src_code = $obj->vat_src_code; + $this->lines[$i]->tva_tx = $obj->tva_tx; + $this->lines[$i]->localtax1_tx = $obj->localtax1_tx; + $this->lines[$i]->localtax2_tx = $obj->localtax2_tx; + $this->lines[$i]->localtax1_type = $obj->localtax1_type; + $this->lines[$i]->localtax2_type = $obj->localtax2_type; + $this->lines[$i]->info_bits = $obj->info_bits; + $this->lines[$i]->total_ht = $obj->total_ht; + $this->lines[$i]->total_tva = $obj->total_tva; + $this->lines[$i]->total_ttc = $obj->total_ttc; + $this->lines[$i]->total_localtax1 = $obj->total_localtax1; + $this->lines[$i]->total_localtax2 = $obj->total_localtax2; + $this->lines[$i]->fk_fournprice = $obj->fk_fournprice; $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht); $this->lines[$i]->pa_ht = $marginInfos[0]; $this->lines[$i]->marge_tx = $marginInfos[1]; $this->lines[$i]->marque_tx = $marginInfos[2]; $this->lines[$i]->fk_parent_line = $obj->fk_parent_line; - $this->lines[$i]->special_code = $obj->special_code; - $this->lines[$i]->rang = $obj->rang; - $this->lines[$i]->date_start = $this->db->jdate($obj->date_start); - $this->lines[$i]->date_end = $this->db->jdate($obj->date_end); - $this->lines[$i]->fk_unit = $obj->fk_unit; + $this->lines[$i]->special_code = $obj->special_code; + $this->lines[$i]->rang = $obj->rang; + $this->lines[$i]->date_start = $this->db->jdate($obj->date_start); + $this->lines[$i]->date_end = $this->db->jdate($obj->date_end); + $this->lines[$i]->fk_unit = $obj->fk_unit; // Multicurrency $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency; @@ -3484,18 +3453,18 @@ class Propal extends CommonObject $this->lines[$i]->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->lines[$i]->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - $i++; - } - $this->db->free($resql); + $i++; + } + $this->db->free($resql); - return 1; - } - else - { - $this->error=$this->db->error(); - return -1; - } - } + return 1; + } + else + { + $this->error=$this->db->error(); + return -1; + } + } /** * Create a document onto disk according to template module. @@ -3553,16 +3522,16 @@ class Propal extends CommonObject */ class PropaleLigne extends CommonObjectLine { - public $element='propaldet'; - public $table_element='propaldet'; + public $element='propaldet'; + public $table_element='propaldet'; - var $oldline; + var $oldline; - // From llx_propaldet - var $fk_propal; - var $fk_parent_line; - var $desc; // Description ligne - var $fk_product; // Id produit predefini + // From llx_propaldet + var $fk_propal; + var $fk_parent_line; + var $desc; // Description ligne + var $fk_product; // Id produit predefini /** * @deprecated * @see product_type @@ -3573,51 +3542,51 @@ class PropaleLigne extends CommonObjectLine * @var int * @see Product::TYPE_PRODUCT, Product::TYPE_SERVICE */ - var $product_type = Product::TYPE_PRODUCT; + var $product_type = Product::TYPE_PRODUCT; - var $qty; - var $tva_tx; - var $subprice; - var $remise_percent; - var $fk_remise_except; + var $qty; + var $tva_tx; + var $subprice; + var $remise_percent; + var $fk_remise_except; - var $rang = 0; + var $rang = 0; var $fk_fournprice; var $pa_ht; var $marge_tx; var $marque_tx; - var $special_code; // Tag for special lines (exlusive tags) - // 1: frais de port - // 2: ecotaxe - // 3: option line (when qty = 0) + var $special_code; // Tag for special lines (exlusive tags) + // 1: frais de port + // 2: ecotaxe + // 3: option line (when qty = 0) - var $info_bits = 0; // Liste d'options cumulables: - // Bit 0: 0 si TVA normal - 1 si TVA NPR - // Bit 1: 0 ligne normale - 1 si ligne de remise fixe + var $info_bits = 0; // Liste d'options cumulables: + // Bit 0: 0 si TVA normal - 1 si TVA NPR + // Bit 1: 0 ligne normale - 1 si ligne de remise fixe - var $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne - var $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne - var $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne + var $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne + var $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne + var $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne /** * @deprecated * @see $remise_percent, $fk_remise_except */ - var $remise; + var $remise; /** * @deprecated * @see subprice */ - var $price; + var $price; - // From llx_product + // From llx_product /** * @deprecated * @see product_ref */ - var $ref; + var $ref; /** * Product reference * @var string @@ -3627,7 +3596,7 @@ class PropaleLigne extends CommonObjectLine * @deprecated * @see product_label */ - var $libelle; + var $libelle; /** * Product label * @var string @@ -3637,21 +3606,21 @@ class PropaleLigne extends CommonObjectLine * Product description * @var string */ - public $product_desc; + public $product_desc; - var $localtax1_tx; // Local tax 1 - var $localtax2_tx; // Local tax 2 - var $localtax1_type; // Local tax 1 type + var $localtax1_tx; // Local tax 1 + var $localtax2_tx; // Local tax 2 + var $localtax1_type; // Local tax 1 type var $localtax2_type; // Local tax 2 type - var $total_localtax1; // Line total local tax 1 - var $total_localtax2; // Line total local tax 2 + var $total_localtax1; // Line total local tax 1 + var $total_localtax2; // Line total local tax 2 - var $date_start; - var $date_end; + var $date_start; + var $date_end; - var $skip_update_total; // Skip update price total for special lines + var $skip_update_total; // Skip update price total for special lines - // Multicurrency + // Multicurrency var $fk_multicurrency; var $multicurrency_code; var $multicurrency_subprice; @@ -3659,22 +3628,22 @@ class PropaleLigne extends CommonObjectLine var $multicurrency_total_tva; var $multicurrency_total_ttc; - /** - * Class line Contructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db= $db; - } + /** + * Class line Contructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db= $db; + } - /** - * Retrieve the propal line object - * - * @param int $rowid Propal line id - * @return int <0 if KO, >0 if OK - */ + /** + * Retrieve the propal line object + * + * @param int $rowid Propal line id + * @return int <0 if KO, >0 if OK + */ function fetch($rowid) { $sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.vat_src_code, pd.tva_tx,'; @@ -3736,7 +3705,7 @@ class PropaleLigne extends CommonObjectLine $this->fk_unit = $objp->fk_unit; $this->date_start = $this->db->jdate($objp->date_start); - $this->date_end = $this->db->jdate($objp->date_end); + $this->date_end = $this->db->jdate($objp->date_end); // Multicurrency $this->fk_multicurrency = $objp->fk_multicurrency; @@ -3748,7 +3717,7 @@ class PropaleLigne extends CommonObjectLine $this->db->free($result); - return 1; + return 1; } else { @@ -3761,45 +3730,45 @@ class PropaleLigne extends CommonObjectLine } } - /** - * Insert object line propal in database - * - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function insert($notrigger=0) - { - global $conf,$user; + /** + * Insert object line propal in database + * + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function insert($notrigger=0) + { + global $conf,$user; - $error=0; + $error=0; - dol_syslog(get_class($this)."::insert rang=".$this->rang); + dol_syslog(get_class($this)."::insert rang=".$this->rang); - $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. + $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. - // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx=0; - if (empty($this->localtax1_tx)) $this->localtax1_tx=0; - if (empty($this->localtax2_tx)) $this->localtax2_tx=0; - if (empty($this->localtax1_type)) $this->localtax1_type=0; + // Clean parameters + if (empty($this->tva_tx)) $this->tva_tx=0; + if (empty($this->localtax1_tx)) $this->localtax1_tx=0; + if (empty($this->localtax2_tx)) $this->localtax2_tx=0; + if (empty($this->localtax1_type)) $this->localtax1_type=0; if (empty($this->localtax2_type)) $this->localtax2_type=0; - if (empty($this->total_localtax1)) $this->total_localtax1=0; - if (empty($this->total_localtax2)) $this->total_localtax2=0; - if (empty($this->rang)) $this->rang=0; - if (empty($this->remise)) $this->remise=0; - if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) $this->remise_percent=0; - if (empty($this->info_bits)) $this->info_bits=0; - if (empty($this->special_code)) $this->special_code=0; - if (empty($this->fk_parent_line)) $this->fk_parent_line=0; - if (empty($this->fk_fournprice)) $this->fk_fournprice=0; + if (empty($this->total_localtax1)) $this->total_localtax1=0; + if (empty($this->total_localtax2)) $this->total_localtax2=0; + if (empty($this->rang)) $this->rang=0; + if (empty($this->remise)) $this->remise=0; + if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) $this->remise_percent=0; + if (empty($this->info_bits)) $this->info_bits=0; + if (empty($this->special_code)) $this->special_code=0; + if (empty($this->fk_parent_line)) $this->fk_parent_line=0; + if (empty($this->fk_fournprice)) $this->fk_fournprice=0; if (! is_numeric($this->qty)) $this->qty = 0; - if (empty($this->pa_ht)) $this->pa_ht=0; - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0; + if (empty($this->pa_ht)) $this->pa_ht=0; + if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0; + if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0; + if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0; + if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0; - // if buy price not defined, define buyprice as configured in margin admin + // if buy price not defined, define buyprice as configured in margin admin if ($this->pa_ht == 0 && $pa_ht_isemptystring) { if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) @@ -3812,183 +3781,183 @@ class PropaleLigne extends CommonObjectLine } } - // Check parameters - if ($this->product_type < 0) return -1; + // Check parameters + if ($this->product_type < 0) return -1; - $this->db->begin(); + $this->db->begin(); - // Insert line into database - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet'; - $sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,'; + // Insert line into database + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet'; + $sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,'; $sql.= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; - $sql.= ' subprice, remise_percent, '; - $sql.= ' info_bits, '; - $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; - $sql.= ' fk_unit,'; - $sql.= ' date_start, date_end'; + $sql.= ' subprice, remise_percent, '; + $sql.= ' info_bits, '; + $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; + $sql.= ' fk_unit,'; + $sql.= ' date_start, date_end'; $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc)'; - $sql.= " VALUES (".$this->fk_propal.","; - $sql.= " ".($this->fk_parent_line>0?"'".$this->fk_parent_line."'":"null").","; - $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; - $sql.= " '".$this->db->escape($this->desc)."',"; - $sql.= " ".($this->fk_product?"'".$this->fk_product."'":"null").","; - $sql.= " '".$this->product_type."',"; - $sql.= " ".($this->fk_remise_except?"'".$this->fk_remise_except."'":"null").","; - $sql.= " ".price2num($this->qty).","; - $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->vat_src_code."'").","; - $sql.= " ".price2num($this->tva_tx).","; - $sql.= " ".price2num($this->localtax1_tx).","; - $sql.= " ".price2num($this->localtax2_tx).","; - $sql.= " '".$this->localtax1_type."',"; - $sql.= " '".$this->localtax2_type."',"; - $sql.= " ".($this->subprice?price2num($this->subprice):"null").","; - $sql.= " ".price2num($this->remise_percent).","; - $sql.= " ".(isset($this->info_bits)?"'".$this->info_bits."'":"null").","; - $sql.= " ".price2num($this->total_ht).","; - $sql.= " ".price2num($this->total_tva).","; - $sql.= " ".price2num($this->total_localtax1).","; - $sql.= " ".price2num($this->total_localtax2).","; - $sql.= " ".price2num($this->total_ttc).","; - $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->fk_fournprice."'":"null").","; - $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").","; - $sql.= ' '.$this->special_code.','; - $sql.= ' '.$this->rang.','; - $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).','; - $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").','; - $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); + $sql.= " VALUES (".$this->fk_propal.","; + $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").","; + $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; + $sql.= " '".$this->db->escape($this->desc)."',"; + $sql.= " ".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":"null").","; + $sql.= " '".$this->db->escape($this->product_type)."',"; + $sql.= " ".($this->fk_remise_except?"'".$this->db->escape($this->fk_remise_except)."'":"null").","; + $sql.= " ".price2num($this->qty).","; + $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").","; + $sql.= " ".price2num($this->tva_tx).","; + $sql.= " ".price2num($this->localtax1_tx).","; + $sql.= " ".price2num($this->localtax2_tx).","; + $sql.= " '".$this->db->escape($this->localtax1_type)."',"; + $sql.= " '".$this->db->escape($this->localtax2_type)."',"; + $sql.= " ".($this->subprice?price2num($this->subprice):"null").","; + $sql.= " ".price2num($this->remise_percent).","; + $sql.= " ".(isset($this->info_bits)?"'".$this->db->escape($this->info_bits)."'":"null").","; + $sql.= " ".price2num($this->total_ht).","; + $sql.= " ".price2num($this->total_tva).","; + $sql.= " ".price2num($this->total_localtax1).","; + $sql.= " ".price2num($this->total_localtax2).","; + $sql.= " ".price2num($this->total_ttc).","; + $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null").","; + $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").","; + $sql.= ' '.$this->special_code.','; + $sql.= ' '.$this->rang.','; + $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).','; + $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").','; + $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); $sql.= ", ".($this->fk_multicurrency > 0?$this->fk_multicurrency:'null'); $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; $sql.= ", ".$this->multicurrency_subprice; $sql.= ", ".$this->multicurrency_total_ht; $sql.= ", ".$this->multicurrency_total_tva; $sql.= ", ".$this->multicurrency_total_ttc; - $sql.= ')'; + $sql.= ')'; - dol_syslog(get_class($this).'::insert', LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet'); + dol_syslog(get_class($this).'::insert', LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet'); - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $this->id=$this->rowid; - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $this->id=$this->rowid; + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('LINEPROPAL_INSERT',$user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - // End call triggers - } + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINEPROPAL_INSERT',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // End call triggers + } - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error()." sql=".$sql; - $this->db->rollback(); - return -1; - } - } + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error()." sql=".$sql; + $this->db->rollback(); + return -1; + } + } - /** - * Delete line in database - * - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function delete($notrigger=0) - { - global $conf,$user; + /** + * Delete line in database + * + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function delete($notrigger=0) + { + global $conf,$user; - $error=0; - $this->db->begin(); + $error=0; + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid; - dol_syslog("PropaleLigne::delete", LOG_DEBUG); - if ($this->db->query($sql) ) - { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid; + dol_syslog("PropaleLigne::delete", LOG_DEBUG); + if ($this->db->query($sql) ) + { - // Remove extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used - { - $this->id=$this->rowid; - $result=$this->deleteExtraFields(); - if ($result < 0) - { - $error++; - dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); - } - } + // Remove extrafields + if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + { + $this->id=$this->rowid; + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); + } + } - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('LINEPROPAL_DELETE',$user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - } - // End call triggers + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINEPROPAL_DELETE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + } + // End call triggers - $this->db->commit(); + $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error()." sql=".$sql; - $this->db->rollback(); - return -1; - } - } + return 1; + } + else + { + $this->error=$this->db->error()." sql=".$sql; + $this->db->rollback(); + return -1; + } + } - /** - * Update propal line object into DB - * - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function update($notrigger=0) - { - global $conf,$user; + /** + * Update propal line object into DB + * + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function update($notrigger=0) + { + global $conf,$user; - $error=0; + $error=0; - $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. + $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. - // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx=0; - if (empty($this->localtax1_tx)) $this->localtax1_tx=0; - if (empty($this->localtax2_tx)) $this->localtax2_tx=0; - if (empty($this->total_localtax1)) $this->total_localtax1=0; - if (empty($this->total_localtax2)) $this->total_localtax2=0; + // Clean parameters + if (empty($this->tva_tx)) $this->tva_tx=0; + if (empty($this->localtax1_tx)) $this->localtax1_tx=0; + if (empty($this->localtax2_tx)) $this->localtax2_tx=0; + if (empty($this->total_localtax1)) $this->total_localtax1=0; + if (empty($this->total_localtax2)) $this->total_localtax2=0; if (empty($this->localtax1_type)) $this->localtax1_type=0; if (empty($this->localtax2_type)) $this->localtax2_type=0; - if (empty($this->marque_tx)) $this->marque_tx=0; - if (empty($this->marge_tx)) $this->marge_tx=0; - if (empty($this->price)) $this->price=0; // TODO A virer - if (empty($this->remise)) $this->remise=0; // TODO A virer - if (empty($this->remise_percent)) $this->remise_percent=0; - if (empty($this->info_bits)) $this->info_bits=0; - if (empty($this->special_code)) $this->special_code=0; - if (empty($this->fk_parent_line)) $this->fk_parent_line=0; - if (empty($this->fk_fournprice)) $this->fk_fournprice=0; - if (empty($this->subprice)) $this->subprice=0; + if (empty($this->marque_tx)) $this->marque_tx=0; + if (empty($this->marge_tx)) $this->marge_tx=0; + if (empty($this->price)) $this->price=0; // TODO A virer + if (empty($this->remise)) $this->remise=0; // TODO A virer + if (empty($this->remise_percent)) $this->remise_percent=0; + if (empty($this->info_bits)) $this->info_bits=0; + if (empty($this->special_code)) $this->special_code=0; + if (empty($this->fk_parent_line)) $this->fk_parent_line=0; + if (empty($this->fk_fournprice)) $this->fk_fournprice=0; + if (empty($this->subprice)) $this->subprice=0; if (empty($this->pa_ht)) $this->pa_ht=0; // if buy price not defined, define buyprice as configured in margin admin @@ -4004,119 +3973,119 @@ class PropaleLigne extends CommonObjectLine } } - $this->db->begin(); + $this->db->begin(); - // Mise a jour ligne en base - $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; - $sql.= " description='".$this->db->escape($this->desc)."'"; - $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); - $sql.= ", product_type=".$this->product_type; + // Mise a jour ligne en base + $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; + $sql.= " description='".$this->db->escape($this->desc)."'"; + $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); + $sql.= ", product_type=".$this->product_type; $sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'"; - $sql.= ", tva_tx='".price2num($this->tva_tx)."'"; - $sql.= ", localtax1_tx=".price2num($this->localtax1_tx); - $sql.= ", localtax2_tx=".price2num($this->localtax2_tx); + $sql.= ", tva_tx='".price2num($this->tva_tx)."'"; + $sql.= ", localtax1_tx=".price2num($this->localtax1_tx); + $sql.= ", localtax2_tx=".price2num($this->localtax2_tx); $sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; $sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql.= ", qty='".price2num($this->qty)."'"; - $sql.= ", subprice=".price2num($this->subprice).""; - $sql.= ", remise_percent=".price2num($this->remise_percent).""; - $sql.= ", price=".price2num($this->price).""; // TODO A virer - $sql.= ", remise=".price2num($this->remise).""; // TODO A virer - $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'"; - if (empty($this->skip_update_total)) - { - $sql.= ", total_ht=".price2num($this->total_ht).""; - $sql.= ", total_tva=".price2num($this->total_tva).""; - $sql.= ", total_ttc=".price2num($this->total_ttc).""; - $sql.= ", total_localtax1=".price2num($this->total_localtax1).""; - $sql.= ", total_localtax2=".price2num($this->total_localtax2).""; - } - $sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->fk_fournprice."'":"null"); + $sql.= ", qty='".price2num($this->qty)."'"; + $sql.= ", subprice=".price2num($this->subprice).""; + $sql.= ", remise_percent=".price2num($this->remise_percent).""; + $sql.= ", price=".price2num($this->price).""; // TODO A virer + $sql.= ", remise=".price2num($this->remise).""; // TODO A virer + $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'"; + if (empty($this->skip_update_total)) + { + $sql.= ", total_ht=".price2num($this->total_ht).""; + $sql.= ", total_tva=".price2num($this->total_tva).""; + $sql.= ", total_ttc=".price2num($this->total_ttc).""; + $sql.= ", total_localtax1=".price2num($this->total_localtax1).""; + $sql.= ", total_localtax2=".price2num($this->total_localtax2).""; + } + $sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null"); $sql.= ", buy_price_ht=".price2num($this->pa_ht); - if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code; - $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); - if (! empty($this->rang)) $sql.= ", rang=".$this->rang; - $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); - $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); - $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); + if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code; + $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); + if (! empty($this->rang)) $sql.= ", rang=".$this->rang; + $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); + $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); + $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); // Multicurrency $sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; - $sql.= " WHERE rowid = ".$this->rowid; + $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $this->id=$this->rowid; - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $this->id=$this->rowid; + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('LINEPROPAL_UPDATE',$user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - // End call triggers - } + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINEPROPAL_UPDATE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // End call triggers + } - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -2; - } - } + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -2; + } + } - /** - * Update DB line fields total_xxx - * Used by migration - * - * @return int <0 if ko, >0 if ok - */ - function update_total() - { - $this->db->begin(); + /** + * Update DB line fields total_xxx + * Used by migration + * + * @return int <0 if ko, >0 if ok + */ + function update_total() + { + $this->db->begin(); - // Mise a jour ligne en base - $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; - $sql.= " total_ht=".price2num($this->total_ht,'MT').""; - $sql.= ",total_tva=".price2num($this->total_tva,'MT').""; - $sql.= ",total_ttc=".price2num($this->total_ttc,'MT').""; - $sql.= " WHERE rowid = ".$this->rowid; + // Mise a jour ligne en base + $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; + $sql.= " total_ht=".price2num($this->total_ht,'MT').""; + $sql.= ",total_tva=".price2num($this->total_tva,'MT').""; + $sql.= ",total_ttc=".price2num($this->total_ttc,'MT').""; + $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog("PropaleLigne::update_total", LOG_DEBUG); + dol_syslog("PropaleLigne::update_total", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -2; - } - } + $resql=$this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -2; + } + } } diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index 480ad7f4fda..a7fe6b05201 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -73,6 +73,10 @@ $search_zip=GETPOST('search_zip','alpha'); $search_state=trim(GETPOST("search_state")); $search_country=GETPOST("search_country",'int'); $search_type_thirdparty=GETPOST("search_type_thirdparty",'int'); +$search_day=GETPOST("search_day","int"); +$search_month=GETPOST("search_month","int"); +$search_year=GETPOST("search_year","int"); + $viewstatut=GETPOST('viewstatut','alpha'); $optioncss = GETPOST('optioncss','alpha'); $object_statut=GETPOST('propal_statut','alpha'); @@ -80,9 +84,6 @@ $object_statut=GETPOST('propal_statut','alpha'); $sall=GETPOST('sall', 'alphanohtml'); $mesg=(GETPOST("msg") ? GETPOST("msg") : GETPOST("mesg")); -$search_day=GETPOST("search_day","int"); -$search_month=GETPOST("search_month","int"); -$search_year=GETPOST("search_year","int"); $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -95,8 +96,8 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield='p.ref'; if (! $sortorder) $sortorder='DESC'; -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$contextpage='proposallist'; +// Initialize technical object to manage context to save list fields +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'proposallist'; // Security check $module='propal'; @@ -123,42 +124,42 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'p.ref'=>'Ref', - 'p.ref_client'=>'CustomerRef', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'p.note_public'=>'NotePublic', + 'p.ref'=>'Ref', + 'p.ref_client'=>'CustomerRef', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'p.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["p.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'p.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'p.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1), - 'p.fin_validite'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), - 'p.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'p.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'p.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), - 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'p.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'p.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'p.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1), + 'p.fin_validite'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), + 'p.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'p.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'p.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), + 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'p.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } } $object = new Propal($db); // To be passed as parameter of executeHooks that need @@ -168,8 +169,8 @@ $object = new Propal($db); // To be passed as parameter of executeHooks that nee * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -180,40 +181,40 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_ref=''; - $search_refcustomer=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_login=''; - $search_product_category=''; - $search_town=''; + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_ref=''; + $search_refcustomer=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_login=''; + $search_product_category=''; + $search_town=''; $search_zip=""; - $search_state=""; + $search_state=""; $search_type=''; $search_country=''; $search_type_thirdparty=''; $search_year=''; - $search_month=''; - $search_day=''; + $search_month=''; + $search_day=''; $viewstatut=''; $object_statut=''; $toselect=''; - $search_array_options=array(); + $search_array_options=array(); } if ($object_statut != '') $viewstatut=$object_statut; if (empty($reshook)) { - $objectclass='Propal'; - $objectlabel='Proposals'; - $permtoread = $user->rights->propal->lire; - $permtodelete = $user->rights->propal->supprimer; - $uploaddir = $conf->propal->dir_output; + $objectclass='Propal'; + $objectlabel='Proposals'; + $permtoread = $user->rights->propal->lire; + $permtodelete = $user->rights->propal->supprimer; + $uploaddir = $conf->propal->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -237,7 +238,7 @@ llxHeader('',$langs->trans('Proposal'),$help_url); $sql = 'SELECT'; if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT'; -$sql.= ' s.rowid as socid, s.nom as name, s.town, s.zip, s.fk_pays, s.client, s.code_client, '; +$sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, '; $sql.= " typent.code as typent_code,"; $sql.= " state.code_departement as state_code, state.nom as state_name,"; $sql.= ' p.rowid, p.note_private, p.total_ht, p.tva as total_vat, p.total as total_ttc, p.localtax1, p.localtax2, p.ref, p.ref_client, p.fk_statut, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,'; @@ -265,8 +266,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr ON pr.rowid = p.fk_projet"; if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE p.fk_soc = s.rowid'; $sql.= ' AND p.entity IN ('.getEntity('propal').')'; @@ -287,7 +288,7 @@ if ($search_montant_ht != '') $sql.= natural_search("p.total_ht", $search_monta if ($search_montant_vat != '') $sql.= natural_search("p.tva", $search_montant_vat, 1); if ($search_montant_ttc != '') $sql.= natural_search("p.total", $search_montant_ttc, 1); if ($sall) { - $sql .= natural_search(array_keys($fieldstosearchall), $sall); + $sql .= natural_search(array_keys($fieldstosearchall), $sall); } if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$db->escape($search_product_category); if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; @@ -297,12 +298,12 @@ if ($viewstatut != '' && $viewstatut != '-1') } if ($search_month > 0) { - if ($search_year > 0 && empty($search_day)) - $sql.= " AND p.datep BETWEEN '".$db->idate(dol_get_first_day($search_year,$search_month,false))."' AND '".$db->idate(dol_get_last_day($search_year,$search_month,false))."'"; - else if ($search_year > 0 && ! empty($search_day)) - $sql.= " AND p.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month, $search_day, $search_year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month, $search_day, $search_year))."'"; - else - $sql.= " AND date_format(p.datep, '%m') = '".$db->escape($search_month)."'"; + if ($search_year > 0 && empty($search_day)) + $sql.= " AND p.datep BETWEEN '".$db->idate(dol_get_first_day($search_year,$search_month,false))."' AND '".$db->idate(dol_get_last_day($search_year,$search_month,false))."'"; + else if ($search_year > 0 && ! empty($search_day)) + $sql.= " AND p.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month, $search_day, $search_year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month, $search_day, $search_year))."'"; + else + $sql.= " AND date_format(p.datep, '%m') = '".$db->escape($search_month)."'"; } else if ($search_year > 0) { @@ -311,21 +312,21 @@ else if ($search_year > 0) if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$db->escape($search_sale); if ($search_user > 0) { - $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND c.element_id = p.rowid AND c.fk_socpeople = ".$db->escape($search_user); + $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND c.element_id = p.rowid AND c.fk_socpeople = ".$db->escape($search_user); } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -339,8 +340,8 @@ $sql.=', p.ref DESC'; $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1, $offset); @@ -360,7 +361,7 @@ if ($resql) } else { - $title = $langs->trans('ListOfProposals'); + $title = $langs->trans('ListOfProposals'); } $num = $db->num_rows($resql); @@ -368,14 +369,15 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); $param='&viewstatut='.urlencode($viewstatut); - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); if ($sall) $param.='&sall='.urlencode($sall); - if ($search_month) $param.='&search_month='.urlencode($search_month); - if ($search_year) $param.='&search_year='.urlencode($search_year); - if ($search_ref) $param.='&search_ref='.urlencode($search_ref); - if ($search_refcustomer) $param.='&search_refcustomer='.urlencode($search_refcustomer); - if ($search_societe) $param.='&search_societe='.urlencode($search_societe); + if ($search_day) $param.='&search_day='.urlencode($search_day); + if ($search_month) $param.='&search_month='.urlencode($search_month); + if ($search_year) $param.='&search_year='.urlencode($search_year); + if ($search_ref) $param.='&search_ref='.urlencode($search_ref); + if ($search_refcustomer) $param.='&search_refcustomer='.urlencode($search_refcustomer); + if ($search_societe) $param.='&search_societe='.urlencode($search_societe); if ($search_user > 0) $param.='&search_user='.urlencode($search_user); if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale); if ($search_montant_ht) $param.='&search_montant_ht='.urlencode($search_montant_ht); @@ -388,15 +390,15 @@ if ($resql) // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->propal->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); if ($massaction == 'presend') $arrayofmassactions=array(); @@ -404,119 +406,32 @@ if ($resql) // Lignes des champs de filtre print '
    '; - if ($optioncss != '') print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; print ''; print ''; print ''; + print ''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit); if ($massaction == 'presend') { - $langs->load("mails"); + $topicmail="SendSupplierProposalRef"; + $modelmail="supplier_proposal_send"; + $objecttmp=new Propal($db); + $trackid='ord'.$object->id; - if (! GETPOST('cancel')) - { - $objecttmp=new Propal($db); - $listofselectedid=array(); - $listofselectedthirdparties=array(); - $listofselectedref=array(); - foreach($arrayofselected as $toselectid) - { - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofselectedid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - $listofselectedthirdparties[$thirdpartyid]=$thirdpartyid; - $listofselectedref[$thirdpartyid][$toselectid]=$objecttmp->ref; - } - } - } - - print ''; - - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - - dol_fiche_head(null, '', ''); - - $topicmail="SendSupplierProposalRef"; - $modelmail="supplier_proposal_send"; - - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->withform=-1; - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 1)) // If bit 1 is set - { - $formmail->trackid='ord'.$object->id; - } - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'ord'.$object->id); - } - $formmail->withfrom=1; - $liste=$langs->trans("AllRecipientSelected"); - if (count($listofselectedthirdparties) == 1) - { - $liste=array(); - $thirdpartyid=array_shift($listofselectedthirdparties); - $soc=new Societe($db); - $soc->fetch($thirdpartyid); - foreach ($soc->thirdparty_and_contact_email_array(1) as $key=>$value) - { - $liste[$key]=$value; - } - $formmail->withtoreadonly=0; - } - else - { - $formmail->withtoreadonly=1; - } - $formmail->withto=$liste; - $formmail->withtofree=0; - $formmail->withtocc=1; - $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic=$langs->transnoentities($topicmail, '__REF__', '__REFCLIENT__'); - $formmail->withfile=$langs->trans("OnlyPDFattachmentSupported"); - $formmail->withbody=1; - $formmail->withdeliveryreceipt=1; - $formmail->withcancel=1; - // Tableau des substitutions - $formmail->substit['__REF__']='__REF__'; // We want to keep the tag - $formmail->substit['__SIGNATURE__']=$user->signature; - $formmail->substit['__REFCLIENT__']='__REFCLIENT__'; // We want to keep the tag - $formmail->substit['__PERSONALIZED__']=''; - $formmail->substit['__CONTACTCIVNAME__']=''; - - // Tableau des parametres complementaires du post - $formmail->param['action']=$action; - $formmail->param['models']=$modelmail; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['id']=join(',',$arrayofselected); - //$formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id; - - print $formmail->get_form(); - - dol_fiche_end(); + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } $i = 0; @@ -536,8 +451,8 @@ if ($resql) { $moreforfilter.='
    '; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter.='
    '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=''; } // If the user can view products if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) @@ -556,126 +471,126 @@ if ($resql) if (! empty($moreforfilter)) { - print '
    '; - print $moreforfilter; - print '
    '; + print '
    '; + print $moreforfilter; + print '
    '; } - $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); + $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 '
    '; print ''."\n"; print ''; if (! empty($arrayfields['p.ref']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.ref_client']['checked'])) { - print ''; } if (! empty($arrayfields['s.nom']['checked'])) { - print ''; } if (! empty($arrayfields['s.town']['checked'])) print ''; if (! empty($arrayfields['s.zip']['checked'])) print ''; // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print ''; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - } + if (! empty($arrayfields['state.nom']['checked'])) + { + print ''; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + } // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - } + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + } // Date if (! empty($arrayfields['p.date']['checked'])) { - print ''; + print ''; } // Date end if (! empty($arrayfields['p.fin_validite']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.total_ht']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['p.total_vat']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['p.total_ttc']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['u.login']['checked'])) { - // Author - print ''; + // Author + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -684,21 +599,21 @@ if ($resql) // Date creation if (! empty($arrayfields['p.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['p.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['p.fk_statut']['checked'])) { - print ''; + print ''; } // Action column print ''; if (! empty($arrayfields['p.ref']['checked'])) { - print '\n"; - if (! $i) $totalarray['nbfield']++; + print "\n"; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['p.ref_client']['checked'])) { - // Customer ref - print ''; - if (! $i) $totalarray['nbfield']++; + // Customer ref + print ''; + if (! $i) $totalarray['nbfield']++; } $companystatic->id=$obj->socid; $companystatic->name=$obj->name; $companystatic->client=$obj->client; $companystatic->code_client=$obj->code_client; + $companystatic->email=$obj->email; // Thirdparty if (! empty($arrayfields['s.nom']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Date proposal - if (! empty($arrayfields['p.date']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.date']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } // Date end validity - if (! empty($arrayfields['p.fin_validite']['checked'])) - { - if ($obj->dfv) - { - print ''; - } - else - { - print ''; - } - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.fin_validite']['checked'])) + { + if ($obj->dfv) + { + print ''; + } + else + { + print ''; + } + if (! $i) $totalarray['nbfield']++; + } - // Amount HT - if (! empty($arrayfields['p.total_ht']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['p.total_vat']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount TTC - if (! empty($arrayfields['p.total_ttc']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } + // Amount HT + if (! empty($arrayfields['p.total_ht']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['p.total_vat']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount TTC + if (! empty($arrayfields['p.total_ttc']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } - $userstatic->id=$obj->fk_user_author; + $userstatic->id=$obj->fk_user_author; $userstatic->login=$obj->login; - // Author - if (! empty($arrayfields['u.login']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } + // Author + if (! empty($arrayfields['u.login']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['p.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['p.fk_statut']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['p.fk_statut']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; @@ -985,7 +901,7 @@ if ($resql) } // Show total line - if (isset($totalarray['totalhtfield']) + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totalttcfield']) || isset($totalarray['totalamfield']) @@ -998,10 +914,10 @@ if ($resql) { $i++; if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''; - else print ''; - } + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } elseif ($totalarray['totalhtfield'] == $i) print ''; elseif ($totalarray['totalvatfield'] == $i) print ''; elseif ($totalarray['totalttcfield'] == $i) print ''; @@ -1017,27 +933,27 @@ if ($resql) print $hookmanager->resPrint; print '
    '; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; print ''; - print ''; + print ''; + print ''; print ''; - print ''; - print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print ''; + print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; - //print $langs->trans('Month').': '; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - //print ' '.$langs->trans('Year').': '; - $formother->select_year($search_year,'search_year',1, 20, 5); - print ''; + //print $langs->trans('Month').': '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + //print ' '.$langs->trans('Year').': '; + $formother->select_year($search_year,'search_year',1, 20, 5); + print '  '; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $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 ''; + $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 ''; - print ''; + print ''; - $formpropal->selectProposalStatus($viewstatut,1); - print ''; + $formpropal->selectProposalStatus($viewstatut,1); + print ''; @@ -730,19 +645,19 @@ if ($resql) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'],$_SERVER["PHP_SELF"],"p.fk_statut","",$param,'align="right"',$sortfield,$sortorder); @@ -756,228 +671,229 @@ if ($resql) { $obj = $db->fetch_object($resql); - $objectstatic->id=$obj->rowid; - $objectstatic->ref=$obj->ref; + $objectstatic->id=$obj->rowid; + $objectstatic->ref=$obj->ref; print '
    '; + print ''; - print ''; - // Picto + Ref - print ''; - // Warning - $warnornote=''; - if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); - if (! empty($obj->note_private)) - { - $warnornote.=($warnornote?' ':''); - $warnornote.= ''; - $warnornote.= ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; - $warnornote.= ''; - } - if ($warnornote) - { - print ''; - } - // Other picto tool - print '
    '; - print $objectstatic->getNomUrl(1, '', '', 0, 1); - print ''; - print $warnornote; - print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); - print '
    '; + print ''; + // Picto + Ref + print ''; + // Warning + $warnornote=''; + if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); + if (! empty($obj->note_private)) + { + $warnornote.=($warnornote?' ':''); + $warnornote.= ''; + $warnornote.= ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; + $warnornote.= ''; + } + if ($warnornote) + { + print ''; + } + // Other picto tool + print '
    '; + print $objectstatic->getNomUrl(1, '', '', 0, 1); + print ''; + print $warnornote; + print ''; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + print '
    '; - print "
    '; - print $obj->ref_client; - print ''; + print $obj->ref_client; + print ''; - print $companystatic->getNomUrl(1,'customer'); - print ''; + print $companystatic->getNomUrl(1,'customer'); + print ''; - print $obj->town; - print ''; - print $obj->zip; - print '".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; + print $obj->town; + print ''; + print $obj->zip; + print '".$obj->state_name."'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; - print dol_print_date($db->jdate($obj->dp), 'day'); - print "'; + print dol_print_date($db->jdate($obj->dp), 'day'); + print "'.dol_print_date($db->jdate($obj->dfv),'day'); - print ' '.dol_print_date($db->jdate($obj->dfv),'day'); + print ' '.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_ttc)."'.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_ttc)."'; - if ($userstatic->id) print $userstatic->getLoginUrl(1); - else print ' '; - print "'; + if ($userstatic->id) print $userstatic->getLoginUrl(1); + else print ' '; + print "'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$objectstatic->LibStatut($obj->fk_statut,5).''; - 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 dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$objectstatic->LibStatut($obj->fk_statut,5).''; + 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 '
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
    '."\n"; - print '
    '."\n"; + print '
    '."\n"; print '
    '."\n"; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->propal->lire; - $delallowed=$user->rights->propal->creer; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->propal->lire; + $delallowed=$user->rights->propal->creer; - print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); + print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); } else { - print '
    '.$langs->trans("ShowTempMassFilesArea").''; + print '
    '.$langs->trans("ShowTempMassFilesArea").''; } } diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php index bca371977a7..1ad4612d879 100644 --- a/htdocs/comm/remise.php +++ b/htdocs/comm/remise.php @@ -46,7 +46,7 @@ $backtopage = GETPOST('backtopage','alpha'); * Actions */ -if (GETPOST('cancel') && ! empty($backtopage)) +if (GETPOST('cancel','alpha') && ! empty($backtopage)) { header("Location: ".$backtopage); exit; diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 17e2feb4a84..0127b8f15be 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -49,7 +49,7 @@ if ($user->societe_id > 0) * Actions */ -if (GETPOST('cancel') && ! empty($backtopage)) +if (GETPOST('cancel','alpha') && ! empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -292,7 +292,7 @@ if ($socid > 0) print $form->load_tva('tva_tx',GETPOST('tva_tx'),$mysoc,$object); print '
    '.$langs->trans("NoteReason").'
    "; } diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 374ec0477fe..238b677395e 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -118,16 +118,11 @@ if (empty($reshook)) { if ($cancel) { - if ($action != 'addlink' && $action != 'updateline') + if (! empty($backtopage)) { - $urltogo=$backtopage?$backtopage:dol_buildpath('/commande/list.php',1); - header("Location: ".$urltogo); + header("Location: ".$backtopage); exit; } - if ($id > 0 || ! empty($ref)) { - $ret = $object->fetch($id,$ref); - $object->fetch_thirdparty(); - } $action=''; } @@ -175,7 +170,7 @@ if (empty($reshook)) $result = $object->set_reopen($user); if ($result > 0) { - setEventMessages($langs->trans('OrderReopened', $object->ref), null); + setEventMessages($langs->trans('OrderReopened', $object->ref), null); } else { @@ -261,20 +256,20 @@ if (empty($reshook)) $db->begin(); $object->date_commande = $datecommande; - $object->note_private = GETPOST('note_private'); - $object->note_public = GETPOST('note_public'); + $object->note_private = GETPOST('note_private','none'); + $object->note_public = GETPOST('note_public','none'); $object->source = GETPOST('source_id'); $object->fk_project = GETPOST('projectid'); $object->ref_client = GETPOST('ref_client'); $object->modelpdf = GETPOST('model'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->availability_id = GETPOST('availability_id'); $object->demand_reason_id = GETPOST('demand_reason_id'); $object->date_livraison = $datelivraison; - $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); - $object->warehouse_id = GETPOST('warehouse_id', 'int'); + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); + $object->warehouse_id = GETPOST('warehouse_id', 'int'); $object->fk_delivery_address = GETPOST('fk_address'); $object->contactid = GETPOST('contactid'); $object->fk_incoterms = GETPOST('incoterm_id', 'int'); @@ -284,8 +279,8 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form if (! $error) { - $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - if ($ret < 0) $error++; + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + if ($ret < 0) $error++; } // If creation from another object of another module (Example: origin=propal, originid=1) @@ -371,7 +366,7 @@ if (empty($reshook)) // Extrafields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if - // trigger used + // trigger used { $lines[$i]->fetch_optionals($lines[$i]->rowid); $array_options = $lines[$i]->array_options; @@ -428,7 +423,7 @@ if (empty($reshook)) $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook if ($reshook < 0) - $error++; + $error++; } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -496,10 +491,10 @@ if (empty($reshook)) } else if ($action == 'classifyunbilled' && $user->rights->commande->creer) { - $ret=$object->classifyUnBilled(); - if ($ret < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $ret=$object->classifyUnBilled(); + if ($ret < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Positionne ref commande client @@ -507,7 +502,7 @@ if (empty($reshook)) $result = $object->set_ref_client($user, GETPOST('ref_client')); if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } @@ -515,7 +510,7 @@ if (empty($reshook)) $result = $object->set_remise($user, GETPOST('remise')); if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } @@ -568,7 +563,7 @@ if (empty($reshook)) else if ($action == 'setavailability' && $user->rights->commande->creer) { $result = $object->availability(GETPOST('availability_id')); if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else if ($action == 'setdemandreason' && $user->rights->commande->creer) { @@ -601,36 +596,36 @@ if (empty($reshook)) // Set incoterm elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { - $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + { + $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } // bank account else if ($action == 'setbankaccount' && $user->rights->commande->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // shipping method else if ($action == 'setshippingmethod' && $user->rights->commande->creer) { - $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } - // warehouse - else if ($action == 'setwarehouse' && $user->rights->commande->creer) { - $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + // warehouse + else if ($action == 'setwarehouse' && $user->rights->commande->creer) { + $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else if ($action == 'setremisepercent' && $user->rights->commande->creer) { $result = $object->set_remise($user, GETPOST('remise_percent')); @@ -903,18 +898,18 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); } else { setEventMessages($object->error, $object->errors, 'errors'); } @@ -932,7 +927,7 @@ if (empty($reshook)) $date_end=''; $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - $description=dol_htmlcleanlastbr(GETPOST('product_desc')); + $description=dol_htmlcleanlastbr(GETPOST('product_desc','none')); $pu_ht=GETPOST('price_ht'); $vat_rate=(GETPOST('tva_tx')?GETPOST('tva_tx'):0); $pu_ht_devise = GETPOST('multicurrency_subprice'); @@ -1061,19 +1056,19 @@ if (empty($reshook)) } } - else if ($action == 'updateline' && $user->rights->commande->creer && GETPOST('cancel') == $langs->trans('Cancel')) { + else if ($action == 'updateline' && $user->rights->commande->creer && GETPOST('cancel','alpha') == $langs->trans('Cancel')) { header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $object->id); // Pour reaffichage de la fiche en cours d'edition exit(); } else if ($action == 'confirm_validate' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) ) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -1126,7 +1121,7 @@ if (empty($reshook)) else if ($action == 'confirm_modif' && $user->rights->commande->creer) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -1179,13 +1174,13 @@ if (empty($reshook)) } else if ($action == 'confirm_cancel' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) ) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -1215,11 +1210,6 @@ if (empty($reshook)) } } - // Actions to build doc - $upload_dir = $conf->commande->dir_output; - $permissioncreate = $user->rights->commande->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - if ($action == 'update_extras') { // Fill array 'array_options' with data from update form @@ -1233,10 +1223,12 @@ if (empty($reshook)) $hookmanager->initHooks(array('orderdao')); $parameters = array('id' => $object->id); $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by - // some hooks + // some hooks if (empty($reshook)) { $result = $object->insertExtraFields(); - if ($result < 0) { + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); $error++; } } else if ($reshook < 0) @@ -1256,13 +1248,18 @@ if (empty($reshook)) exit(); } - include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + // Actions to build doc + $upload_dir = $conf->commande->dir_output; + $permissioncreate = $user->rights->commande->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; // Actions to send emails $trigger_name='ORDER_SENTBYMAIL'; $paramname='id'; - $mode='emailfromorder'; + $autocopy='MAIN_MAIL_AUTOCOPY_ORDER_TO'; // used to know the automatic BCC to add $trackid='ord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; @@ -1398,10 +1395,10 @@ if ($action == 'create' && $user->rights->commande->creer) $soc = $objectsrc->thirdparty; $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); - $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); - $warehouse_id = (! empty($objectsrc->warehouse_id)?$objectsrc->warehouse_id:(! empty($soc->warehouse_id)?$soc->warehouse_id:0)); + $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); + $warehouse_id = (! empty($objectsrc->warehouse_id)?$objectsrc->warehouse_id:(! empty($soc->warehouse_id)?$soc->warehouse_id:0)); $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); @@ -1426,10 +1423,10 @@ if ($action == 'create' && $user->rights->commande->creer) { $cond_reglement_id = $soc->cond_reglement_id; $mode_reglement_id = $soc->mode_reglement_id; - $fk_account = $soc->fk_account; + $fk_account = $soc->fk_account; $availability_id = $soc->availability_id; - $shipping_method_id = $soc->shipping_method_id; - $warehouse_id = $soc->warehouse_id; + $shipping_method_id = $soc->shipping_method_id; + $warehouse_id = $soc->warehouse_id; $demand_reason_id = $soc->demand_reason_id; $remise_percent = $soc->remise_percent; $remise_absolue = 0; @@ -1441,7 +1438,6 @@ if ($action == 'create' && $user->rights->commande->creer) $note_private = $object->getDefaultCreateValueFor('note_private'); $note_public = $object->getDefaultCreateValueFor('note_public'); } - $absolute_discount=$soc->getAvailableDiscounts(); print '
    '; @@ -1468,7 +1464,7 @@ if ($action == 'create' && $user->rights->commande->creer) print ''; print ''; - // Client + // Thirdparty print ''; print '' . $langs->trans('Customer') . ''; if ($socid > 0) { @@ -1492,6 +1488,7 @@ if ($action == 'create' && $user->rights->commande->creer) }); '; } + print ' '.$langs->trans("AddThirdParty").''; print ''; } print '' . "\n"; @@ -1542,12 +1539,12 @@ if ($action == 'create' && $user->rights->commande->creer) $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id'); print ''; - // Bank Account + // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) { print '' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; } // Delivery delay @@ -1555,21 +1552,21 @@ if ($action == 'create' && $user->rights->commande->creer) $form->selectAvailabilityDelay($availability_id, 'availability_id', '', 1); print ''; - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print '' . $langs->trans('SendingMethod') . ''; - print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print '' . $langs->trans('SendingMethod') . ''; + print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); + print ''; + } - // Warehouse - if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct=new FormProduct($db); - print '' . $langs->trans('Warehouse') . ''; - print $formproduct->selectWarehouses($warehouse_id, 'warehouse_id', '', 1); - print ''; - } + // Warehouse + if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct=new FormProduct($db); + print '' . $langs->trans('Warehouse') . ''; + print $formproduct->selectWarehouses($warehouse_id, 'warehouse_id', '', 1); + print ''; + } // What trigger creation print '' . $langs->trans('Source') . ''; @@ -1595,22 +1592,22 @@ if ($action == 'create' && $user->rights->commande->creer) { print ''; print ''; - print ''; - $incoterm_id = GETPOST('incoterm_id'); - $incoterm_location = GETPOST('location_incoterms'); - if (empty($incoterm_id)) - { - $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); - $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); - } - print $form->select_incoterms($incoterm_id, $incoterm_location); + print ''; + $incoterm_id = GETPOST('incoterm_id'); + $incoterm_location = GETPOST('location_incoterms'); + if (empty($incoterm_id)) + { + $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); + $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); + } + print $form->select_incoterms($incoterm_id, $incoterm_location); print ''; } // Other attributes $parameters = array('objectsrc' => $objectsrc, 'socid'=>$socid); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields, 'edit'); } @@ -1628,8 +1625,8 @@ if ($action == 'create' && $user->rights->commande->creer) { print ''; print ''.fieldLabel('Currency','multicurrency_code').''; - print ''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print ''; } @@ -1691,6 +1688,8 @@ if ($action == 'create' && $user->rights->commande->creer) } print '' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . ''; + + // Amount print '' . $langs->trans('TotalHT') . '' . price($objectsrc->total_ht) . ''; print '' . $langs->trans('TotalVAT') . '' . price($objectsrc->total_tva) . ""; if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE @@ -1721,7 +1720,7 @@ if ($action == 'create' && $user->rights->commande->creer) print '
    '; print ''; print '     '; - print ''; + print ''; print '
    '; print '
    '; @@ -1923,69 +1922,69 @@ if ($action == 'create' && $user->rights->commande->creer) // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherOrders").')'; - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->commande->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
    '; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
    '; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - } - $morehtmlref.='
    '; + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->commande->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
    '; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; if ($soc->outstanding_limit) { - // Outstanding Bill - print ''; - print ''; + // Outstanding Bill + print ''; + print ''; } // Relative and absolute discounts if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final - // invoice + // invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; @@ -2042,7 +2041,7 @@ if ($action == 'create' && $user->rights->commande->creer) } else { print $object->date ? dol_print_date($object->date, 'day') : ' '; if ($object->hasDelay() && ! empty($object->date_livraison)) { - print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); + print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } print ''; @@ -2067,51 +2066,51 @@ if ($action == 'create' && $user->rights->commande->creer) } else { print $object->date_livraison ? dol_print_date($object->date_livraison, 'daytext') : ' '; if ($object->hasDelay() && ! empty($object->date_livraison)) { - print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); + print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } print ''; print ''; - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + print ''; + } - // Warehouse - if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct=new FormProduct($db); - print ''; - print ''; - } + // Warehouse + if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct=new FormProduct($db); + print ''; + print ''; + } // Terms of payment print '
    '; - print $langs->trans('OutstandingBill'); - print ''; - print price($soc->get_OutstandingBill()) . ' / '; - print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); - print '
    '; + print $langs->trans('OutstandingBill'); + print ''; + print price($soc->get_OutstandingBill()) . ' / '; + print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); + print '
    '; - print ''; - if ($action != 'editshippingmethod' && $user->rights->commande->creer) - print ''; - print '
    '; - print $langs->trans('SendingMethod'); - print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
    '; - print '
    '; - if ($action == 'editshippingmethod') { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); - } else { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); - } - print '
    '; + print ''; + if ($action != 'editshippingmethod' && $user->rights->commande->creer) + print ''; + print '
    '; + print $langs->trans('SendingMethod'); + print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
    '; + print '
    '; + if ($action == 'editshippingmethod') { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); + } else { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); + } + print '
    '; - print ''; - if ($action != 'editwarehouse' && $user->rights->commande->creer) - print ''; - print '
    '; - print $langs->trans('Warehouse'); - print 'id.'">'.img_edit($langs->trans('SetWarehouse'),1).'
    '; - print '
    '; - if ($action == 'editwarehouse') { - $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1); - } else { - $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none'); - } - print '
    '; + print ''; + if ($action != 'editwarehouse' && $user->rights->commande->creer) + print ''; + print '
    '; + print $langs->trans('Warehouse'); + print 'id.'">'.img_edit($langs->trans('SetWarehouse'),1).'
    '; + print '
    '; + if ($action == 'editwarehouse') { + $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1); + } else { + $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none'); + } + print '
    '; @@ -2178,9 +2177,9 @@ if ($action == 'create' && $user->rights->commande->creer) print '
    '; print ''; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { - if($action == 'actualizemulticurrencyrate') { - list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); - } + if($action == 'actualizemulticurrencyrate') { + list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); + } $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); @@ -2248,30 +2247,30 @@ if ($action == 'create' && $user->rights->commande->creer) $totalVolume=$tmparray['volume']; if ($totalWeight || $totalVolume) { - print ''.$langs->trans("CalculatedWeight").''; - print ''; - print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); - print ''; - print ''.$langs->trans("CalculatedVolume").''; - print ''; - print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); - print ''; + print ''.$langs->trans("CalculatedWeight").''; + print ''; + print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); + print ''; + print ''.$langs->trans("CalculatedVolume").''; + print ''; + print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); + print ''; } - // TODO How record was recorded OrderMode (llx_c_input_method) + // TODO How record was recorded OrderMode (llx_c_input_method) // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; - print '
    '; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->commande->creer) print ''.img_edit().''; - else print ' '; - print '
    '; - print ''; - print ''; + print '
    '; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->commande->creer) print ''.img_edit().''; + else print ' '; + print '
    '; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2280,27 +2279,27 @@ if ($action == 'create' && $user->rights->commande->creer) { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } - // Bank Account + // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) { - print ''; - print ''; - print '
    '; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $user->rights->commande->creer) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; - print ''; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print ''; - print ''; + print ''; + print ''; + print '
    '; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->commande->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; + print ''; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print ''; + print ''; } // Other attributes @@ -2317,20 +2316,20 @@ if ($action == 'create' && $user->rights->commande->creer) if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { - // Multicurrency Amount HT - print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; - print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount HT + print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; + print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount VAT - print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; - print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount VAT + print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; + print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount TTC - print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; - print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount TTC + print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; + print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; } // Total HT @@ -2362,7 +2361,7 @@ if ($action == 'create' && $user->rights->commande->creer) // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } @@ -2400,7 +2399,7 @@ if ($action == 'create' && $user->rights->commande->creer) include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
    '; + print '
    '; print ''; // Show object lines @@ -2426,7 +2425,7 @@ if ($action == 'create' && $user->rights->commande->creer) } } print '
    '; - print '
    '; + print '
    '; print "\n"; @@ -2440,7 +2439,7 @@ if ($action == 'create' && $user->rights->commande->creer) $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { // Send if ($object->statut > Commande::STATUS_DRAFT) { @@ -2450,10 +2449,10 @@ if ($action == 'create' && $user->rights->commande->creer) print ''; } - // Valid + // Valid if ($object->statut == Commande::STATUS_DRAFT && $object->total_ttc >= 0 && $numlines > 0 && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) ) { print ''; @@ -2464,8 +2463,8 @@ if ($action == 'create' && $user->rights->commande->creer) } // Create event if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a - // "workflow" action so should appears somewhere else on - // page. + // "workflow" action so should appears somewhere else on + // page. { print '' . $langs->trans("AddAction") . ''; } @@ -2484,12 +2483,12 @@ if ($action == 'create' && $user->rights->commande->creer) } // Create contract - if ($conf->contrat->enabled && ($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_ACCEPTED || $object->statut == Commande::STATUS_CLOSED)) { - $langs->load("contracts"); + if ($conf->contrat->enabled && ($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS || $object->statut == Commande::STATUS_CLOSED)) { + $langs->load("contracts"); - if ($user->rights->contrat->creer) { - print ''; - } + if ($user->rights->contrat->creer) { + print ''; + } } // Ship @@ -2517,7 +2516,7 @@ if ($action == 'create' && $user->rights->commande->creer) } // Set to shipped - if (($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_ACCEPTED) && $user->rights->commande->cloturer) { + if (($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS) && $user->rights->commande->cloturer) { print ''; } @@ -2532,9 +2531,9 @@ if ($action == 'create' && $user->rights->commande->creer) } } if ($object->statut > Commande::STATUS_DRAFT && $object->billed) { - if ($user->rights->commande->creer && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { - print ''; - } + if ($user->rights->commande->creer && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { + print ''; + } } // Clone if ($user->rights->commande->creer) { @@ -2543,8 +2542,8 @@ if ($action == 'create' && $user->rights->commande->creer) // Cancel order if ($object->statut == Commande::STATUS_VALIDATED && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->cloturer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->annuler))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->cloturer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->annuler))) ) { print ''; @@ -2585,145 +2584,38 @@ if ($action == 'create' && $user->rights->commande->creer) $linktoelem = $form->showLinkToObjectBlock($object, null, array('order')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show online signature link + $useonlinepayment = $conf->global->ORDER_SHOW_ONLINE_PAYMENT_ON_ORDER; + if ($object->statut != Commande::STATUS_DRAFT && $useonlinepayment) + { + print '
    '; + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + print showOnlinePaymentUrl('order', $object->ref).'
    '; + } + + if ($object->statut != Commande::STATUS_DRAFT && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) + { + print '
    '."\n"; + print showDirectDownloadLink($object).'
    '; + } 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, 'order', $socid); + $somethingshown = $formactions->showactions($object, 'order', $socid, 1); print '
    '; } - /* - * Action presend - */ - if ($action == 'presend') - { - $object->fetch_projet(); + // Presend form + $modelmail='order_send'; + $defaulttopic='SendOrderRef'; + $diroutput = $conf->commande->dir_output; + $trackid = 'ord'.$object->id; - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($conf->commande->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - - if (!empty($newlang)) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($newlang); - $outputlangs->load('commercial'); - } - - // Show email form - - // By default if $action=='presend' - $titreform='SendOrderByMail'; - $topicmail=''; - if (empty($object->ref_client)) { - $topicmail = $outputlangs->trans('SendOrderRef', '__ORDERREF__'); - } else if (! empty($object->ref_client)) { - $topicmail = $outputlangs->trans('SendOrderRef', '__ORDERREF__ (__REFCLIENT__)'); - } - $action='send'; - $modelmail='order_send'; - - // Build document if it not exists - if (! $file || ! is_readable($file)) { - $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) { - dol_print_error($db, $object->error, $object->errors); - exit(); - } - $fileparams = dol_most_recent_file($conf->commande->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - } - - print '
    '; - print '
    '; - print '
    '; - print load_fiche_titre($langs->trans($titreform)); - - dol_fiche_head(''); - - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - $formmail->trackid='ord'.$object->id; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'ord'.$object->id); - } - $formmail->withfrom = 1; - $liste = array(); - foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) - $liste [$key] = $value; - $formmail->withto = GETPOST('sendto') ? GETPOST('sendto') : $liste; - $formmail->withtocc = $liste; - $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic = $topicmail; - $formmail->withfile = 2; - $formmail->withbody = 1; - $formmail->withdeliveryreceipt = 1; - $formmail->withcancel = 1; - // Tableau des substitutions - $formmail->setSubstitFromObject($object); - $formmail->substit ['__ORDERREF__'] = $object->ref; - - $custcontact = ''; - $contactarr = array(); - $contactarr = $object->liste_contact(- 1, 'external'); - - if (is_array($contactarr) && count($contactarr) > 0) - { - foreach ($contactarr as $contact) - { - if ($contact['libelle'] == $langs->trans('TypeContact_commande_external_CUSTOMER')) { // TODO Use code and not label - $contactstatic = new Contact($db); - $contactstatic->fetch($contact ['id']); - $custcontact = $contactstatic->getFullName($langs, 1); - } - } - - if (! empty($custcontact)) { - $formmail->substit['__CONTACTCIVNAME__'] = $custcontact; - } - } - - // Tableau des parametres complementaires - $formmail->param['action'] = $action; - $formmail->param['models'] = $modelmail; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['orderid'] = $object->id; - $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; - - // Init list of files - if (GETPOST("mode") == 'init') { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file, basename($file), dol_mimetype($file)); - } - - // Show form - print $formmail->get_form(); - - dol_fiche_end(); - } + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } } diff --git a/htdocs/commande/class/api_deprecated_commande.class.php b/htdocs/commande/class/api_deprecated_commande.class.php index 11d3fe7260a..f494709e441 100644 --- a/htdocs/commande/class/api_deprecated_commande.class.php +++ b/htdocs/commande/class/api_deprecated_commande.class.php @@ -107,7 +107,7 @@ class CommandeApi extends DolibarrApi * @url GET /order/list * @return array Array of order objects */ - function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $mode=0, $societe = 0) { + function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode=0, $societe = 0) { global $db, $conf; $obj_ret = array(); @@ -316,7 +316,7 @@ class CommandeApi extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; @@ -389,7 +389,7 @@ class CommandeApi extends DolibarrApi * * @return int */ - function delLine($id, $lineid) { + function deleteLine($id, $lineid) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index f2c8de6da5b..e31aaa4e060 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -362,8 +362,10 @@ class Orders extends DolibarrApi * @url DELETE {id}/lines/{lineid} * * @return int + * @throws 401 + * @throws 404 */ - function delLine($id, $lineid) { + function deleteLine($id, $lineid) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } @@ -376,7 +378,8 @@ class Orders extends DolibarrApi if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $request_data = (object) $request_data; + + $request_data = (object) $request_data; $updateRes = $this->commande->deleteline(DolibarrApiAccess::$user,$lineid); if ($updateRes > 0) { return $this->get($id); @@ -498,6 +501,47 @@ class Orders extends DolibarrApi ); } + /** + * Close an order (Classify it as "Delivered") + * + * @param int $id Order ID + * @param int $notrigger Disabled triggers + * + * @url POST {id}/close + * + * @return array + */ + function close($id, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->commande->creer) { + throw new RestException(401); + } + $result = $this->commande->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Order not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->commande->cloture(DolibarrApiAccess::$user, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already closed'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Order: '.$this->commande->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Order closed (Ref='.$this->commande->ref.')' + ) + ); + } + + /** * Clean sensible object datas * @@ -509,6 +553,10 @@ class Orders extends DolibarrApi $object = parent::_cleanObjectDatas($object); unset($object->address); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); return $object; } diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index c5271c34744..52af47a83a5 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -46,7 +46,7 @@ class Commande extends CommonOrder public $table_element_line = 'commandedet'; public $class_element_line = 'OrderLine'; public $fk_element = 'fk_commande'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto = 'order'; /** @@ -169,15 +169,13 @@ class Commande extends CommonOrder */ const STATUS_VALIDATED = 1; /** - * Accepted (supplier orders) - */ - const STATUS_ACCEPTED = 2; - /** - * Shipment on process (customer orders) + * Shipment on process */ const STATUS_SHIPMENTONPROCESS = 2; + const STATUS_ACCEPTED = 2; // For backward compatibility. Use key STATUS_SHIPMENTONPROCESS instead. + /** - * Closed (Sent/Received, billed or not) + * Closed (Sent, billed or not) */ const STATUS_CLOSED = 3; @@ -559,9 +557,10 @@ class Commande extends CommonOrder * Close order * * @param User $user Objet user that close + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers * @return int <0 if KO, >0 if OK */ - function cloture($user) + function cloture($user, $notrigger=0) { global $conf; @@ -582,10 +581,13 @@ class Commande extends CommonOrder if ($this->db->query($sql)) { - // Call trigger - $result=$this->call_trigger('ORDER_CLOSE',$user); - if ($result < 0) $error++; - // End call triggers + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('ORDER_CLOSE',$user); + if ($result < 0) $error++; + // End call triggers + } if (! $error) { @@ -608,6 +610,7 @@ class Commande extends CommonOrder return -1; } } + return 0; } /** @@ -709,7 +712,7 @@ class Commande extends CommonOrder // $date_commande is deprecated $date = ($this->date_commande ? $this->date_commande : $this->date); - // Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate) + // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate) if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date); else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); if (empty($this->fk_multicurrency)) @@ -775,11 +778,11 @@ class Commande extends CommonOrder $sql.= ", ".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null"); $sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null"); $sql.= ", '".$this->db->escape($this->modelpdf)."'"; - $sql.= ", ".($this->cond_reglement_id>0?"'".$this->cond_reglement_id."'":"null"); - $sql.= ", ".($this->mode_reglement_id>0?"'".$this->mode_reglement_id."'":"null"); + $sql.= ", ".($this->cond_reglement_id>0?$this->cond_reglement_id:"null"); + $sql.= ", ".($this->mode_reglement_id>0?$this->mode_reglement_id:"null"); $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); - $sql.= ", ".($this->availability_id>0?"'".$this->availability_id."'":"null"); - $sql.= ", ".($this->demand_reason_id>0?"'".$this->demand_reason_id."'":"null"); + $sql.= ", ".($this->availability_id>0?$this->availability_id:"null"); + $sql.= ", ".($this->demand_reason_id>0?$this->demand_reason_id:"null"); $sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null"); $sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:'NULL'); $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); @@ -1006,7 +1009,7 @@ class Commande extends CommonOrder $this->db->begin(); - // get extrafields so they will be clone + // get lines so they will be clone foreach($this->lines as $line) $line->fetch_optionals($line->rowid); @@ -1084,11 +1087,12 @@ class Commande extends CommonOrder * Load an object from a proposal and create a new order into database * * @param Object $object Object source + * @param User $user User making creation * @return int <0 if KO, 0 if nothing done, 1 if OK */ - function createFromProposal($object) + function createFromProposal($object, User $user) { - global $conf,$user,$hookmanager; + global $conf, $hookmanager; dol_include_once('/core/class/extrafields.class.php'); @@ -1247,7 +1251,7 @@ class Commande extends CommonOrder { global $mysoc, $conf, $langs, $user; - dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit", LOG_DEBUG); + dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1555,7 +1559,7 @@ class Commande extends CommonOrder $sql.= ', c.fk_shipping_method'; $sql.= ', c.fk_warehouse'; $sql.= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed'; - $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams'; + $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.last_main_doc, c.fk_delivery_address, c.extraparams'; $sql.= ', c.fk_incoterms, c.location_incoterms'; $sql.= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc"; $sql.= ", i.libelle as libelle_incoterms"; @@ -1564,10 +1568,10 @@ class Commande extends CommonOrder $sql.= ', ca.code as availability_code, ca.label as availability_label'; $sql.= ', dr.code as demand_reason_code'; $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON (c.fk_cond_reglement = cr.rowid)'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON (c.fk_mode_reglement = p.id)'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON (c.fk_availability = ca.rowid)'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON (c.fk_input_reason = ca.rowid)'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term') . ')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement') . ')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid'; $sql.= " WHERE c.entity IN (".getEntity('commande').")"; if ($id) $sql.= " AND c.rowid=".$id; @@ -1610,6 +1614,7 @@ class Commande extends CommonOrder $this->note_public = $obj->note_public; $this->fk_project = $obj->fk_projet; $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement_libelle; @@ -1901,6 +1906,40 @@ class Commande extends CommonOrder return $nb; } + /** + * Count numbe rof shipments for this order + * + * @return int <0 if KO, Nb of shipment found if OK + */ + function getNbOfShipments() + { + $nb = 0; + + $sql = 'SELECT COUNT(DISTINCT ed.fk_expedition) as nb'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,'; + $sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd'; + $sql.= ' WHERE'; + $sql.= ' ed.fk_origin_line = cd.rowid'; + $sql.= ' AND cd.fk_commande =' .$this->id; + //print $sql; + + dol_syslog(get_class($this)."::getNbOfShipments", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) $nb = $obj->nb; + + $this->db->free($resql); + return $nb; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + /** * Load array this->expeditions of lines of shipments with nb of products sent for each order line * Note: For a dedicated shipment, the fetch_lines can be used to load the qty_asked and qty_shipped. This function is use to return qty_shipped cumulated for the order @@ -1927,18 +1966,18 @@ class Commande extends CommonOrder //print $sql; dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) + $resql = $this->db->query($sql); + if ($resql) { - $num = $this->db->num_rows($result); + $num = $this->db->num_rows($resql); $i = 0; while ($i < $num) { - $obj = $this->db->fetch_object($result); + $obj = $this->db->fetch_object($resql); $this->expeditions[$obj->rowid] = $obj->qty; $i++; } - $this->db->free(); + $this->db->free($resql); return $num; } else @@ -1946,7 +1985,6 @@ class Commande extends CommonOrder $this->error=$this->db->lasterror(); return -1; } - } /** @@ -1997,18 +2035,18 @@ class Commande extends CommonOrder $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; $sql.= " WHERE ps.fk_product IN (".join(',',$array_of_product).")"; $sql.= ' GROUP BY fk_product '; - $result = $this->db->query($sql); - if ($result) + $resql = $this->db->query($sql); + if ($resql) { - $num = $this->db->num_rows($result); + $num = $this->db->num_rows($resql); $i = 0; while ($i < $num) { - $obj = $this->db->fetch_object($result); + $obj = $this->db->fetch_object($resql); $this->stocks[$obj->fk_product] = $obj->total; $i++; } - $this->db->free(); + $this->db->free($resql); } } return 0; @@ -3055,48 +3093,6 @@ class Commande extends CommonOrder } } - /** - * Update value of extrafields on order - * - * @param User $user Object user that modify - * @return int <0 if ko, >0 if ok - */ - function update_extrafields($user) - { - global $hookmanager, $conf; - - $action='create'; - $error = 0; - - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('orderdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - else if ($reshook < 0) $error++; - - if (!$error) - { - return 1; - } - else - { - return -1; - } - - } - /** * Delete the customer order * @@ -3230,7 +3226,7 @@ class Commande extends CommonOrder } $sql.= $clause." c.entity IN (".getEntity('commande').")"; //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0"; - $sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_ACCEPTED.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected + $sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_SHIPMENTONPROCESS.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id; $resql=$this->db->query($sql); @@ -3315,7 +3311,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceled'); if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraft'); if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidated').$billedtext; - if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext; + if ($statut==self::STATUS_SHIPMENTONPROCESS) return $langs->trans('StatusOrderSentShort').$billedtext; if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBill'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered'); @@ -3325,7 +3321,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceledShort'); if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraftShort'); if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidatedShort').$billedtext; - if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext; + if ($statut==self::STATUS_SHIPMENTONPROCESS) return $langs->trans('StatusOrderSentShort').$billedtext; if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBillShort'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered'); @@ -3335,7 +3331,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceledShort'); if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraftShort'); if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated'),'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext; - if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext; + if ($statut==self::STATUS_SHIPMENTONPROCESS) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext; if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBillShort'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDeliveredShort'); @@ -3345,7 +3341,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5'); if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1'); - if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3'); + if ($statut==self::STATUS_SHIPMENTONPROCESS) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3'); if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6'); if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6'); @@ -3355,7 +3351,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceled'); if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraft'); if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext; - if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext; + if ($statut==self::STATUS_SHIPMENTONPROCESS) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext; if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBill'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDelivered'); @@ -3365,7 +3361,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return ''.$langs->trans('StatusOrderCanceledShort').' '.img_picto($langs->trans('StatusOrderCanceled'),'statut5'); if ($statut==self::STATUS_DRAFT) return ''.$langs->trans('StatusOrderDraftShort').' '.img_picto($langs->trans('StatusOrderDraft'),'statut0'); if ($statut==self::STATUS_VALIDATED) return ''.$langs->trans('StatusOrderValidatedShort').$billedtext.' '.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1'); - if ($statut==self::STATUS_ACCEPTED) return ''.$langs->trans('StatusOrderSentShort').$billedtext.' '.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3'); + if ($statut==self::STATUS_SHIPMENTONPROCESS) return ''.$langs->trans('StatusOrderSentShort').$billedtext.' '.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3'); if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderToBillShort').' '.img_picto($langs->trans('StatusOrderToBill'),'statut4'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderProcessedShort').$billedtext.' '.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6'); if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderDeliveredShort').' '.img_picto($langs->trans('StatusOrderDelivered'),'statut6'); @@ -3405,7 +3401,6 @@ class Commande extends CommonOrder if ($short) return $url; - $picto = 'order'; $label = ''; if ($user->rights->commande->lire) { @@ -3439,9 +3434,11 @@ class Commande extends CommonOrder $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - $result.=$linkstart.$this->ref.$linkend; + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; + return $result; } @@ -4000,18 +3997,18 @@ class OrderLine extends CommonOrderLine $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; $sql.= ')'; $sql.= " VALUES (".$this->fk_commande.","; - $sql.= " ".($this->fk_parent_line>0?"'".$this->fk_parent_line."'":"null").","; + $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").","; $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; $sql.= " '".$this->db->escape($this->desc)."',"; $sql.= " '".price2num($this->qty)."',"; - $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->vat_src_code."'").","; + $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").","; $sql.= " '".price2num($this->tva_tx)."',"; $sql.= " '".price2num($this->localtax1_tx)."',"; $sql.= " '".price2num($this->localtax2_tx)."',"; - $sql.= " '".$this->localtax1_type."',"; - $sql.= " '".$this->localtax2_type."',"; + $sql.= " '".$this->db->escape($this->localtax1_type)."',"; + $sql.= " '".$this->db->escape($this->localtax2_type)."',"; $sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").','; - $sql.= " '".$this->product_type."',"; + $sql.= " '".$this->db->escape($this->product_type)."',"; $sql.= " '".price2num($this->remise_percent)."',"; $sql.= " ".($this->subprice!=''?"'".price2num($this->subprice)."'":"null").","; $sql.= " ".($this->price!=''?"'".price2num($this->price)."'":"null").","; @@ -4021,7 +4018,7 @@ class OrderLine extends CommonOrderLine $sql.= ' '.$this->rang.','; $sql.= ' '.(! empty($this->fk_fournprice)?$this->fk_fournprice:"null").','; $sql.= ' '.price2num($this->pa_ht).','; - $sql.= " '".$this->info_bits."',"; + $sql.= " '".$this->db->escape($this->info_bits)."',"; $sql.= " '".price2num($this->total_ht)."',"; $sql.= " '".price2num($this->total_tva)."',"; $sql.= " '".price2num($this->total_localtax1)."',"; diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 86a5f463840..e007953bfe3 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -42,6 +42,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $langs->loadLangs(array("orders",'sendings','deliveries','companies','compta','bills')); @@ -82,6 +83,7 @@ $result = restrictedArea($user, 'commande', $id,''); $diroutputmassaction=$conf->commande->dir_output . '/temp/massgeneration/'.$user->id; +// Load variable for pagination $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); @@ -106,41 +108,42 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'c.ref'=>'Ref', - 'c.ref_client'=>'RefCustomerOrder', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'c.note_public'=>'NotePublic', + 'c.ref'=>'Ref', + 'c.ref_client'=>'RefCustomerOrder', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'c.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["c.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'c.ref_client'=>array('label'=>$langs->trans("RefCustomerOrder"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'c.date_commande'=>array('label'=>$langs->trans("OrderDateShort"), 'checked'=>1), - 'c.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)), - 'c.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'c.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'c.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'c.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), - 'c.facture'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) + 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'c.ref_client'=>array('label'=>$langs->trans("RefCustomerOrder"), 'checked'=>1), + 'p.project_ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>0, 'enabled'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'c.date_commande'=>array('label'=>$langs->trans("OrderDateShort"), 'checked'=>1), + 'c.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)), + 'c.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'c.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'c.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'c.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'c.facture'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } } @@ -149,8 +152,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -158,270 +161,272 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_ref_customer=''; - $search_company=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_total_ht=''; - $search_total_vat=''; - $search_total_ttc=''; - $search_orderyear=''; - $search_ordermonth=''; - $search_orderday=''; - $search_deliveryday=''; - $search_deliverymonth=''; - $search_deliveryyear=''; - $viewstatut=''; - $billed=''; - $toselect=''; - $search_array_options=array(); - } - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') - || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) - { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation - } + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=''; + $search_ref_customer=''; + $search_company=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $search_total_ht=''; + $search_total_vat=''; + $search_total_ttc=''; + $search_orderyear=''; + $search_ordermonth=''; + $search_orderday=''; + $search_deliveryday=''; + $search_deliverymonth=''; + $search_deliveryyear=''; + $search_project_ref=''; + $viewstatut=''; + $billed=''; + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } - // Mass actions - $objectclass='Commande'; - $objectlabel='Orders'; - $permtoread = $user->rights->commande->lire; - $permtodelete = $user->rights->commande->supprimer; - $uploaddir = $conf->commande->dir_output; + // Mass actions + $objectclass='Commande'; + $objectlabel='Orders'; + $permtoread = $user->rights->commande->lire; + $permtodelete = $user->rights->commande->supprimer; + $uploaddir = $conf->commande->dir_output; + $trigger_name='ORDER_SENTBYMAIL'; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // TODO Move this into mass action include - if ($massaction == 'confirm_createbills') { + if ($massaction == 'confirm_createbills') { - $orders = GETPOST('toselect','array'); - $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); - $validate_invoices = GETPOST('valdate_invoices', 'int'); + $orders = GETPOST('toselect','array'); + $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); + $validate_invoices = GETPOST('valdate_invoices', 'int'); - $TFact = array(); - $TFactThird = array(); + $TFact = array(); + $TFactThird = array(); - $nb_bills_created = 0; + $nb_bills_created = 0; - $db->begin(); + $db->begin(); - foreach($orders as $id_order) - { - $cmd = new Commande($db); - if ($cmd->fetch($id_order) <= 0) continue; + foreach($orders as $id_order) + { + $cmd = new Commande($db); + if ($cmd->fetch($id_order) <= 0) continue; - $object = new Facture($db); - if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. - else { + $object = new Facture($db); + if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. + else { - $object->socid = $cmd->socid; - $object->type = Facture::TYPE_STANDARD; - $object->cond_reglement_id = $cmd->cond_reglement_id; - $object->mode_reglement_id = $cmd->mode_reglement_id; - $object->fk_project = $cmd->fk_project; + $object->socid = $cmd->socid; + $object->type = Facture::TYPE_STANDARD; + $object->cond_reglement_id = $cmd->cond_reglement_id; + $object->mode_reglement_id = $cmd->mode_reglement_id; + $object->fk_project = $cmd->fk_project; - $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); - if (empty($datefacture)) - { - $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); - } + $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + if (empty($datefacture)) + { + $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); + } - $object->date = $datefacture; - $object->origin = 'commande'; - $object->origin_id = $id_order; + $object->date = $datefacture; + $object->origin = 'commande'; + $object->origin_id = $id_order; - $res = $object->create($user); + $res = $object->create($user); - if($res > 0) $nb_bills_created++; - } + if($res > 0) $nb_bills_created++; + } - if ($object->id > 0) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $id_order; - $sql.= ", '".$object->origin."'"; - $sql.= ", ".$object->id; - $sql.= ", '".$object->element."'"; - $sql.= ")"; + if ($object->id > 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; + $sql.= "fk_source"; + $sql.= ", sourcetype"; + $sql.= ", fk_target"; + $sql.= ", targettype"; + $sql.= ") VALUES ("; + $sql.= $id_order; + $sql.= ", '".$object->origin."'"; + $sql.= ", ".$object->id; + $sql.= ", '".$object->element."'"; + $sql.= ")"; - if (! $db->query($sql)) - { - $error++; - } + if (! $db->query($sql)) + { + $error++; + } - if (! $error) - { - $lines = $cmd->lines; - if (empty($lines) && method_exists($cmd, 'fetch_lines')) - { - $cmd->fetch_lines(); - $lines = $cmd->lines; - } + if (! $error) + { + $lines = $cmd->lines; + if (empty($lines) && method_exists($cmd, 'fetch_lines')) + { + $cmd->fetch_lines(); + $lines = $cmd->lines; + } - $fk_parent_line=0; - $num=count($lines); + $fk_parent_line=0; + $num=count($lines); - for ($i=0;$i<$num;$i++) - { - $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); - if ($lines[$i]->subprice < 0) - { - // Negative line, we create a discount line - $discount = new DiscountAbsolute($db); - $discount->fk_soc=$object->socid; - $discount->amount_ht=abs($lines[$i]->total_ht); - $discount->amount_tva=abs($lines[$i]->total_tva); - $discount->amount_ttc=abs($lines[$i]->total_ttc); - $discount->tva_tx=$lines[$i]->tva_tx; - $discount->fk_user=$user->id; - $discount->description=$desc; - $discountid=$discount->create($user); - if ($discountid > 0) - { - $result=$object->insert_discount($discountid); - //$result=$discount->link_to_invoice($lineid,$id); - } - else - { - setEventMessages($discount->error, $discount->errors, 'errors'); - $error++; - break; - } - } - else - { - // Positive line - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); - // Date start - $date_start=false; - if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; - //Date end - $date_end=false; - if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; - // Reset fk_parent_line for no child products and special product - if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) - { - $fk_parent_line = 0; - } - $result = $object->addline( - $desc, - $lines[$i]->subprice, - $lines[$i]->qty, - $lines[$i]->tva_tx, - $lines[$i]->localtax1_tx, - $lines[$i]->localtax2_tx, - $lines[$i]->fk_product, - $lines[$i]->remise_percent, - $date_start, - $date_end, - 0, - $lines[$i]->info_bits, - $lines[$i]->fk_remise_except, - 'HT', - 0, - $product_type, - $ii, - $lines[$i]->special_code, - $object->origin, - $lines[$i]->rowid, - $fk_parent_line, - $lines[$i]->fk_fournprice, - $lines[$i]->pa_ht, - $lines[$i]->label - ); - if ($result > 0) - { - $lineid=$result; - } - else - { - $lineid=0; - $error++; - break; - } - // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { - $fk_parent_line = $result; - } - } - } - } - } + for ($i=0;$i<$num;$i++) + { + $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); + if ($lines[$i]->subprice < 0) + { + // Negative line, we create a discount line + $discount = new DiscountAbsolute($db); + $discount->fk_soc=$object->socid; + $discount->amount_ht=abs($lines[$i]->total_ht); + $discount->amount_tva=abs($lines[$i]->total_tva); + $discount->amount_ttc=abs($lines[$i]->total_ttc); + $discount->tva_tx=$lines[$i]->tva_tx; + $discount->fk_user=$user->id; + $discount->description=$desc; + $discountid=$discount->create($user); + if ($discountid > 0) + { + $result=$object->insert_discount($discountid); + //$result=$discount->link_to_invoice($lineid,$id); + } + else + { + setEventMessages($discount->error, $discount->errors, 'errors'); + $error++; + break; + } + } + else + { + // Positive line + $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + // Date start + $date_start=false; + if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue; + if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; + if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; + //Date end + $date_end=false; + if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue; + if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; + if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; + // Reset fk_parent_line for no child products and special product + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) + { + $fk_parent_line = 0; + } + $result = $object->addline( + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $lines[$i]->tva_tx, + $lines[$i]->localtax1_tx, + $lines[$i]->localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $date_start, + $date_end, + 0, + $lines[$i]->info_bits, + $lines[$i]->fk_remise_except, + 'HT', + 0, + $product_type, + $ii, + $lines[$i]->special_code, + $object->origin, + $lines[$i]->rowid, + $fk_parent_line, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $lines[$i]->label + ); + if ($result > 0) + { + $lineid=$result; + } + else + { + $lineid=0; + $error++; + break; + } + // Defined the new fk_parent_line + if ($result > 0 && $lines[$i]->product_type == 9) + { + $fk_parent_line = $result; + } + } + } + } + } - //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. + //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. - if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; - else $TFact[$object->id] = $object; - } + if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; + else $TFact[$object->id] = $object; + } - // Build doc with all invoices - $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; - $toselect = array(); + // Build doc with all invoices + $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; + $toselect = array(); - if (! $error && $validate_invoices) - { - $massaction = $action = 'builddoc'; - foreach($TAllFact as &$object) - { - $result = $object->validate($user); - if ($result <= 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - break; - } + if (! $error && $validate_invoices) + { + $massaction = $action = 'builddoc'; + foreach($TAllFact as &$object) + { + $result = $object->validate($user); + if ($result <= 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + break; + } - $id = $object->id; // For builddoc action + $id = $object->id; // For builddoc action - // Fac builddoc - $donotredirect = 1; - $upload_dir = $conf->facture->dir_output; - $permissioncreate=$user->rights->facture->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - } + // Fac builddoc + $donotredirect = 1; + $upload_dir = $conf->facture->dir_output; + $permissioncreate=$user->rights->facture->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + } - $massaction = $action = 'confirm_createbills'; - } + $massaction = $action = 'confirm_createbills'; + } - if (! $error) - { - $db->commit(); - setEventMessage($langs->trans('BillCreated', $nb_bills_created)); - } - else - { - $db->rollback(); - $action='create'; - $_GET["origin"]=$_POST["origin"]; - $_GET["originid"]=$_POST["originid"]; - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } + if (! $error) + { + $db->commit(); + setEventMessage($langs->trans('BillCreated', $nb_bills_created)); + } + else + { + $db->rollback(); + $action='create'; + $_GET["origin"]=$_POST["origin"]; + $_GET["originid"]=$_POST["originid"]; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } } @@ -436,6 +441,7 @@ $formother = new FormOther($db); $formfile = new FormFile($db); $companystatic = new Societe($db); $formcompany=new FormCompany($db); +$projectstatic=new Project($db); $title=$langs->trans("Orders"); $help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; @@ -443,12 +449,13 @@ llxHeader('',$title,$help_url); $sql = 'SELECT'; if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT'; -$sql.= ' s.rowid as socid, s.nom as name, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; +$sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; $sql.= " typent.code as typent_code,"; $sql.= " state.code_departement as state_code, state.nom as state_name,"; $sql.= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_client,'; $sql.= ' c.date_valid, c.date_commande, c.note_private, c.date_livraison as date_delivery, c.fk_statut, c.facture as billed,'; -$sql.= ' c.date_creation as date_creation, c.tms as date_update'; +$sql.= ' c.date_creation as date_creation, c.tms as date_update,'; +$sql.= " p.rowid as project_id, p.ref as project_ref"; // Add fields from extrafields foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : ''); // Add fields from hooks @@ -463,12 +470,13 @@ $sql.= ', '.MAIN_DB_PREFIX.'commande as c'; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)"; if ($sall || $search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid=pd.fk_commande'; if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = c.fk_projet"; // We'll need this table joined to the select in order to filter by sale if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE c.fk_soc = s.rowid'; $sql.= ' AND c.entity IN ('.getEntity('commande').')'; @@ -504,29 +512,29 @@ if ($viewstatut <> '') } if ($search_ordermonth > 0) { - if ($search_orderyear > 0 && empty($search_orderday)) - $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,$search_ordermonth,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,$search_ordermonth,false))."'"; - else if ($search_orderyear > 0 && ! empty($search_orderday)) - $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_ordermonth, $search_orderday, $search_orderyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_ordermonth, $search_orderday, $search_orderyear))."'"; - else - $sql.= " AND date_format(c.date_commande, '%m') = '".$search_ordermonth."'"; + if ($search_orderyear > 0 && empty($search_orderday)) + $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,$search_ordermonth,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,$search_ordermonth,false))."'"; + else if ($search_orderyear > 0 && ! empty($search_orderday)) + $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_ordermonth, $search_orderday, $search_orderyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_ordermonth, $search_orderday, $search_orderyear))."'"; + else + $sql.= " AND date_format(c.date_commande, '%m') = '".$search_ordermonth."'"; } else if ($search_orderyear > 0) { - $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,12,false))."'"; + $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,12,false))."'"; } if ($search_deliverymonth > 0) { - if ($search_deliveryyear > 0 && empty($search_deliveryday)) - $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,$search_deliverymonth,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,$search_deliverymonth,false))."'"; - else if ($search_deliveryyear > 0 && ! empty($search_deliveryday)) - $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."'"; - else - $sql.= " AND date_format(c.date_livraison, '%m') = '".$search_deliverymonth."'"; + if ($search_deliveryyear > 0 && empty($search_deliveryday)) + $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,$search_deliverymonth,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,$search_deliverymonth,false))."'"; + else if ($search_deliveryyear > 0 && ! empty($search_deliveryday)) + $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."'"; + else + $sql.= " AND date_format(c.date_livraison, '%m') = '".$search_deliverymonth."'"; } else if ($search_deliveryyear > 0) { - $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,12,false))."'"; + $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,12,false))."'"; } if ($search_town) $sql.= natural_search('s.town', $search_town); if ($search_zip) $sql.= natural_search("s.zip",$search_zip); @@ -537,19 +545,20 @@ if ($search_company) $sql .= natural_search('s.nom', $search_company); if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; if ($search_total_ht != '') $sql.= natural_search('c.total_ht', $search_total_ht, 1); +if ($search_project_ref != '') $sql.= natural_search("p.ref",$search_project_ref); // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -605,7 +614,7 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $param.='&sall='.$sall; if ($socid > 0) $param.='&socid='.$socid; @@ -624,21 +633,22 @@ if ($resql) if ($search_total_ht != '') $param.='&search_total_ht='.$search_total_ht; if ($search_total_vat != '') $param.='&search_total_vat='.$search_total_vat; if ($search_total_ttc != '') $param.='&search_total_ttc='.$search_total_ttc; - if ($show_files) $param.='&show_files=' .$show_files; - if ($optioncss != '') $param.='&optioncss='.$optioncss; + if ($search_project_ref >= 0) $param.="&search_project_ref=".$search_project_ref; + if ($show_files) $param.='&show_files=' .$show_files; + if ($optioncss != '') $param.='&optioncss='.$optioncss; if ($billed != '') $param.='&billed='.$billed; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if ($user->rights->commande->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); @@ -647,114 +657,29 @@ if ($resql) // Lines of title fields print '
    '; - if ($optioncss != '') print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit); - // TODO Move this into an invluce if ($massaction == 'presend') { - $langs->load("mails"); + $topicmail="SendOrderRef"; + $modelmail="order_send"; + $objecttmp=new Commande($db); + $trackid='ord'.$object->id; - if (! GETPOST('cancel')) - { - $objecttmp=new Commande($db); - $listofselectedid=array(); - $listofselectedthirdparties=array(); - $listofselectedref=array(); - foreach($arrayofselected as $toselectid) - { - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofselectedid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - $listofselectedthirdparties[$thirdpartyid]=$thirdpartyid; - $listofselectedref[$thirdpartyid][$toselectid]=$objecttmp->ref; - } - } - } - - print ''; - - dol_fiche_head(null, '', ''); - - $topicmail="SendOrderRef"; - $modelmail="order_send"; - - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->withform=-1; - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 1)) // If bit 1 is set - { - $formmail->trackid='ord'.$object->id; - } - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'ord'.$object->id); - } - $formmail->withfrom=1; - $liste=$langs->trans("AllRecipientSelected"); - if (count($listofselectedthirdparties) == 1) - { - $liste=array(); - $thirdpartyid=array_shift($listofselectedthirdparties); - $soc=new Societe($db); - $soc->fetch($thirdpartyid); - foreach ($soc->thirdparty_and_contact_email_array(1) as $key=>$value) - { - $liste[$key]=$value; - } - $formmail->withtoreadonly=0; - } - else - { - $formmail->withtoreadonly=1; - } - $formmail->withto=$liste; - $formmail->withtofree=0; - $formmail->withtocc=1; - $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic=$langs->transnoentities($topicmail, '__REF__', '__REFCLIENT__'); - $formmail->withfile=$langs->trans("OnlyPDFattachmentSupported"); - $formmail->withbody=1; - $formmail->withdeliveryreceipt=1; - $formmail->withcancel=1; - // Tableau des substitutions - $formmail->substit['__REF__']='__REF__'; // We want to keep the tag - $formmail->substit['__SIGNATURE__']=$user->signature; - $formmail->substit['__REFCLIENT__']='__REFCLIENT__'; // We want to keep the tag - $formmail->substit['__PERSONALIZED__']=''; - $formmail->substit['__CONTACTCIVNAME__']=''; - - // Tableau des parametres complementaires du post - $formmail->param['action']=$action; - $formmail->param['models']=$modelmail; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['id']=join(',',$arrayofselected); - //$formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id; - - print $formmail->get_form(); - - dol_fiche_end(); + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; } - elseif ($massaction == 'createbills') + + if ($massaction == 'createbills') { //var_dump($_REQUEST); print ''; @@ -783,12 +708,12 @@ if ($resql) print ''; if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL)) { - print $form->selectyesno('valdate_invoices', 0, 1, 1); - print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; + print $form->selectyesno('valdate_invoices', 0, 1, 1); + print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; } else { - print $form->selectyesno('valdate_invoices', 0, 1); + print $form->selectyesno('valdate_invoices', 0, 1); } print ''; print ''; @@ -803,10 +728,10 @@ if ($resql) } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } $moreforfilter=''; @@ -824,7 +749,7 @@ if ($resql) { $moreforfilter.='
    '; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='
    '; } // If the user can view prospects other than his' @@ -846,37 +771,42 @@ if ($resql) { print '
    '; print $moreforfilter; - print '
    '; + print '
    '; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
    '; - print ''."\n"; + print '
    '; + print '
    '."\n"; print ''; // Ref if (! empty($arrayfields['c.ref']['checked'])) { - print ''; + print ''; } // Ref customer if (! empty($arrayfields['c.ref_client']['checked'])) { - print ''; + print ''; + } + // Project ref + if (! empty($arrayfields['p.project_ref']['checked'])) + { + print ''; } // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) { - print ''; + print ''; } // Town if (! empty($arrayfields['s.town']['checked'])) print ''; @@ -885,84 +815,84 @@ if ($resql) // State if (! empty($arrayfields['state.nom']['checked'])) { - print ''; + print ''; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; + print ''; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print ''; + print ''; } // Date order if (! empty($arrayfields['c.date_commande']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['c.date_delivery']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['c.total_ht']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['c.total_vat']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['c.total_ttc']['checked'])) { - // Amount - print ''; + // Amount + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -971,36 +901,36 @@ if ($resql) // Date creation if (! empty($arrayfields['c.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['c.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['c.fk_statut']['checked'])) { - print ''; + print ''; } // Status billed if (! empty($arrayfields['c.facture']['checked'])) { - print ''; + print ''; } // Action column print ''; - print "\n"; + print "\n"; // Fields title print ''; if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'],$_SERVER["PHP_SELF"],'c.ref','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['c.ref_client']['checked'])) print_liste_field_titre($arrayfields['c.ref_client']['label'],$_SERVER["PHP_SELF"],'c.ref_client','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['p.project_ref']['checked'])) print_liste_field_titre($arrayfields['p.project_ref']['label'],$_SERVER["PHP_SELF"],"p.ref","",$param,'',$sortfield,$sortorder); if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER["PHP_SELF"],'s.nom','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); @@ -1030,19 +961,19 @@ if ($resql) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'],$_SERVER["PHP_SELF"],"c.date_creation","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'],$_SERVER["PHP_SELF"],"c.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['c.fk_statut']['checked'])) print_liste_field_titre($arrayfields['c.fk_statut']['label'],$_SERVER["PHP_SELF"],"c.fk_statut","",$param,'align="right"',$sortfield,$sortorder); @@ -1052,351 +983,365 @@ if ($resql) $total=0; $subtotal=0; - $productstat_cache=array(); + $productstat_cache=array(); - $generic_commande = new Commande($db); - $generic_product = new Product($db); + $generic_commande = new Commande($db); + $generic_product = new Product($db); - $i=0; + $i=0; $totalarray=array(); - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); - print ''; + $notshippable=0; + $warning = 0; + $text_info=''; + $text_warning=''; + $nbprod=0; - $notshippable=0; - $warning = 0; - $text_info=''; - $text_warning=''; - $nbprod=0; + $companystatic->id=$obj->socid; + $companystatic->code_client = $obj->code_client; + $companystatic->name=$obj->name; + $companystatic->client=$obj->client; + $companystatic->email=$obj->email; - // Ref - if (! empty($arrayfields['c.ref']['checked'])) - { - print ''; + if (! $i) $totalarray['nbfield']++; + } // Ref customer if (! empty($arrayfields['c.ref_client']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } - $companystatic->id=$obj->socid; - $companystatic->code_client = $obj->code_client; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; + // Project + if (! empty($arrayfields['p.project_ref']['checked'])) + { + $projectstatic->id=$obj->project_id; + $projectstatic->ref=$obj->project_ref; + print ''; + if (! $i) $totalarray['nbfield']++; + } // Third party if (! empty($arrayfields['s.nom']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + // If module invoices enabled and user with invoice creation permissions + if (! empty($conf->facture->enabled) && ! empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) + { + if ($user->rights->facture->creer) + { + if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) + { + print ' '; + print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').''; + } + } + } + print ''; + if (! $i) $totalarray['nbfield']++; } // Town if (! empty($arrayfields['s.town']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Zip if (! empty($arrayfields['s.zip']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // State if (! empty($arrayfields['state.nom']['checked'])) { - print "\n"; - if (! $i) $totalarray['nbfield']++; + print "\n"; + if (! $i) $totalarray['nbfield']++; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Type ent if (! empty($arrayfields['typent.code']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Order date if (! empty($arrayfields['c.date_commande']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Plannned date of delivery if (! empty($arrayfields['c.date_delivery']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Amount HT + if (! empty($arrayfields['c.total_ht']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['c.total_vat']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_tva; + } + // Amount TTC + if (! empty($arrayfields['c.total_ttc']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; } - // Amount HT - if (! empty($arrayfields['c.total_ht']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['c.total_vat']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_tva; - } - // Amount TTC - if (! empty($arrayfields['c.total_ttc']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['c.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['c.fk_statut']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['c.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['c.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['c.fk_statut']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Billed - if (! empty($arrayfields['c.facture']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['c.facture']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; @@ -1406,29 +1351,29 @@ if ($resql) } // Show total line - if (isset($totalarray['totalhtfield']) + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totalttcfield']) || isset($totalarray['totalamfield']) || isset($totalarray['totalrtpfield']) ) { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''; - else print ''; - } - elseif ($totalarray['totalhtfield'] == $i) print ''; - elseif ($totalarray['totalvatfield'] == $i) print ''; - elseif ($totalarray['totalttcfield'] == $i) print ''; - else print ''; - } - print ''; + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } + elseif ($totalarray['totalhtfield'] == $i) print ''; + elseif ($totalarray['totalvatfield'] == $i) print ''; + elseif ($totalarray['totalttcfield'] == $i) print ''; + else print ''; + } + print ''; } $db->free($resql); @@ -1444,21 +1389,21 @@ if ($resql) if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->commande->lire; - $delallowed=$user->rights->commande->creer; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->commande->lire; + $delallowed=$user->rights->commande->creer; - print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else { - print '
    '.$langs->trans("ShowTempMassFilesArea").''; + print '
    '.$langs->trans("ShowTempMassFilesArea").''; } } diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php index 6a8b57e3707..b1baf7332a1 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -280,7 +280,7 @@ if ($mode == 'customer') $liststatus=array( Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraft"), Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), - Commande::STATUS_ACCEPTED=>$langs->trans("StatusOrderSent"), + Commande::STATUS_SHIPMENTONPROCESS=>$langs->trans("StatusOrderSent"), Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceled") ); diff --git a/htdocs/compta/bank/annuel.php b/htdocs/compta/bank/annuel.php index eb14db2d3ac..44badfa51d8 100644 --- a/htdocs/compta/bank/annuel.php +++ b/htdocs/compta/bank/annuel.php @@ -149,7 +149,7 @@ dol_fiche_head($head, 'annual', $langs->trans("FinancialAccount"), -1, 'account' $title=$langs->trans("FinancialAccount")." : ".$object->label; $link=($year_start?"".img_previous('', 'class="valignbottom"')." ".$langs->trans("Year")." ".img_next('', 'class="valignbottom"')."":""); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; if (!empty($id)) @@ -203,7 +203,7 @@ print ''; $var=true; for ($mois = 1 ; $mois < 13 ; $mois++) { - + print ''; print ""; for ($annee = $year_start ; $annee <= $year_end ; $annee++) diff --git a/htdocs/compta/bank/bankentries.php b/htdocs/compta/bank/bankentries_list.php similarity index 92% rename from htdocs/compta/bank/bankentries.php rename to htdocs/compta/bank/bankentries_list.php index 2a10308a324..5e79874ae8f 100644 --- a/htdocs/compta/bank/bankentries.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -23,7 +23,7 @@ */ /** - * \file htdocs/compta/bank/bankentries.php + * \file htdocs/compta/bank/bankentries_list.php * \ingroup banque * \brief List of bank transactions */ @@ -100,13 +100,13 @@ $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) $sortorder='ASC'; -if (! $sortfield) $sortfield='b.datev, b.dateo, b.rowid'; +if (! $sortfield) $sortfield='b.datev,b.dateo,b.rowid'; $mode_balance_ok=false; -//if (($sortfield == 'b.datev' || $sortfield == 'b.datev, b.dateo, b.rowid')) // TODO Manage balance when account not selected -if (($sortfield == 'b.datev' || $sortfield == 'b.datev, b.dateo, b.rowid')) +//if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) // TODO Manage balance when account not selected +if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) { - $sortfield = 'b.datev, b.dateo, b.rowid'; + $sortfield = 'b.datev,b.dateo,b.rowid'; if ($id > 0 || ! empty($ref) || $account > 0) $mode_balance_ok = true; } if (strtolower($sortorder) == 'desc') $mode_balance_ok = false; @@ -151,7 +151,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -161,8 +161,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -367,7 +367,7 @@ if (!empty($debit)) $param.='&debit='.$debit; if (!empty($credit)) $param.='&credit='.$credit; if (!empty($account)) $param.='&account='.$account; if (!empty($search_num_releve)) $param.='&search_num_releve='.urlencode($search_num_releve); -if ($search_conciliated != '') $param.='&search_conciliated='.urlencode($search_conciliated); +if ($search_conciliated != '' && $search_conciliated != '-1') $param.='&search_conciliated='.urlencode($search_conciliated); if (!empty($bid)) $param.='&bid='.$bid; if (dol_strlen($search_dt_start) > 0) $param .= '&search_start_dtmonth=' . GETPOST('search_start_dtmonth', 'int') . '&search_start_dtday=' . GETPOST('search_start_dtday', 'int') . '&search_start_dtyear=' . GETPOST('search_start_dtyear', 'int'); if (dol_strlen($search_dt_end) > 0) $param .= '&search_end_dtmonth=' . GETPOST('search_end_dtmonth', 'int') . '&search_end_dtday=' . GETPOST('search_end_dtday', 'int') . '&search_end_dtyear=' . GETPOST('search_end_dtyear', 'int'); @@ -376,8 +376,6 @@ if (dol_strlen($search_dv_end) > 0) $param .= '&search_end_dvmonth=' . GETPOST if ($search_req_nb) $param.='&req_nb='.urlencode($search_req_nb); if (GETPOST("thirdparty")) $param.='&thirdparty='.urlencode(GETPOST("thirdparty")); if ($optioncss != '') $param.='&optioncss='.$optioncss; -if(!empty($search_conciliated) || $search_conciliated === 0) $param.='&search_conciliated='.$search_conciliated; - // Add $param from extra fields foreach ($search_array_options as $key => $val) { @@ -407,7 +405,7 @@ if ($id > 0 || ! empty($ref)) $head=bank_prepare_head($object); dol_fiche_head($head,'journal',$langs->trans("FinancialAccount"),0,'account'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); @@ -449,7 +447,7 @@ if ($id > 0 || ! empty($ref)) if ($object->canBeConciliated() > 0) { // If not cash account and can be reconciliate if ($user->rights->banque->consolidate) { - print ''.$langs->trans("Conciliate").''; + print ''.$langs->trans("Conciliate").''; } else { print ''.$langs->trans("Conciliate").''; } @@ -561,7 +559,7 @@ if (! empty($thirdparty)) $mode_balance_ok=false; $sql.= $db->plimit($limit+1,$offset); -dol_syslog('compta/bank/bankentries.php', LOG_DEBUG); +dol_syslog('compta/bank/bankentries_list.php', LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -608,7 +606,7 @@ if ($resql) // print '
    '; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_orderyear?$search_orderyear:-1,'search_orderyear',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_orderyear?$search_orderyear:-1,'search_orderyear',1, 20, 5); + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_deliveryyear?$search_deliveryyear:-1,'search_deliveryyear',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_deliveryyear?$search_deliveryyear:-1,'search_deliveryyear',1, 20, 5); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + 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 ''; + 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 ''; - print ''; + print ''; - $liststatus=array( - Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"), - Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), - Commande::STATUS_ACCEPTED=>$langs->trans("StatusOrderSentShort"), - Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), - -3=>$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort").'+'.$langs->trans("StatusOrderDelivered"), - Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceledShort") - ); - print $form->selectarray('viewstatut', $liststatus, $viewstatut, -4); - print ''; + $liststatus=array( + Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"), + Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), + Commande::STATUS_SHIPMENTONPROCESS=>$langs->trans("StatusOrderSentShort"), + Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), + -3=>$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort").'+'.$langs->trans("StatusOrderDelivered"), + Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceledShort") + ); + print $form->selectarray('viewstatut', $liststatus, $viewstatut, -4); + print ''; - print $form->selectyesno('billed', $billed, 1, 0, 1); - print ''; + print $form->selectyesno('billed', $billed, 1, 0, 1); + print ''; @@ -1008,12 +938,13 @@ if ($resql) print $searchpicto; print '
    '; - $generic_commande->id=$obj->rowid; - $generic_commande->ref=$obj->ref; - $generic_commande->statut = $obj->fk_statut; - $generic_commande->date_commande = $db->jdate($obj->date_commande); - $generic_commande->date_livraison = $db->jdate($obj->date_delivery); - $generic_commande->ref_client = $obj->ref_client; - $generic_commande->total_ht = $obj->total_ht; - $generic_commande->total_tva = $obj->total_tva; - $generic_commande->total_ttc = $obj->total_ttc; - $generic_commande->lines=array(); - $generic_commande->getLinesArray(); + $generic_commande->id=$obj->rowid; + $generic_commande->ref=$obj->ref; + $generic_commande->statut = $obj->fk_statut; + $generic_commande->date_commande = $db->jdate($obj->date_commande); + $generic_commande->date_livraison = $db->jdate($obj->date_delivery); + $generic_commande->ref_client = $obj->ref_client; + $generic_commande->total_ht = $obj->total_ht; + $generic_commande->total_tva = $obj->total_tva; + $generic_commande->total_ttc = $obj->total_ttc; - print ''; - print ''; + print ''; - // Show shippable Icon (create subloop, so may be slow) - if ($conf->stock->enabled) - { - $langs->load("stocks"); - if (($obj->fk_statut > 0) && ($obj->fk_statut < 3)) - { - $numlines = count($generic_commande->lines); // Loop on each line of order - for ($lig=0; $lig < $numlines; $lig++) - { - if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) // If line is a product and not a service - { - $nbprod++; // order contains real products - $generic_product->id = $generic_commande->lines[$lig]->fk_product; + // Ref + if (! empty($arrayfields['c.ref']['checked'])) + { + print ''; - if (! $i) $totalarray['nbfield']++; - } + print ''; + } + + // Warning late icon and note + print ''; + + print ''; + print '
    '; - print $generic_commande->getNomUrl(1, ($viewstatut != 2?0:$obj->fk_statut), 0, 0, 0, 1); - print '
    '; - // Get local and virtual stock and store it into cache - if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product])) { - $generic_product->load_stock('nobatch'); - //$generic_product->load_virtual_stock(); Already included into load_stock - $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_reel; - $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; - } else { - $generic_product->stock_reel = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel']; - $generic_product->stock_theorique = $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; - } + $generic_commande->lines=array(); + $generic_commande->getLinesArray(); - if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) // Default code. Default is when this option is not set, setting it create strange result - { - $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); - $text_info .= ' - '.$langs->trans("Stock").': '.$generic_product->stock_reel; - $text_info .= ' - '.$langs->trans("VirtualStock").': '.$generic_product->stock_theorique; - $text_info .= '
    '; + print ''; + print ''; - if ($generic_commande->lines[$lig]->qty > $generic_product->stock_reel) - { - $notshippable++; - } - } - else { // Detailed code, looks bugged - // stock order and stock order_supplier - $stock_order=0; - $stock_order_supplier=0; - if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) // What about other options ? - { - if (! empty($conf->commande->enabled)) - { - if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) { - $generic_product->load_stats_commande(0,'1,2'); - $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'] = $generic_product->stats_commande['qty']; - } else { - $generic_product->stats_commande['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer']; - } - $stock_order=$generic_product->stats_commande['qty']; - } - if (! empty($conf->fournisseur->enabled)) - { - if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'])) { - $generic_product->load_stats_commande_fournisseur(0,'3'); - $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'] = $generic_product->stats_commande_fournisseur['qty']; - } else { - $generic_product->stats_commande_fournisseur['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier']; - } - $stock_order_supplier=$generic_product->stats_commande_fournisseur['qty']; - } - } - $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); - $text_stock_reel = $generic_product->stock_reel.'/'.$stock_order; - if ($stock_order > $generic_product->stock_reel && ! ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) { - $warning++; - $text_warning.=''.$langs->trans('Available').' : '.$text_stock_reel.''; - } - if ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty) { - $notshippable++; - $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; - } else { - $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; - } - if (! empty($conf->fournisseur->enabled)) { - $text_info.= ' '.$langs->trans('SupplierOrder').' : '.$stock_order_supplier.'
    '; - } else { - $text_info.= '
    '; - } - } - } - } - if ($notshippable==0) { - $text_icon = img_picto('', 'object_sending'); - $text_info = $langs->trans('Shippable').'
    '.$text_info; - } else { - $text_icon = img_picto('', 'error'); - $text_info = $langs->trans('NonShippable').'
    '.$text_info; - } - } + // Show shippable Icon (create subloop, so may be slow) + if ($conf->stock->enabled) + { + $langs->load("stocks"); + if (($obj->fk_statut > 0) && ($obj->fk_statut < 3)) + { + $numlines = count($generic_commande->lines); // Loop on each line of order + for ($lig=0; $lig < $numlines; $lig++) + { + if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) // If line is a product and not a service + { + $nbprod++; // order contains real products + $generic_product->id = $generic_commande->lines[$lig]->fk_product; - print ''; - } + // Get local and virtual stock and store it into cache + if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product])) { + $generic_product->load_stock('nobatch'); + //$generic_product->load_virtual_stock(); Already included into load_stock + $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_reel; + $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; + } else { + $generic_product->stock_reel = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel']; + $generic_product->stock_theorique = $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; + } - // Warning late icon and note - print ''; + if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) // Default code. Default is when this option is not set, setting it create strange result + { + $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); + $text_info .= ' - '.$langs->trans("Stock").': '.$generic_product->stock_reel; + $text_info .= ' - '.$langs->trans("VirtualStock").': '.$generic_product->stock_theorique; + $text_info .= '
    '; - print ''; - print '
    '; + print $generic_commande->getNomUrl(1, ($viewstatut != 2?0:$obj->fk_statut), 0, 0, 0, 1); + print ''; - if ($nbprod) - { - print $form->textwithtooltip('',$text_info,2,1,$text_icon,'',2); - } - if ($warning) { // Always false in default mode - print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders').'
    '.$text_warning, 2, 1, img_picto('', 'error'),'',2); - } - print '
    '; - if ($generic_commande->hasDelay()) { - print img_picto($langs->trans("Late").' : '.$generic_commande->showDelay(), "warning"); - } - if (!empty($obj->note_private) || !empty($obj->note_public)) - { - print ' '; - print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; - print ''; - } - print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); - print '
    '; + if ($generic_commande->lines[$lig]->qty > $generic_product->stock_reel) + { + $notshippable++; + } + } + else { // Detailed code, looks bugged + // stock order and stock order_supplier + $stock_order=0; + $stock_order_supplier=0; + if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) // What about other options ? + { + if (! empty($conf->commande->enabled)) + { + if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) { + $generic_product->load_stats_commande(0,'1,2'); + $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'] = $generic_product->stats_commande['qty']; + } else { + $generic_product->stats_commande['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer']; + } + $stock_order=$generic_product->stats_commande['qty']; + } + if (! empty($conf->fournisseur->enabled)) + { + if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'])) { + $generic_product->load_stats_commande_fournisseur(0,'3'); + $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'] = $generic_product->stats_commande_fournisseur['qty']; + } else { + $generic_product->stats_commande_fournisseur['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier']; + } + $stock_order_supplier=$generic_product->stats_commande_fournisseur['qty']; + } + } + $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); + $text_stock_reel = $generic_product->stock_reel.'/'.$stock_order; + if ($stock_order > $generic_product->stock_reel && ! ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) { + $warning++; + $text_warning.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + } + if ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty) { + $notshippable++; + $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + } else { + $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + } + if (! empty($conf->fournisseur->enabled)) { + $text_info.= ' '.$langs->trans('SupplierOrder').' : '.$stock_order_supplier.'
    '; + } else { + $text_info.= '
    '; + } + } + } + } + if ($notshippable==0) { + $text_icon = img_picto('', 'object_sending'); + $text_info = $langs->trans('Shippable').'
    '.$text_info; + } else { + $text_icon = img_picto('', 'error'); + $text_info = $langs->trans('NonShippable').'
    '.$text_info; + } + } - print '
    '; + if ($nbprod) + { + print $form->textwithtooltip('',$text_info,2,1,$text_icon,'',2); + } + if ($warning) { // Always false in default mode + print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders').'
    '.$text_warning, 2, 1, img_picto('', 'error'),'',2); + } + print '
    '; + if ($generic_commande->hasDelay()) { + print img_picto($langs->trans("Late").' : '.$generic_commande->showDelay(), "warning"); + } + if (!empty($obj->note_private) || !empty($obj->note_public)) + { + print ' '; + print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; + print ''; + } + print ''; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); + print '
    '; + + print '
    '.$obj->ref_client.''.$obj->ref_client.''; + if ($obj->project_id > 0) print $projectstatic->getNomUrl(1); + print ''; - print $companystatic->getNomUrl(1,'customer'); + print ''; + print $companystatic->getNomUrl(1,'customer'); - // If module invoices enabled and user with invoice creation permissions - if (! empty($conf->facture->enabled) && ! empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) - { - if ($user->rights->facture->creer) - { - if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) - { - print ' '; - print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').''; - } - } - } - print ''; - print $obj->town; - print ''; + print $obj->town; + print ''; - print $obj->zip; - print ''; + print $obj->zip; + print '".$obj->state_name."".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; - print dol_print_date($db->jdate($obj->date_commande), 'day'); - print ''; + print dol_print_date($db->jdate($obj->date_commande), 'day'); + print ''; - print dol_print_date($db->jdate($obj->date_delivery), 'day'); - print ''; + print dol_print_date($db->jdate($obj->date_delivery), 'day'); + print ''.price($obj->total_ht)."'.price($obj->total_tva)."'.price($obj->total_ttc)."'.price($obj->total_ht)."'.price($obj->total_tva)."'.price($obj->total_ttc)."'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).''.yn($obj->billed).''.yn($obj->billed).''; - 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 ''; + 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 '
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
    ".dol_print_date(dol_mktime(1,1,1,$mois,1,2000),"%B")."'; print '
    '; print ''.$langs->trans("InputReceiptNumber").': '; - print ''; // The only default value is value we just entered + print ''; // The only default value is value we just entered print '
    '; if ($options) { print $langs->trans("EventualyAddCategory").': '; @@ -652,6 +650,16 @@ if ($resql) { dol_print_error($db); } + /** + * Using BANK_REPORT_LAST_NUM_RELEVE to automatically report last num (or not) + */ + if ($conf->global->BANK_REPORT_LAST_NUM_RELEVE == 1) { + print ' + + '; + } print '

    '; // print '
    '; } @@ -735,7 +743,7 @@ if ($resql) // Title $bankcateg=new BankCateg($db); - $morehtml='
    '; + $morehtml='
    '; $morehtml.= ' "; // ' Page '; $morehtml.=''; $morehtml.='/'.$nbtotalofpages.' '; @@ -879,7 +887,7 @@ if ($resql) if (! empty($arrayfields['b.rowid']['checked'])) print_liste_field_titre($arrayfields['b.rowid']['label'],$_SERVER['PHP_SELF'],'b.rowid','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['description']['checked'])) print_liste_field_titre($arrayfields['description']['label'],$_SERVER['PHP_SELF'],'','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['b.dateo']['checked'])) print_liste_field_titre($arrayfields['b.dateo']['label'],$_SERVER['PHP_SELF'],'b.dateo','',$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['b.datev']['checked'])) print_liste_field_titre($arrayfields['b.datev']['label'],$_SERVER['PHP_SELF'],'b.datev, b.dateo, b.rowid','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['b.datev']['checked'])) print_liste_field_titre($arrayfields['b.datev']['label'],$_SERVER['PHP_SELF'],'b.datev,b.dateo,b.rowid','',$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['type']['checked'])) print_liste_field_titre($arrayfields['type']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['b.num_chq']['checked'])) print_liste_field_titre($arrayfields['b.num_chq']['label'],$_SERVER['PHP_SELF'],'b.num_chq','',$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['bu.label']['checked'])) print_liste_field_titre($arrayfields['bu.label']['label'],$_SERVER['PHP_SELF'],'bu.label','',$param,'',$sortfield,$sortorder); @@ -955,6 +963,55 @@ if ($resql) else dol_print_error($db); $balancecalculated=true; + + // Output a line with start balance + if ($user->rights->banque->consolidate && $action == 'reconcile') + { + $tmpnbfieldbeforebalance=0; + $tmpnbfieldafterbalance=0; + $balancefieldfound=false; + foreach($arrayfields as $key => $val) + { + if ($key == 'balance') + { + $balancefieldfound=true; + continue; + } + if (! empty($arrayfields[$key]['checked'])) + { + if (! $balancefieldfound) $tmpnbfieldbeforebalance++; + else $tmpnbfieldafterbalance++; + } + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + if (! empty($arrayfields[$key]['checked'])) + { + if (! $balancefieldfound) $tmpnbfieldbeforebalance++; + else $tmpnbfieldafterbalance++; + } + } + } + } + + print ''; + if ($tmpnbfieldbeforebalance) + { + print ''; + print ''; + } + print ''; + print price(price2num($balance, 'MT'), 1, $langs); + print ''; + print ''; + print ''; + print ''; + } } $balance = price2num($balance + ($sign * $objp->amount),'MT'); @@ -1120,7 +1177,16 @@ if ($resql) // Date ope if (! empty($arrayfields['b.dateo']['checked'])) { - print ''.dol_print_date($db->jdate($objp->do),"day")."\n"; + print ''; + print ''.dol_print_date($db->jdate($objp->do),"day").""; + print ' '; + print ''; + print ''; + print img_edit_remove() . " "; + print ''; + print img_edit_add() .""; + print ''; + print "\n"; if (! $i) $totalarray['nbfield']++; } @@ -1144,7 +1210,7 @@ if ($resql) if (! empty($arrayfields['type']['checked'])) { print ''; - $labeltype=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$langs->getLabelFromKey($db,$objp->fk_type,'c_paiement','code','libelle'); + $labeltype=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$langs->getLabelFromKey($db,$objp->fk_type,'c_paiement','code','libelle','',1); if ($labeltype == 'SOLD') print ' '; //$langs->trans("InitialBankBalance"); else print $labeltype; print "\n"; diff --git a/htdocs/compta/bank/budget.php b/htdocs/compta/bank/budget.php index 699edd31b7a..15aae28c1d1 100644 --- a/htdocs/compta/bank/budget.php +++ b/htdocs/compta/bank/budget.php @@ -74,9 +74,9 @@ if ($result) while ($i < $num) { $objp = $db->fetch_object($result); - + print ''; - print "rowid\">$objp->label"; + print "rowid\">$objp->label"; print ''.$objp->nombre.''; print ''.price(abs($objp->somme)).""; print ''.price(abs(price2num($objp->somme / $objp->nombre,'MT'))).""; diff --git a/htdocs/compta/bank/card.php b/htdocs/compta/bank/card.php index 1f55698d13f..0fc7657f184 100644 --- a/htdocs/compta/bank/card.php +++ b/htdocs/compta/bank/card.php @@ -72,204 +72,204 @@ if ($cancel) $action=''; if ($action == 'add') { - $error=0; + $error=0; - $db->begin(); + $db->begin(); - // Create account - $object = new Account($db); + // Create account + $object = new Account($db); - $object->ref = dol_sanitizeFileName(trim($_POST["ref"])); - $object->label = trim($_POST["label"]); - $object->courant = $_POST["type"]; - $object->clos = $_POST["clos"]; - $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; - $object->url = $_POST["url"]; + $object->ref = dol_sanitizeFileName(trim($_POST["ref"])); + $object->label = trim($_POST["label"]); + $object->courant = $_POST["type"]; + $object->clos = $_POST["clos"]; + $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; + $object->url = $_POST["url"]; $object->bank = trim($_POST["bank"]); - $object->code_banque = trim($_POST["code_banque"]); - $object->code_guichet = trim($_POST["code_guichet"]); - $object->number = trim($_POST["number"]); - $object->cle_rib = trim($_POST["cle_rib"]); - $object->bic = trim($_POST["bic"]); - $object->iban = trim($_POST["iban"]); - $object->domiciliation = trim($_POST["domiciliation"]); + $object->code_banque = trim($_POST["code_banque"]); + $object->code_guichet = trim($_POST["code_guichet"]); + $object->number = trim($_POST["number"]); + $object->cle_rib = trim($_POST["cle_rib"]); + $object->bic = trim($_POST["bic"]); + $object->iban = trim($_POST["iban"]); + $object->domiciliation = trim($_POST["domiciliation"]); - $object->proprio = trim($_POST["proprio"]); - $object->owner_address = trim($_POST["owner_address"]); + $object->proprio = trim($_POST["proprio"]); + $object->owner_address = trim($_POST["owner_address"]); $account_number = GETPOST('account_number','alpha'); if ($account_number <= 0) { $object->account_number = ''; } else { $object->account_number = $account_number; } $fk_accountancy_journal = GETPOST('fk_accountancy_journal','int'); if ($fk_accountancy_journal <= 0) { $object->fk_accountancy_journal = ''; } else { $object->fk_accountancy_journal = $fk_accountancy_journal; } - $object->solde = $_POST["solde"]; - $object->date_solde = dol_mktime(12,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]); + $object->solde = $_POST["solde"]; + $object->date_solde = dol_mktime(12,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]); - $object->currency_code = trim($_POST["account_currency_code"]); + $object->currency_code = trim($_POST["account_currency_code"]); - $object->state_id = $_POST["account_state_id"]; - $object->country_id = $_POST["account_country_id"]; + $object->state_id = $_POST["account_state_id"]; + $object->country_id = $_POST["account_country_id"]; - $object->min_allowed = GETPOST("account_min_allowed",'int'); - $object->min_desired = GETPOST("account_min_desired",'int'); - $object->comment = trim(GETPOST("account_comment")); + $object->min_allowed = GETPOST("account_min_allowed",'int'); + $object->min_desired = GETPOST("account_min_desired",'int'); + $object->comment = trim(GETPOST("account_comment")); - $object->fk_user_author = $user->id; + $object->fk_user_author = $user->id; - if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'errors'); - $action='create'; // Force chargement page en mode creation - $error++; - } - if (empty($object->ref)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); - $action='create'; // Force chargement page en mode creation - $error++; - } - if (empty($object->label)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); - $action='create'; // Force chargement page en mode creation - $error++; - } + if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'errors'); + $action='create'; // Force chargement page en mode creation + $error++; + } + if (empty($object->ref)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); + $action='create'; // Force chargement page en mode creation + $error++; + } + if (empty($object->label)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); + $action='create'; // Force chargement page en mode creation + $error++; + } - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - if (! $error) - { - $id = $object->create($user); - if ($id > 0) - { - // Category association - $categories = GETPOST('categories'); - $object->setCategories($categories); + if (! $error) + { + $id = $object->create($user); + if ($id > 0) + { + // Category association + $categories = GETPOST('categories', 'array'); + $object->setCategories($categories); - $_GET["id"]=$id; // Force chargement page en mode visu + $_GET["id"]=$id; // Force chargement page en mode visu - $action=''; - } - else { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); + $action=''; + } + else { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); - $action='create'; // Force chargement page en mode creation - } - } + $action='create'; // Force chargement page en mode creation + } + } - if (! $error) - { - $db->commit(); - } - else - { - $db->rollback(); - } + if (! $error) + { + $db->commit(); + } + else + { + $db->rollback(); + } } if ($action == 'update') { - $error=0; + $error=0; - // Update account - $object = new Account($db); - $object->fetch(GETPOST("id")); + // Update account + $object = new Account($db); + $object->fetch(GETPOST("id")); - $object->ref = dol_string_nospecial(trim($_POST["ref"])); - $object->label = trim($_POST["label"]); - $object->courant = $_POST["type"]; - $object->clos = $_POST["clos"]; - $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; - $object->url = trim($_POST["url"]); + $object->ref = dol_string_nospecial(trim($_POST["ref"])); + $object->label = trim($_POST["label"]); + $object->courant = $_POST["type"]; + $object->clos = $_POST["clos"]; + $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; + $object->url = trim($_POST["url"]); - $object->bank = trim($_POST["bank"]); - $object->code_banque = trim($_POST["code_banque"]); - $object->code_guichet = trim($_POST["code_guichet"]); - $object->number = trim($_POST["number"]); - $object->cle_rib = trim($_POST["cle_rib"]); - $object->bic = trim($_POST["bic"]); - $object->iban = trim($_POST["iban"]); - $object->domiciliation = trim($_POST["domiciliation"]); + $object->bank = trim($_POST["bank"]); + $object->code_banque = trim($_POST["code_banque"]); + $object->code_guichet = trim($_POST["code_guichet"]); + $object->number = trim($_POST["number"]); + $object->cle_rib = trim($_POST["cle_rib"]); + $object->bic = trim($_POST["bic"]); + $object->iban = trim($_POST["iban"]); + $object->domiciliation = trim($_POST["domiciliation"]); - $object->proprio = trim($_POST["proprio"]); - $object->owner_address = trim($_POST["owner_address"]); + $object->proprio = trim($_POST["proprio"]); + $object->owner_address = trim($_POST["owner_address"]); $account_number = GETPOST('account_number', 'int'); if ($account_number <= 0) { $object->account_number = ''; } else { $object->account_number = $account_number; } $fk_accountancy_journal = GETPOST('fk_accountancy_journal','int'); if ($fk_accountancy_journal <= 0) { $object->fk_accountancy_journal = ''; } else { $object->fk_accountancy_journal = $fk_accountancy_journal; } - $object->currency_code = trim($_POST["account_currency_code"]); + $object->currency_code = trim($_POST["account_currency_code"]); - $object->state_id = $_POST["account_state_id"]; - $object->country_id = $_POST["account_country_id"]; + $object->state_id = $_POST["account_state_id"]; + $object->country_id = $_POST["account_country_id"]; - $object->min_allowed = GETPOST("account_min_allowed",'int'); - $object->min_desired = GETPOST("account_min_desired",'int'); - $object->comment = trim(GETPOST("account_comment")); + $object->min_allowed = GETPOST("account_min_allowed",'int'); + $object->min_desired = GETPOST("account_min_desired",'int'); + $object->comment = trim(GETPOST("account_comment")); - if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'error'); - $action='edit'; // Force chargement page en mode creation - $error++; - } - if (empty($object->ref)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); - $action='edit'; // Force chargement page en mode creation - $error++; - } - if (empty($object->label)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); - $action='edit'; // Force chargement page en mode creation - $error++; - } + if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'error'); + $action='edit'; // Force chargement page en mode creation + $error++; + } + if (empty($object->ref)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); + $action='edit'; // Force chargement page en mode creation + $error++; + } + if (empty($object->label)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); + $action='edit'; // Force chargement page en mode creation + $error++; + } - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - if (! $error) - { - $result = $object->update($user); - if ($result >= 0) - { - // Category association - $categories = GETPOST('categories'); - $object->setCategories($categories); + if (! $error) + { + $result = $object->update($user); + if ($result >= 0) + { + // Category association + $categories = GETPOST('categories', 'array'); + $object->setCategories($categories); - $_GET["id"]=$_POST["id"]; // Force chargement page en mode visu - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - $action='edit'; // Force chargement page edition - } - } + $_GET["id"]=$_POST["id"]; // Force chargement page en mode visu + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $action='edit'; // Force chargement page edition + } + } } if ($action == 'confirm_delete' && $_POST["confirm"] == "yes" && $user->rights->banque->configurer) { - // Delete - $object = new Account($db); - $object->fetch(GETPOST("id","int")); - $result = $object->delete($user); + // Delete + $object = new Account($db); + $object->fetch(GETPOST("id","int")); + $result = $object->delete($user); - if ($result > 0) - { - setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); - header("Location: ".DOL_URL_ROOT."/compta/bank/index.php"); - exit; - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - $action=''; - } + if ($result > 0) + { + setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); + header("Location: ".DOL_URL_ROOT."/compta/bank/list.php"); + exit; + } + else + { + setEventMessages($account->error, $account->errors, 'errors'); + $action=''; + } } @@ -297,10 +297,10 @@ if ($action == 'create') print load_fiche_titre($langs->trans("NewFinancialAccount"), '', 'title_bank.png'); - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) + { print "\n".''."\n"; - } + print ''."\n"; + } print ''; print ''; @@ -324,11 +324,11 @@ if ($action == 'create') // Ref print ''.$langs->trans("Ref").''; - print 'ref).'" maxlength="12">'; + print 'ref).'" maxlength="12" autofocus>'; // Label print ''.$langs->trans("LabelBankCashAccount").''; - print ''; + print ''; // Type print ''.$langs->trans("AccountType").''; @@ -347,12 +347,12 @@ if ($action == 'create') print ''; // Status - print ''.$langs->trans("Status").''; - print ''; - print $form->selectarray("clos", $object->status,(isset($_POST["clos"])?$_POST["clos"]:$object->clos)); - print ''; + print ''.$langs->trans("Status").''; + print ''; + print $form->selectarray("clos", $object->status,(GETPOST("clos",'int')!=''?GETPOST("clos",'int'):$object->clos)); + print ''; - // Country + // Country $selectedcode=''; if (isset($_POST["account_country_id"])) { @@ -383,24 +383,24 @@ if ($action == 'create') print ''.$langs->trans("Web").''; print ''; - // Tags-Categories - if ($conf->categorie->enabled) - { - print ''.$langs->trans("Categories").''; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); - $c = new Categorie($db); - $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); - foreach($cats as $cat) { - $arrayselected[] = $cat->id; - } - print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); - print ""; - } + // Tags-Categories + if ($conf->categorie->enabled) + { + print ''.$langs->trans("Categories").''; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); + $c = new Categorie($db); + $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); + foreach($cats as $cat) { + $arrayselected[] = $cat->id; + } + print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); + print ""; + } // Comment print ''.$langs->trans("Comment").''; print ''; - // Editor wysiwyg + // Editor wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor=new DolEditor('account_comment',(GETPOST("account_comment")?GETPOST("account_comment"):$object->comment),'',90,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_4,'90%'); $doleditor->Create(); @@ -409,7 +409,7 @@ if ($action == 'create') // Other attributes $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields,'edit',$parameters); @@ -504,7 +504,7 @@ if ($action == 'create') print ''; // Accountancy code $fieldrequired=''; - if (! empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) $fieldrequired='fieldrequired '; + if (! empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) $fieldrequired='fieldrequired '; if (! empty($conf->accounting->enabled)) { @@ -523,7 +523,7 @@ if ($action == 'create') if (! empty($conf->accounting->enabled)) { print ''; - print ''; } @@ -547,7 +547,7 @@ if ($action == 'create') /* ************************************************************************** */ else { - if (($_GET["id"] || $_GET["ref"]) && $action != 'edit') + if (($_GET["id"] || $_GET["ref"]) && $action != 'edit') { $object = new Account($db); if ($_GET["id"]) @@ -560,11 +560,7 @@ else $_GET["id"]=$object->id; } - /* - * Affichage onglets - */ - - // Onglets + // Show tabs $head=bank_prepare_head($object); dol_fiche_head($head, 'bankname', $langs->trans("FinancialAccount"), -1, 'account'); @@ -580,7 +576,7 @@ else // Print form confirm print $formconfirm; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref=''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -592,18 +588,6 @@ else print '
    '.$langs->trans("AccountancyJournal").''; + print ''; print $formaccounting->select_journal($object->fk_accountancy_journal, 'fk_accountancy_journal', 4, 1, 0, 0); print '
    '; - - // Ref - /* - print ''; - print '';*/ - - // Label - /*print ''; - print '';*/ - // Type print ''; print ''; @@ -616,32 +600,12 @@ else print $langs->trans("Currency".$selectedcode); print ''; - // Status - /*print ''; - print '';*/ - - // Country - /* - print ''; - - // State - print '';*/ - // Conciliate print ''; print ''; @@ -660,15 +624,15 @@ else print $accountingaccount->getNomUrl(0,1,1,'',1); } else { - print $object->account_number; + print $object->account_number; } print ''; // Accountancy journal if (! empty($conf->accounting->enabled)) { - print ''; - print ''; + print ''; } +// Currency +if (! empty($arrayfields['b.currency_code']['checked'])) +{ + print ''; +} // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { @@ -377,7 +383,7 @@ if (! empty($arrayfields['b.tms']['checked'])) print ''; } -// Statut +// Status if (! empty($arrayfields['b.clos']['checked'])) { print ''; } // Balance @@ -408,6 +414,7 @@ if (! empty($arrayfields['accountype']['checked'])) print_liste_field_titr if (! empty($arrayfields['b.number']['checked'])) print_liste_field_titre($arrayfields['b.number']['label'],$_SERVER["PHP_SELF"],'b.number','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['b.account_number']['checked'])) print_liste_field_titre($arrayfields['b.account_number']['label'],$_SERVER["PHP_SELF"],'b.account_number','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['b.fk_accountancy_journal']['checked'])) print_liste_field_titre($arrayfields['b.fk_accountancy_journal']['label'],$_SERVER["PHP_SELF"],'b.fk_accountancy_journal','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['b.currency_code']['checked'])) print_liste_field_titre($arrayfields['b.currency_code']['label'],$_SERVER["PHP_SELF"],'','',$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['toreconcile']['checked'])) print_liste_field_titre($arrayfields['toreconcile']['label'],$_SERVER["PHP_SELF"],'','',$param,'align="center"',$sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -443,19 +450,19 @@ foreach ($accounts as $key=>$type) $found++; - $acc = new Account($db); - $acc->fetch($key); + $obj = new Account($db); + $obj->fetch($key); $var = !$var; - $solde = $acc->solde(1); + $solde = $obj->solde(1); - if (! empty($lastcurrencycode) && $lastcurrencycode != $acc->currency_code) + if (! empty($lastcurrencycode) && $lastcurrencycode != $obj->currency_code) { $lastcurrencycode='various'; // We found several different currencies } if ($lastcurrencycode != 'various') { - $lastcurrencycode=$acc->currency_code; + $lastcurrencycode=$obj->currency_code; } print ''; @@ -463,14 +470,14 @@ foreach ($accounts as $key=>$type) // Ref if (! empty($arrayfields['b.ref']['checked'])) { - print ''; + print ''; if (! $i) $totalarray['nbfield']++; } // Label if (! empty($arrayfields['b.label']['checked'])) { - print ''; + print ''; if (! $i) $totalarray['nbfield']++; } @@ -478,7 +485,7 @@ foreach ($accounts as $key=>$type) if (! empty($arrayfields['accountype']['checked'])) { print ''; if (! $i) $totalarray['nbfield']++; } @@ -486,7 +493,7 @@ foreach ($accounts as $key=>$type) // Number if (! empty($arrayfields['b.number']['checked'])) { - print ''; + print ''; if (! $i) $totalarray['nbfield']++; } @@ -497,12 +504,12 @@ foreach ($accounts as $key=>$type) if (! empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); - $accountingaccount->fetch('',$acc->account_number); + $accountingaccount->fetch('',$obj->account_number); print $accountingaccount->getNomUrl(0,1,1,'',1); } else { - print $acc->account_number; + print $obj->account_number; } print ''; if (! $i) $totalarray['nbfield']++; @@ -515,7 +522,7 @@ foreach ($accounts as $key=>$type) if (! empty($conf->accounting->enabled)) { $accountingjournal = new AccountingJournal($db); - $accountingjournal->fetch($acc->fk_accountancy_journal); + $accountingjournal->fetch($obj->fk_accountancy_journal); print $accountingjournal->getNomUrl(0,1,1,'',1); } else @@ -526,15 +533,24 @@ foreach ($accounts as $key=>$type) if (! $i) $totalarray['nbfield']++; } + // Currency + if (! empty($arrayfields['b.currency_code']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Transactions to reconcile if (! empty($arrayfields['toreconcile']['checked'])) { print ''; if (! $i) $totalarray['nbfield']++; } @@ -579,15 +595,15 @@ foreach ($accounts as $key=>$type) if (! empty($arrayfields['b.tms']['checked'])) { print ''; if (! $i) $totalarray['nbfield']++; } - // Statut + // Status if (! empty($arrayfields['b.clos']['checked'])) { - print ''; + print ''; if (! $i) $totalarray['nbfield']++; } @@ -595,7 +611,7 @@ foreach ($accounts as $key=>$type) if (! empty($arrayfields['balance']['checked'])) { print ''; if (! $i) $totalarray['nbfield']++; if (! $i) $totalarray['totalbalancefield']=$totalarray['nbfield']; @@ -615,7 +631,7 @@ foreach ($accounts as $key=>$type) print ''; - $total[$acc->currency_code] += $solde; + $total[$obj->currency_code] += $solde; $i++; } diff --git a/htdocs/compta/bank/releve.php b/htdocs/compta/bank/releve.php index efa7c03f89b..fb43f098583 100644 --- a/htdocs/compta/bank/releve.php +++ b/htdocs/compta/bank/releve.php @@ -52,6 +52,9 @@ $ref=GETPOST('ref','alpha'); $dvid=GETPOST('dvid','alpha'); $numref=GETPOST('num','alpha'); $ve=GETPOST("ve",'alpha'); +$brref=GETPOST('brref','alpha'); +$oldbankreceipt=GETPOST('oldbankreceipt','alpha'); +$newbankreceipt=GETPOST('newbankreceipt','alpha'); // Security check $fieldid = (! empty($ref)?$ref:$id); @@ -149,9 +152,6 @@ else { } - - - $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv,"; $sql.= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,"; $sql.= " b.fk_bordereau,"; @@ -174,6 +174,16 @@ $sqlrequestforbankline = $sql; * Actions */ +if ($action == 'confirm_editbankreceipt' && ! empty($oldbankreceipt) && ! empty($newbankreceipt)) +{ + // TODO Add a test to check newbankreceipt does not exists yet + $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX.'bank SET num_releve = "'.$db->escape($newbankreceipt).'" WHERE num_releve = "'.$db->escape($oldbankreceipt).'"'; + $result = $db->query($sqlupdate); + if ($result < 0) dol_print_error($db); + + $action='view'; +} + // ZIP creation if ($action=="dl" && $numref > 0) { @@ -385,7 +395,7 @@ if (empty($numref)) $head=bank_prepare_head($object); dol_fiche_head($head,'statement',$langs->trans("FinancialAccount"),0,'account'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); @@ -397,23 +407,29 @@ if (empty($numref)) if ($object->canBeConciliated() > 0) { // If not cash account and can be reconciliate if ($user->rights->banque->consolidate) { - print ''.$langs->trans("Conciliate").''; + print ''.$langs->trans("Conciliate").''; } else { print ''.$langs->trans("Conciliate").''; } } print ''; - print '

    '; print_barre_liste('', $page, $_SERVER["PHP_SELF"], "&account=".$object->id, $sortfield, $sortorder,'',$numrows); + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '.$langs->trans("Ref").''; - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref'); - print '
    '.$langs->trans("Label").''.$object->label.'
    '.$langs->trans("AccountType").''.$object->type_lib[$object->type].'
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("BankAccountCountry").''; - if ($object->country_id > 0) - { - $img=picto_from_langcode($object->country_code); - print $img?$img.' ':''; - print getCountry($object->getCountryCode(),0,$db); - } - print '
    '.$langs->trans('State').''; - if ($object->state_id > 0) print getState($object->state_id); - print '
    '.$langs->trans("Conciliable").''; $conciliate=$object->canBeConciliated(); if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; - else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; + else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; else print ($object->rappro==1 ? $langs->trans("Yes") : ($langs->trans("No").' ('.$langs->trans("ConciliationDisabled").')')); print '
    '.$langs->trans("AccountancyJournal").''; + print '
    '.$langs->trans("AccountancyJournal").''; $accountingjournal = new AccountingJournal($db); $accountingjournal->fetch($object->fk_accountancy_journal); @@ -691,12 +655,12 @@ else print ''; - // Categories - if ($conf->categorie->enabled) { - print '"; - } + // Categories + if ($conf->categorie->enabled) { + print '"; + } print ''; print ''; @@ -705,11 +669,10 @@ else if ($object->type == Account::TYPE_SAVINGS || $object->type == Account::TYPE_CURRENT) { - print '
    '; - print '
    '; + print '
    '; - print '
    '.$langs->trans("Categories").''; - print $form->showCategories($object->id,'account',1); - print "
    '.$langs->trans("Categories").''; + print $form->showCategories($object->id,'bank_account',1); + print "
    '.$langs->trans("Comment").''.dol_htmlentitiesbr($object->comment).'
    '; + print '
    '; print ''; print ''; @@ -800,23 +763,23 @@ else } - /* ************************************************************************** */ - /* */ - /* Edition */ - /* */ - /* ************************************************************************** */ + /* ************************************************************************** */ + /* */ + /* Edition */ + /* */ + /* ************************************************************************** */ - if (GETPOST('id','int') && $action == 'edit' && $user->rights->banque->configurer) - { - $object = new Account($db); - $object->fetch(GETPOST('id','int')); + if (GETPOST('id','int') && $action == 'edit' && $user->rights->banque->configurer) + { + $object = new Account($db); + $object->fetch(GETPOST('id','int')); - print load_fiche_titre($langs->trans("EditFinancialAccount"), '', 'title_bank.png'); + print load_fiche_titre($langs->trans("EditFinancialAccount"), '', 'title_bank.png'); - if ($conf->use_javascript_ajax) - { - print "\n".''."\n"; - } + print ''."\n"; + } - print ''; - print ''; - print ''; - print ''."\n\n"; + print ''; + print ''; + print ''; + print ''."\n\n"; - dol_fiche_head(''); + dol_fiche_head(''); - print '
    '; + print '
    '; - print '
    '.$langs->trans("BankName").''.$object->bank.'
    '; + print '
    '; // Ref print ''; print ''; // Label - print ''; - print ''; + print ''; + print ''; - // Type - print ''; - print ''; + print ''; + print ''; // Currency print ''; // Status - print ''; - print ''; + print ''; + print ''; // Country $object->country_id=$object->country_id?$object->country_id:$mysoc->country_id; @@ -901,15 +864,15 @@ else print ''; // Conciliable - print ''; - print ''; + print ''; + print ''; - // Balance + // Balance print ''; print ''; @@ -917,28 +880,28 @@ else print ''; // Web - print ''; - print ''; + print ''; + print ''; - // Tags-Categories - if ($conf->categorie->enabled) - { - print '"; - } + // Tags-Categories + if ($conf->categorie->enabled) + { + print '"; + } // Comment print ''; print ''.$langs->trans("AccountancyCode").''; print ''; @@ -990,9 +953,9 @@ else if ($_POST["type"] == Account::TYPE_SAVINGS || $_POST["type"] == Account::TYPE_CURRENT) { - print '
    '; + print '
    '; - //print '
    '; + //print '
    '; print '
    '.$langs->trans("Ref").'ref).'">
    '.$langs->trans("Label").'label).'">
    '.$langs->trans("Label").'label).'">
    '.$langs->trans("AccountType").''; + // Type + print '
    '.$langs->trans("AccountType").''; $formbank->selectTypeOfBankAccount((isset($_POST["type"])?$_POST["type"]:$object->type),"type"); - print '
    '.$langs->trans("Currency"); @@ -870,10 +833,10 @@ else print '
    '.$langs->trans("Status").''; - print $form->selectarray("clos", $object->status, (isset($_POST["clos"])?$_POST["clos"]:$object->clos)); - print '
    '.$langs->trans("Status").''; + print $form->selectarray("clos", $object->status, (isset($_POST["clos"])?$_POST["clos"]:$object->clos)); + print '
    '.$langs->trans("Conciliable").''; - $conciliate=$object->canBeConciliated(); - if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; - else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; - else print ' 0)?'':' checked="checked"').'"> '.$langs->trans("DisableConciliation"); - print '
    '.$langs->trans("Conciliable").''; + $conciliate=$object->canBeConciliated(); + if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; + else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; + else print ' 0)?'':' checked="checked"').'"> '.$langs->trans("DisableConciliation"); + print '
    '.$langs->trans("BalanceMinimalAllowed").'min_allowed).'">
    min_desired).'">
    '.$langs->trans("Web").'url).'">'; - print '
    '.$langs->trans("Web").'url).'">'; + print '
    '.$langs->trans("Categories").''; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); - $c = new Categorie($db); - $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); - foreach($cats as $cat) { - $arrayselected[] = $cat->id; - } - print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); - print "
    '.$langs->trans("Categories").''; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); + $c = new Categorie($db); + $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); + foreach($cats as $cat) { + $arrayselected[] = $cat->id; + } + print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); + print "
    '.$langs->trans("Comment").''; - // Editor wysiwyg + // Editor wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor=new DolEditor('account_comment',(GETPOST("account_comment")?GETPOST("account_comment"):$object->comment),'',90,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_4,'95%'); $doleditor->Create(); @@ -947,7 +910,7 @@ else // Other attributes $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields,'edit'); @@ -965,15 +928,15 @@ else $tdextra = ' class="titlefieldcreate"'; if (!empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) { - $tdextra = ' class="fieldrequired titlefieldcreate"'; + $tdextra = ' class="fieldrequired titlefieldcreate"'; } print '
    '; if (!empty($conf->accounting->enabled)) { - print $formaccounting->select_account($object->account_number, 'account_number', 1, '', 1, 1); + print $formaccounting->select_account($object->account_number, 'account_number', 1, '', 1, 1); } else { - print 'account_number).'">'; + print 'account_number).'">'; } print '
    '; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 08631abec79..6bc9ae16089 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -36,117 +36,117 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; */ class Account extends CommonObject { - public $element = 'bank_account'; - public $table_element = 'bank_account'; - public $picto = 'account'; + public $element = 'bank_account'; + public $table_element = 'bank_account'; + public $picto = 'account'; - /** - * @var int Use id instead of rowid - * @deprecated - * @see id - */ - public $rowid; + /** + * @var int Use id instead of rowid + * @deprecated + * @see id + */ + public $rowid; - /** - * Label - * @var string - */ - public $label; + /** + * Label + * @var string + */ + public $label; - /** - * Bank account type. Check TYPE_ constants - * @var int - */ - public $courant; + /** + * Bank account type. Check TYPE_ constants + * @var int + */ + public $courant; - /** - * Bank account type. Check TYPE_ constants - * @var int - */ - public $type; + /** + * Bank account type. Check TYPE_ constants + * @var int + */ + public $type; - /** - * Bank name - * @var string - */ - public $bank; + /** + * Bank name + * @var string + */ + public $bank; - /** - * Status - * @var int - */ - public $clos = self::STATUS_OPEN; + /** + * Status + * @var int + */ + public $clos = self::STATUS_OPEN; - /** - * Does it need to be conciliated? - * @var int - */ - public $rappro=1; + /** + * Does it need to be conciliated? + * @var int + */ + public $rappro=1; - /** - * Webpage - * @var string - */ - public $url; + /** + * Webpage + * @var string + */ + public $url; - /** - * Bank number. If in SEPA area, you should move to IBAN field - * @var string - */ - public $code_banque; + /** + * Bank number. If in SEPA area, you should move to IBAN field + * @var string + */ + public $code_banque; - /** - * Branch number. If in SEPA area, you should move to IBAN field - * @var string - */ - public $code_guichet; + /** + * Branch number. If in SEPA area, you should move to IBAN field + * @var string + */ + public $code_guichet; - /** - * Account number. If in SEPA area, you should move to IBAN field - * @var string - */ - public $number; + /** + * Account number. If in SEPA area, you should move to IBAN field + * @var string + */ + public $number; - /** - * Bank account number control digit. If in SEPA area, you should move to IBAN field - * @var string - */ - public $cle_rib; + /** + * Bank account number control digit. If in SEPA area, you should move to IBAN field + * @var string + */ + public $cle_rib; - /** - * BIC/Swift code - * @var string - */ - public $bic; + /** + * BIC/Swift code + * @var string + */ + public $bic; - /** - * IBAN number (International Bank Account Number). Stored into iban_prefix field into database - * @var - */ - public $iban; + /** + * IBAN number (International Bank Account Number). Stored into iban_prefix field into database + * @var + */ + public $iban; - /** - * Name of account holder - * @var string - */ - public $proprio; + /** + * Name of account holder + * @var string + */ + public $proprio; - /** - * Address of account holder - * @var string - */ - public $owner_address; + /** + * Address of account holder + * @var string + */ + public $owner_address; - public $state_id; - public $state_code; - public $state; + public $state_id; + public $state_code; + public $state; /** * Variable containing all account types with their respective translated label. * Defined in __construct * @var array */ - public $type_lib = array(); + public $type_lib = array(); /** * Variable containing all account statuses with their respective translated label. @@ -155,90 +155,90 @@ class Account extends CommonObject */ public $status = array(); - /** - * Accountancy code - * @var string - */ - public $account_number; + /** + * Accountancy code + * @var string + */ + public $account_number; public $fk_accountancy_journal; - /** - * Currency code - * @var string - */ - public $currency_code; + /** + * Currency code + * @var string + */ + public $currency_code; - /** - * Currency code - * @var string - * @deprecated Use currency_code instead - */ - public $account_currency_code; + /** + * Currency code + * @var string + * @deprecated Use currency_code instead + */ + public $account_currency_code; - /** - * Authorized minimum balance - * @var float - */ - public $min_allowed; + /** + * Authorized minimum balance + * @var float + */ + public $min_allowed; - /** - * Desired minimum balance - * @var float - */ - public $min_desired; + /** + * Desired minimum balance + * @var float + */ + public $min_desired; - /** - * Notes - * @var string - */ - public $comment; + /** + * Notes + * @var string + */ + public $comment; - /** - * Date of the initial balance. Used in Account::create - * @var int - */ - public $date_solde; + /** + * Date of the initial balance. Used in Account::create + * @var int + */ + public $date_solde; - /** - * Current account - */ - const TYPE_CURRENT = 1; - /** - * Cash account - */ - const TYPE_CASH = 2; - /** - * Savings account - */ - const TYPE_SAVINGS = 0; + /** + * Current account + */ + const TYPE_CURRENT = 1; + /** + * Cash account + */ + const TYPE_CASH = 2; + /** + * Savings account + */ + const TYPE_SAVINGS = 0; - const STATUS_OPEN = 0; - const STATUS_CLOSED = 1; + const STATUS_OPEN = 0; + const STATUS_CLOSED = 1; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct(DoliDB $db) - { - global $langs; + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct(DoliDB $db) + { + global $langs; - $this->db = $db; + $this->db = $db; - $this->solde = 0; + $this->solde = 0; - $this->type_lib = array( - self::TYPE_SAVINGS => $langs->trans("BankType0"), - self::TYPE_CURRENT => $langs->trans("BankType1"), - self::TYPE_CASH => $langs->trans("BankType2"), - ); + $this->type_lib = array( + self::TYPE_SAVINGS => $langs->trans("BankType0"), + self::TYPE_CURRENT => $langs->trans("BankType1"), + self::TYPE_CASH => $langs->trans("BankType2"), + ); - $this->status = array( - self::STATUS_OPEN => $langs->trans("StatusAccountOpened"), - self::STATUS_CLOSED => $langs->trans("StatusAccountClosed") - ); - } + $this->status = array( + self::STATUS_OPEN => $langs->trans("StatusAccountOpened"), + self::STATUS_CLOSED => $langs->trans("StatusAccountClosed") + ); + } /** * Shows the account number in the appropiate format @@ -270,183 +270,184 @@ class Account extends CommonObject } - /** - * Return if a bank account need to be conciliated - * - * @return int 1 if need to be concialiated, < 0 otherwise. - */ - function canBeConciliated() - { - global $conf; + /** + * Return if a bank account need to be conciliated + * + * @return int 1 if need to be concialiated, < 0 otherwise. + */ + function canBeConciliated() + { + global $conf; - if (empty($this->rappro)) return -1; - if ($this->courant == Account::TYPE_CASH && empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) return -2; - if ($this->clos) return -3; - return 1; - } + if (empty($this->rappro)) return -1; + if ($this->courant == Account::TYPE_CASH && empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) return -2; + if ($this->clos) return -3; + return 1; + } - /** - * Add a link between bank line record and its source - * - * @param int $line_id Id ecriture bancaire - * @param int $url_id Id parametre url - * @param string $url Url - * @param string $label Link label - * @param string $type Type of link ('payment', 'company', 'member', ...) - * @return int <0 if KO, id line if OK - */ - function add_url_line($line_id, $url_id, $url, $label, $type) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url ("; - $sql.= "fk_bank"; - $sql.= ", url_id"; - $sql.= ", url"; - $sql.= ", label"; - $sql.= ", type"; - $sql.= ") VALUES ("; - $sql.= "'".$line_id."'"; - $sql.= ", '".$url_id."'"; - $sql.= ", '".$url."'"; - $sql.= ", '".$this->db->escape($label)."'"; - $sql.= ", '".$type."'"; - $sql.= ")"; + /** + * Add a link between bank line record and its source + * + * @param int $line_id Id ecriture bancaire + * @param int $url_id Id parametre url + * @param string $url Url + * @param string $label Link label + * @param string $type Type of link ('payment', 'company', 'member', ...) + * @return int <0 if KO, id line if OK + */ + function add_url_line($line_id, $url_id, $url, $label, $type) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url ("; + $sql.= "fk_bank"; + $sql.= ", url_id"; + $sql.= ", url"; + $sql.= ", label"; + $sql.= ", type"; + $sql.= ") VALUES ("; + $sql.= "'".$line_id."'"; + $sql.= ", '".$url_id."'"; + $sql.= ", '".$url."'"; + $sql.= ", '".$this->db->escape($label)."'"; + $sql.= ", '".$type."'"; + $sql.= ")"; - dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG); - if ($this->db->query($sql)) - { - $rowid = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_url"); - return $rowid; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } + dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG); + if ($this->db->query($sql)) + { + $rowid = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_url"); + return $rowid; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } - /** - * TODO Move this into AccountLine - * Return array with links from llx_bank_url - * - * @param int $fk_bank To search using bank transaction id - * @param int $url_id To search using link to - * @param string $type To search using type - * @return array|-1 Array of links or -1 on error - */ - function get_url($fk_bank='', $url_id='', $type='') - { - $lines = array(); + /** + * TODO Move this into AccountLine + * Return array with links from llx_bank_url + * + * @param int $fk_bank To search using bank transaction id + * @param int $url_id To search using link to + * @param string $type To search using type + * @return array|-1 Array of links or -1 on error + */ + function get_url($fk_bank='', $url_id='', $type='') + { + $lines = array(); - // Check parameters - if (! empty($fk_bank) && (! empty($url_id) || ! empty($type))) - { - $this->error="ErrorBadParameter"; - return -1; - } + // Check parameters + if (! empty($fk_bank) && (! empty($url_id) || ! empty($type))) + { + $this->error="ErrorBadParameter"; + return -1; + } - $sql = "SELECT fk_bank, url_id, url, label, type"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_url"; - if ($fk_bank > 0) { - $sql.= " WHERE fk_bank = ".$fk_bank; - } - else { $sql.= " WHERE url_id = ".$url_id." AND type = '".$type."'"; - } - $sql.= " ORDER BY type, label"; + $sql = "SELECT fk_bank, url_id, url, label, type"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_url"; + if ($fk_bank > 0) { + $sql.= " WHERE fk_bank = ".$fk_bank; + } + else { $sql.= " WHERE url_id = ".$url_id." AND type = '".$type."'"; + } + $sql.= " ORDER BY type, label"; - dol_syslog(get_class($this)."::get_url", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $i = 0; - $num = $this->db->num_rows($result); - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - // Anciens liens (pour compatibilite) - $lines[$i][0] = $obj->url; - $lines[$i][1] = $obj->url_id; - $lines[$i][2] = $obj->label; - $lines[$i][3] = $obj->type; - // Nouveaux liens - $lines[$i]['url'] = $obj->url; - $lines[$i]['url_id'] = $obj->url_id; - $lines[$i]['label'] = $obj->label; - $lines[$i]['type'] = $obj->type; - $lines[$i]['fk_bank'] = $obj->fk_bank; - $i++; - } - } - else dol_print_error($this->db); + dol_syslog(get_class($this)."::get_url", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $i = 0; + $num = $this->db->num_rows($result); + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + // Anciens liens (pour compatibilite) + $lines[$i][0] = $obj->url; + $lines[$i][1] = $obj->url_id; + $lines[$i][2] = $obj->label; + $lines[$i][3] = $obj->type; + // Nouveaux liens + $lines[$i]['url'] = $obj->url; + $lines[$i]['url_id'] = $obj->url_id; + $lines[$i]['label'] = $obj->label; + $lines[$i]['type'] = $obj->type; + $lines[$i]['fk_bank'] = $obj->fk_bank; + $i++; + } + } + else dol_print_error($this->db); - return $lines; - } + return $lines; + } - /** - * Add an entry into table ".MAIN_DB_PREFIX."bank - * - * @param int $date Date operation - * @param string $oper 1,2,3,4... (deprecated) or TYP,VIR,PRE,LIQ,VAD,CB,CHQ... - * @param string $label Descripton - * @param float $amount Amount - * @param string $num_chq Numero cheque ou virement - * @param int $categorie Category id (optionnal) - * @param User $user User that create - * @param string $emetteur Name of cheque writer - * @param string $banque Bank of cheque writer - * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on. - * @return int Rowid of added entry, <0 if KO - */ - function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='') - { - // Deprecatîon warning - if (is_numeric($oper)) { - dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING); - } + /** + * Add an entry into table ".MAIN_DB_PREFIX."bank + * + * @param int $date Date operation + * @param string $oper 1,2,3,4... (deprecated) or 'TYP','VIR','PRE','LIQ','VAD','CB','CHQ'... + * @param string $label Descripton + * @param float $amount Amount + * @param string $num_chq Numero cheque ou virement + * @param int $categorie Category id (optionnal) + * @param User $user User that create + * @param string $emetteur Name of cheque writer + * @param string $banque Bank of cheque writer + * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on. + * @return int Rowid of added entry, <0 if KO + */ + function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='') + { + // Deprecatîon warning + if (is_numeric($oper)) { + dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING); + } - // Clean parameters - $emetteur=trim($emetteur); - $banque=trim($banque); + // Clean parameters + $emetteur=trim($emetteur); + $banque=trim($banque); - $now=dol_now(); + $now=dol_now(); - if (is_numeric($oper)) // Clean oper to have a code instead of a rowid - { - $sql ="SELECT code FROM ".MAIN_DB_PREFIX."c_paiement"; - $sql.=" WHERE id=".$oper; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $oper=$obj->code; - } - else - { - dol_print_error($this->db,'Failed to get payment type code'); - return -1; - } - } + if (is_numeric($oper)) // Clean oper to have a code instead of a rowid + { + $sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_paiement"; + $sql.= " WHERE id=".$oper; + $sql.= " AND entity IN (" . getEntity('c_paiement') . ")"; + $resql=$this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $oper=$obj->code; + } + else + { + dol_print_error($this->db,'Failed to get payment type code'); + return -1; + } + } - // Check parameters - if (! $oper) - { - $this->error="oper not defined"; - return -1; - } - if (! $this->rowid) - { - $this->error="this->rowid not defined"; - return -2; - } - if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ') - { - $this->error="ErrorCashAccountAcceptsOnlyCashMoney"; - return -3; - } + // Check parameters + if (! $oper) + { + $this->error="oper not defined"; + return -1; + } + if (! $this->rowid) + { + $this->error="this->rowid not defined"; + return -2; + } + if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ') + { + $this->error="ErrorCashAccountAcceptsOnlyCashMoney"; + return -3; + } - $this->db->begin(); + $this->db->begin(); - $datev = $date; + $datev = $date; $accline = new AccountLine($this->db); $accline->datec = $now; @@ -497,109 +498,109 @@ class Account extends CommonObject } } - /** - * Create bank account into database - * - * @param User $user Object user making creation - * @param int $notrigger 1=Disable triggers - * @return int < 0 if KO, > 0 if OK - */ - function create(User $user = null, $notrigger=0) - { - global $langs,$conf, $hookmanager; + /** + * Create bank account into database + * + * @param User $user Object user making creation + * @param int $notrigger 1=Disable triggers + * @return int < 0 if KO, > 0 if OK + */ + function create(User $user = null, $notrigger=0) + { + global $langs,$conf, $hookmanager; - // Clean parameters - if (! $this->min_allowed) $this->min_allowed=0; - if (! $this->min_desired) $this->min_desired=0; - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + // Clean parameters + if (! $this->min_allowed) $this->min_allowed=0; + if (! $this->min_desired) $this->min_desired=0; + $this->state_id = ($this->state_id?$this->state_id:$this->state_id); + $this->country_id = ($this->country_id?$this->country_id:$this->country_id); - // Check parameters - if (empty($this->country_id)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } - if (empty($this->ref)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } - if (empty($this->date_solde)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateInitialBalance")); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } + // Check parameters + if (empty($this->country_id)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } + if (empty($this->ref)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } + if (empty($this->date_solde)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateInitialBalance")); + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } - // Chargement librairie pour acces fonction controle RIB - require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; + // Chargement librairie pour acces fonction controle RIB + require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; - $now=dol_now(); + $now=dol_now(); - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account ("; - $sql.= "datec"; - $sql.= ", ref"; - $sql.= ", label"; - $sql.= ", entity"; - $sql.= ", account_number"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account ("; + $sql.= "datec"; + $sql.= ", ref"; + $sql.= ", label"; + $sql.= ", entity"; + $sql.= ", account_number"; $sql.= ", fk_accountancy_journal"; $sql.= ", bank"; - $sql.= ", code_banque"; - $sql.= ", code_guichet"; - $sql.= ", number"; - $sql.= ", cle_rib"; - $sql.= ", bic"; - $sql.= ", iban_prefix"; - $sql.= ", domiciliation"; - $sql.= ", proprio"; - $sql.= ", owner_address"; + $sql.= ", code_banque"; + $sql.= ", code_guichet"; + $sql.= ", number"; + $sql.= ", cle_rib"; + $sql.= ", bic"; + $sql.= ", iban_prefix"; + $sql.= ", domiciliation"; + $sql.= ", proprio"; + $sql.= ", owner_address"; $sql.= ", currency_code"; - $sql.= ", rappro"; - $sql.= ", min_allowed"; - $sql.= ", min_desired"; - $sql.= ", comment"; - $sql.= ", state_id"; - $sql.= ", fk_pays"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->idate($now)."'"; - $sql.= ", '".$this->db->escape($this->ref)."'"; - $sql.= ", '".$this->db->escape($this->label)."'"; - $sql.= ", ".$conf->entity; - $sql.= ", '".$this->db->escape($this->account_number)."'"; + $sql.= ", rappro"; + $sql.= ", min_allowed"; + $sql.= ", min_desired"; + $sql.= ", comment"; + $sql.= ", state_id"; + $sql.= ", fk_pays"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->idate($now)."'"; + $sql.= ", '".$this->db->escape($this->ref)."'"; + $sql.= ", '".$this->db->escape($this->label)."'"; + $sql.= ", ".$conf->entity; + $sql.= ", '".$this->db->escape($this->account_number)."'"; $sql.= ", ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); $sql.= ", '".$this->db->escape($this->bank)."'"; - $sql.= ", '".$this->code_banque."'"; - $sql.= ", '".$this->code_guichet."'"; - $sql.= ", '".$this->number."'"; - $sql.= ", '".$this->cle_rib."'"; - $sql.= ", '".$this->bic."'"; - $sql.= ", '".$this->iban."'"; - $sql.= ", '".$this->db->escape($this->domiciliation)."'"; - $sql.= ", '".$this->db->escape($this->proprio)."'"; - $sql.= ", '".$this->db->escape($this->owner_address)."'"; - $sql.= ", '".$this->currency_code."'"; - $sql.= ", ".$this->rappro; - $sql.= ", ".price2num($this->min_allowed); - $sql.= ", ".price2num($this->min_desired); - $sql.= ", '".$this->db->escape($this->comment)."'"; - $sql.= ", ".($this->state_id>0?"'".$this->state_id."'":"null"); - $sql.= ", ".$this->country_id; - $sql.= ")"; + $sql.= ", '".$this->db->escape($this->code_banque)."'"; + $sql.= ", '".$this->db->escape($this->code_guichet)."'"; + $sql.= ", '".$this->db->escape($this->number)."'"; + $sql.= ", '".$this->db->escape($this->cle_rib)."'"; + $sql.= ", '".$this->db->escape($this->bic)."'"; + $sql.= ", '".$this->db->escape($this->iban)."'"; + $sql.= ", '".$this->db->escape($this->domiciliation)."'"; + $sql.= ", '".$this->db->escape($this->proprio)."'"; + $sql.= ", '".$this->db->escape($this->owner_address)."'"; + $sql.= ", '".$this->db->escape($this->currency_code)."'"; + $sql.= ", ".$this->rappro; + $sql.= ", ".price2num($this->min_allowed); + $sql.= ", ".price2num($this->min_desired); + $sql.= ", '".$this->db->escape($this->comment)."'"; + $sql.= ", ".($this->state_id>0?$this->state_id:"null"); + $sql.= ", ".$this->country_id; + $sql.= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account"); + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account"); - $result=$this->update($user, 1); - if ($result > 0) - { + $result=$this->update($user, 1); + if ($result > 0) + { $accline = new AccountLine($this->db); $accline->datec = $this->db->idate($now); $accline->label = '('.$langs->trans("InitialBankBalance").')'; @@ -612,454 +613,455 @@ class Account extends CommonObject if ($accline->insert() < 0) { $error++; - $this->error = $accline->error; - $this->errors = $accline->errors; + $this->error = $accline->error; + $this->errors = $accline->errors; } if (! $error) { - $result=$this->insertExtraFields(); - if ($result < 0) $error++; + $result=$this->insertExtraFields(); + if ($result < 0) $error++; } - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('BANKACCOUNT_CREATE',$user); - if ($result < 0) $error++; - // End call triggers - } - } - else - { - $error++; - } - } - else - { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $this->error=$langs->trans("ErrorBankLabelAlreadyExists"); - $error++; - } - else { - $this->error=$this->db->error()." sql=".$sql; - $error++; - } - } - - if (! $error) - { - $this->db->commit(); - return $this->id; - } - else - { - $this->db->rollback(); - return -1*$error; - } - } - - /** - * Update bank account card - * - * @param User $user Object user making action - * @param int $notrigger 1=Disable triggers - * @return int <0 if KO, >0 if OK - */ - function update(User $user = null, $notrigger = 0) - { - global $langs,$conf, $hookmanager; - - $error=0; - - $this->db->begin(); - - // Clean parameters - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); - - // Check parameters - if (empty($this->country_id)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); - return -1; - } - if (empty($this->ref)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); - return -1; - } - if (! $this->label) $this->label = "???"; - - $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; - - $sql.= " ref = '".$this->db->escape($this->ref)."'"; - $sql.= ",label = '".$this->db->escape($this->label)."'"; - - $sql.= ",courant = ".$this->courant; - $sql.= ",clos = ".$this->clos; - $sql.= ",rappro = ".$this->rappro; - $sql.= ",url = ".($this->url?"'".$this->url."'":"null"); - $sql.= ",account_number = '".$this->db->escape($this->account_number)."'"; - $sql.= ",fk_accountancy_journal = ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); - $sql.= ",bank = '".$this->db->escape($this->bank)."'"; - $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; - $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; - $sql.= ",number='".$this->db->escape($this->number)."'"; - $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; - $sql.= ",bic='".$this->db->escape($this->bic)."'"; - $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; - $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; - $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; - $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - - $sql.= ",currency_code = '".$this->db->escape($this->currency_code)."'"; - - $sql.= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null"); - $sql.= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null"); - $sql.= ",comment = '".$this->db->escape($this->comment)."'"; - - $sql.= ",state_id = ".($this->state_id>0?"'".$this->state_id."'":"null"); - $sql.= ",fk_pays = ".$this->country_id; - - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - // Actions on extra fields (by external module or standard code) - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - if (! $error) - { - $result=$this->insertExtraFields(); - if ($result < 0) $error++; - } - } - - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('BANKACCOUNT_UPDATE',$user); - if ($result < 0) $error++; - // End call triggers - } - } - else - { - $error++; - $this->error=$this->db->lasterror(); - dol_print_error($this->db); - } - - if (! $error) - { - $this->db->commit(); - return $this->id; + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BANKACCOUNT_CREATE',$user); + if ($result < 0) $error++; + // End call triggers + } + } + else + { + $error++; + } } else { - $this->db->rollback(); - return -1*$error; + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $this->error=$langs->trans("ErrorBankLabelAlreadyExists"); + $error++; + } + else { + $this->error=$this->db->error()." sql=".$sql; + $error++; + } } - } + + if (! $error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1*$error; + } + } + + /** + * Update bank account card + * + * @param User $user Object user making action + * @param int $notrigger 1=Disable triggers + * @return int <0 if KO, >0 if OK + */ + function update(User $user = null, $notrigger = 0) + { + global $langs,$conf, $hookmanager; + + $error=0; + + $this->db->begin(); + + // Clean parameters + $this->state_id = ($this->state_id?$this->state_id:$this->state_id); + $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + + // Check parameters + if (empty($this->country_id)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); + dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); + return -1; + } + if (empty($this->ref)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); + dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); + return -1; + } + if (! $this->label) $this->label = "???"; + + $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; + + $sql.= " ref = '".$this->db->escape($this->ref)."'"; + $sql.= ",label = '".$this->db->escape($this->label)."'"; + + $sql.= ",courant = ".$this->courant; + $sql.= ",clos = ".$this->clos; + $sql.= ",rappro = ".$this->rappro; + $sql.= ",url = ".($this->url?"'".$this->db->escape($this->url)."'":"null"); + $sql.= ",account_number = '".$this->db->escape($this->account_number)."'"; + $sql.= ",fk_accountancy_journal = ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); + $sql.= ",bank = '".$this->db->escape($this->bank)."'"; + $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; + $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; + $sql.= ",number='".$this->db->escape($this->number)."'"; + $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; + $sql.= ",bic='".$this->db->escape($this->bic)."'"; + $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; + $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; + $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; + $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; + + $sql.= ",currency_code = '".$this->db->escape($this->currency_code)."'"; + + $sql.= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null"); + $sql.= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null"); + $sql.= ",comment = '".$this->db->escape($this->comment)."'"; + + $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); + $sql.= ",fk_pays = ".$this->country_id; + + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + // Actions on extra fields (by external module or standard code) + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + if (! $error) + { + $result=$this->insertExtraFields(); + if ($result < 0) $error++; + } + } + + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BANKACCOUNT_UPDATE',$user); + if ($result < 0) $error++; + // End call triggers + } + } + else + { + $error++; + $this->error=$this->db->lasterror(); + dol_print_error($this->db); + } + + if (! $error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1*$error; + } + } - /** - * Update BBAN (RIB) account fields - * - * @param User $user Object user making update - * @return int <0 if KO, >0 if OK - */ - function update_bban(User $user = null) - { - global $conf,$langs; + /** + * Update BBAN (RIB) account fields + * + * @param User $user Object user making update + * @return int <0 if KO, >0 if OK + */ + function update_bban(User $user = null) + { + global $conf,$langs; - // Clean parameters - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + // Clean parameters + $this->state_id = ($this->state_id?$this->state_id:$this->state_id); + $this->country_id = ($this->country_id?$this->country_id:$this->country_id); - // Chargement librairie pour acces fonction controle RIB - require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; + // Chargement librairie pour acces fonction controle RIB + require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; - dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban"); + dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban"); - // Check parameters - if (! $this->ref) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->trans("Ref")); - return -2; - } + // Check parameters + if (! $this->ref) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->trans("Ref")); + return -2; + } - $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; - $sql.= " bank = '".$this->db->escape($this->bank)."'"; - $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; - $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; - $sql.= ",number='".$this->db->escape($this->number)."'"; - $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; - $sql.= ",bic='".$this->db->escape($this->bic)."'"; - $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; - $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; - $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; - $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - $sql.= ",state_id = ".($this->state_id>0?"'".$this->state_id."'":"null"); - $sql.= ",fk_pays = ".$this->country_id; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; + $sql.= " bank = '".$this->db->escape($this->bank)."'"; + $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; + $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; + $sql.= ",number='".$this->db->escape($this->number)."'"; + $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; + $sql.= ",bic='".$this->db->escape($this->bic)."'"; + $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; + $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; + $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; + $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; + $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); + $sql.= ",fk_pays = ".$this->country_id; + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; - dol_syslog(get_class($this)."::update_bban", LOG_DEBUG); + dol_syslog(get_class($this)."::update_bban", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - return 1; - } - else - { - $this->error=$this->db->lasterror(); - dol_print_error($this->db); - return -1; - } - } + $result = $this->db->query($sql); + if ($result) + { + return 1; + } + else + { + $this->error=$this->db->lasterror(); + dol_print_error($this->db); + return -1; + } + } - /** - * Load a bank account into memory from database - * - * @param int $id Id of bank account to get - * @param string $ref Ref of bank account to get - * @return int <0 if KO, >0 if OK - */ - function fetch($id, $ref='') - { - global $conf; + /** + * Load a bank account into memory from database + * + * @param int $id Id of bank account to get + * @param string $ref Ref of bank account to get + * @return int <0 if KO, >0 if OK + */ + function fetch($id, $ref='') + { + global $conf; - if (empty($id) && empty($ref)) - { - $this->error="ErrorBadParameters"; - return -1; - } + if (empty($id) && empty($ref)) + { + $this->error="ErrorBadParameters"; + return -1; + } - $sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,"; - $sql.= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,"; - $sql.= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,"; - $sql.= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,"; - $sql.= " ba.min_allowed, ba.min_desired, ba.comment,"; - $sql.= " ba.datec as date_creation, ba.tms as date_update,"; - $sql.= ' c.code as country_code, c.label as country,'; - $sql.= ' d.code_departement as state_code, d.nom as state'; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid'; - $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; - if ($id) $sql.= " AND ba.rowid = ".$id; - if ($ref) $sql.= " AND ba.ref = '".$this->db->escape($ref)."'"; + $sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,"; + $sql.= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,"; + $sql.= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,"; + $sql.= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,"; + $sql.= " ba.min_allowed, ba.min_desired, ba.comment,"; + $sql.= " ba.datec as date_creation, ba.tms as date_update,"; + $sql.= ' c.code as country_code, c.label as country,'; + $sql.= ' d.code_departement as state_code, d.nom as state'; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid'; + $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; + if ($id) $sql.= " AND ba.rowid = ".$id; + if ($ref) $sql.= " AND ba.ref = '".$this->db->escape($ref)."'"; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; - $this->rowid = $obj->rowid; - $this->ref = $obj->ref; - $this->label = $obj->label; - $this->type = $obj->courant; - $this->courant = $obj->courant; - $this->bank = $obj->bank; - $this->clos = $obj->clos; - $this->rappro = $obj->rappro; - $this->url = $obj->url; + $this->id = $obj->rowid; + $this->rowid = $obj->rowid; + $this->ref = $obj->ref; + $this->label = $obj->label; + $this->type = $obj->courant; + $this->courant = $obj->courant; + $this->bank = $obj->bank; + $this->clos = $obj->clos; + $this->rappro = $obj->rappro; + $this->url = $obj->url; - $this->code_banque = $obj->code_banque; - $this->code_guichet = $obj->code_guichet; - $this->number = $obj->number; - $this->cle_rib = $obj->cle_rib; - $this->bic = $obj->bic; - $this->iban = $obj->iban; - $this->domiciliation = $obj->domiciliation; - $this->proprio = $obj->proprio; - $this->owner_address = $obj->owner_address; + $this->code_banque = $obj->code_banque; + $this->code_guichet = $obj->code_guichet; + $this->number = $obj->number; + $this->cle_rib = $obj->cle_rib; + $this->bic = $obj->bic; + $this->iban = $obj->iban; + $this->domiciliation = $obj->domiciliation; + $this->proprio = $obj->proprio; + $this->owner_address = $obj->owner_address; - $this->state_id = $obj->state_id; - $this->state_code = $obj->state_code; - $this->state = $obj->state; + $this->state_id = $obj->state_id; + $this->state_code = $obj->state_code; + $this->state = $obj->state; - $this->country_id = $obj->country_id; - $this->country_code = $obj->country_code; - $this->country = $obj->country; + $this->country_id = $obj->country_id; + $this->country_code = $obj->country_code; + $this->country = $obj->country; - $this->account_number = $obj->account_number; + $this->account_number = $obj->account_number; $this->fk_accountancy_journal = $obj->fk_accountancy_journal; - $this->currency_code = $obj->currency_code; - $this->account_currency_code = $obj->currency_code; - $this->min_allowed = $obj->min_allowed; - $this->min_desired = $obj->min_desired; - $this->comment = $obj->comment; + $this->currency_code = $obj->currency_code; + $this->account_currency_code = $obj->currency_code; + $this->min_allowed = $obj->min_allowed; + $this->min_desired = $obj->min_desired; + $this->comment = $obj->comment; - $this->date_creation = $this->db->jdate($obj->date_creation); - $this->date_update = $this->db->jdate($obj->date_update); + $this->date_creation = $this->db->jdate($obj->date_creation); + $this->date_update = $this->db->jdate($obj->date_update); - // Retreive all extrafield for thirdparty - // fetch optionals attributes and labels - require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + // Retreive all extrafield for thirdparty + // fetch optionals attributes and labels + require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + $this->fetch_optionals($this->id,$extralabels); - return 1; - } - else + return 1; + } + else { - return 0; - } - } - else - { - dol_print_error($this->db); - return -1; - } - } + return 0; + } + } + else + { + $this->error=$this->db->lasterror; + $this->errors[]=$this->error; + return -1; + } + } - /** - * Sets object to supplied categories. - * - * Deletes object from existing categories not supplied. - * Adds it to non existing supplied categories. - * Existing categories are left untouch. - * - * @param int[]|int $categories Category or categories IDs - */ - public function setCategories($categories) { - // Handle single category - if (! is_array($categories)) { - $categories = array($categories); - } + /** + * Sets object to supplied categories. + * + * Deletes object from existing categories not supplied. + * Adds it to non existing supplied categories. + * Existing categories are left untouch. + * + * @param int[]|int $categories Category or categories IDs + */ + public function setCategories($categories) { + // Handle single category + if (! is_array($categories)) { + $categories = array($categories); + } - // Get current categories - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $c = new Categorie($this->db); - $existing = $c->containing($this->id, Categorie::TYPE_ACCOUNT, 'id'); + // Get current categories + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $c = new Categorie($this->db); + $existing = $c->containing($this->id, Categorie::TYPE_ACCOUNT, 'id'); - // Diff - if (is_array($existing)) { - $to_del = array_diff($existing, $categories); - $to_add = array_diff($categories, $existing); - } else { - $to_del = array(); // Nothing to delete - $to_add = $categories; - } + // Diff + if (is_array($existing)) { + $to_del = array_diff($existing, $categories); + $to_add = array_diff($categories, $existing); + } else { + $to_del = array(); // Nothing to delete + $to_add = $categories; + } - // Process - foreach($to_del as $del) { - if ($c->fetch($del) > 0) { - $c->del_type($this, 'account'); - } - } - foreach ($to_add as $add) { - if ($c->fetch($add) > 0) { - $c->add_type($this, 'account'); - } - } + // Process + foreach($to_del as $del) { + if ($c->fetch($del) > 0) { + $c->del_type($this, 'account'); + } + } + foreach ($to_add as $add) { + if ($c->fetch($add) > 0) { + $c->add_type($this, 'account'); + } + } - return; - } + return; + } - /** - * Delete bank account from database - * - * @param User $user User deleting - * @return int <0 if KO, >0 if OK - */ - function delete(User $user = null) - { - global $conf; + /** + * Delete bank account from database + * + * @param User $user User deleting + * @return int <0 if KO, >0 if OK + */ + function delete(User $user = null) + { + global $conf; - $error=0; + $error=0; - $this->db->begin(); + $this->db->begin(); - // Delete link between tag and bank account - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account"; - $sql.= " WHERE fk_account = ".$this->id; + // Delete link between tag and bank account + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account"; + $sql.= " WHERE fk_account = ".$this->id; - $resql = $this->db->query($sql); - if (!$resql) - { - $error++; - $this->error = "Error ".$this->db->lasterror(); - } - } + $resql = $this->db->query($sql); + if (!$resql) + { + $error++; + $this->error = "Error ".$this->db->lasterror(); + } + } - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_account"; - $sql.= " WHERE rowid = ".$this->rowid; + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_account"; + $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - // Remove extrafields - if ((empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used - { - $result=$this->deleteExtraFields(); - if ($result < 0) - { - $error++; - dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); - } - } - } - else - { - $error++; - $this->error = "Error ".$this->db->lasterror(); - } - } + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + // Remove extrafields + if ((empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + { + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); + } + } + } + else + { + $error++; + $this->error = "Error ".$this->db->lasterror(); + } + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } - /** + /** * Return label of object status - * + * * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto - * @return string Label - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->clos,$mode); - } + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->clos,$mode); + } - /** - * Return label of given object status - * - * @param int $statut Id statut + /** + * Return label of given object status + * + * @param int $statut Id statut * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto - * @return string Label - */ + * @return string Label + */ function LibStatut($statut, $mode = 0) { global $langs; @@ -1082,7 +1084,7 @@ class Account extends CommonObject } elseif ($mode == 5) { return $label.' '.$picto; } elseif ($mode == 6) { - return $label.' '.$picto; + return $label.' '.$picto; } //There is no short mode for this label @@ -1090,341 +1092,397 @@ class Account extends CommonObject } - /** - * Renvoi si un compte peut etre supprimer ou non (sans mouvements) - * - * @return boolean vrai si peut etre supprime, faux sinon - */ - function can_be_deleted() - { - $can_be_deleted=false; + /** + * Renvoi si un compte peut etre supprimer ou non (sans mouvements) + * + * @return boolean vrai si peut etre supprime, faux sinon + */ + function can_be_deleted() + { + $can_be_deleted=false; - $sql = "SELECT COUNT(rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account=".$this->id; + $sql = "SELECT COUNT(rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank"; + $sql.= " WHERE fk_account=".$this->id; - $resql = $this->db->query($sql); - if ($resql) { - $obj=$this->db->fetch_object($resql); - if ($obj->nb <= 1) $can_be_deleted=true; // Juste le solde - } - else { - dol_print_error($this->db); - } - return $can_be_deleted; - } + $resql = $this->db->query($sql); + if ($resql) { + $obj=$this->db->fetch_object($resql); + if ($obj->nb <= 1) $can_be_deleted=true; // Juste le solde + } + else { + dol_print_error($this->db); + } + return $can_be_deleted; + } - /** - * Return error - * - * @return string Error string - */ - function error() - { - return $this->error; - } + /** + * Return error + * + * @return string Error string + */ + function error() + { + return $this->error; + } - /** - * Return current sold - * - * @param int $option 1=Exclude future operation date (this is to exclude input made in advance and have real account sold) - * @return int Current sold (value date <= today) - */ - function solde($option=0) - { - $sql = "SELECT sum(amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account = ".$this->id; - if ($option == 1) $sql.= " AND dateo <= '".$this->db->idate(dol_now())."'"; + /** + * Return current sold + * + * @param int $option 1=Exclude future operation date (this is to exclude input made in advance and have real account sold) + * @return int Current sold (value date <= today) + */ + function solde($option=0) + { + $sql = "SELECT sum(amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank"; + $sql.= " WHERE fk_account = ".$this->id; + if ($option == 1) $sql.= " AND dateo <= '".$this->db->idate(dol_now())."'"; - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj=$this->db->fetch_object($resql); - $solde = $obj->amount; - } - $this->db->free($resql); - return $solde; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj=$this->db->fetch_object($resql); + $solde = $obj->amount; + } + $this->db->free($resql); + return $solde; + } + } - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @param int $filteraccountid To get info for a particular account id - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - function load_board(User $user, $filteraccountid = 0) - { - global $conf, $langs; + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @param int $filteraccountid To get info for a particular account id + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + function load_board(User $user, $filteraccountid = 0) + { + global $conf, $langs; - if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe + if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe - $sql = "SELECT b.rowid, b.datev as datefin"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; - $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.rappro=0"; - $sql.= " AND b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable - $sql.= " AND clos = 0"; - if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; + $sql = "SELECT b.rowid, b.datev as datefin"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.rappro=0"; + $sql.= " AND b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable + $sql.= " AND clos = 0"; + if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; - $resql=$this->db->query($sql); - if ($resql) - { - $langs->load("banks"); - $now=dol_now(); + $resql=$this->db->query($sql); + if ($resql) + { + $langs->load("banks"); + $now=dol_now(); - require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php'; - $response = new WorkboardResponse(); - $response->warning_delay=$conf->bank->rappro->warning_delay/60/60/24; - $response->label=$langs->trans("TransactionsToConciliate"); - $response->url=DOL_URL_ROOT.'/compta/bank/index.php?leftmenu=bank&mainmenu=bank'; - $response->img=img_object('',"payment"); + $response = new WorkboardResponse(); + $response->warning_delay=$conf->bank->rappro->warning_delay/60/60/24; + $response->label=$langs->trans("TransactionsToConciliate"); + $response->url=DOL_URL_ROOT.'/compta/bank/list.php?leftmenu=bank&mainmenu=bank'; + $response->img=img_object('',"payment"); - while ($obj=$this->db->fetch_object($resql)) - { - $response->nbtodo++; - if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->rappro->warning_delay)) { - $response->nbtodolate++; - } - } + while ($obj=$this->db->fetch_object($resql)) + { + $response->nbtodo++; + if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->rappro->warning_delay)) { + $response->nbtodolate++; + } + } - return $response; - } - else - { - dol_print_error($this->db); - $this->error=$this->db->error(); - return -1; - } - } + return $response; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } + + /** + * Charge indicateurs this->nb de tableau de bord + * @param int $filteraccountid To get info for a particular account id + * @return int <0 if ko, >0 if ok + */ + function load_state_board($filteraccountid = 0) + { + global $user; + + if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe + + $sql = "SELECT count(b.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable + $sql.= " AND clos = 0"; + if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; + + $resql=$this->db->query($sql); + if ($resql) + { + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["banklines"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @return int Nb of account we can reconciliate - */ - public static function countAccountToReconcile() - { - global $db, $conf, $user; + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @return int Nb of account we can reconciliate + */ + public static function countAccountToReconcile() + { + global $db, $conf, $user; - //Protection against external users - if ($user->societe_id) { - return 0; - } + //Protection against external users + if ($user->societe_id) { + return 0; + } - $nb=0; + $nb=0; - $sql = "SELECT COUNT(ba.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE ba.rappro > 0 and ba.clos = 0"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql.= " AND ba.courant != 2"; - $resql=$db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $nb = $obj->nb; - } - else dol_print_error($db); + $sql = "SELECT COUNT(ba.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE ba.rappro > 0 and ba.clos = 0"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql.= " AND ba.courant != 2"; + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $nb = $obj->nb; + } + else dol_print_error($db); - return $nb; - } + return $nb; + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto Include picto into link - * @param string $mode ''=Link to card, 'transactions'=Link to transactions card - * @param string $option ''=Show ref, 'reflabel'=Show ref+label - * @return string Chaine avec URL - */ - function getNomUrl($withpicto=0, $mode='', $option='') - { - global $conf, $langs; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto Include picto into link + * @param string $mode ''=Link to card, 'transactions'=Link to transactions card + * @param string $option ''=Show ref, 'reflabel'=Show ref+label + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL + */ + function getNomUrl($withpicto=0, $mode='', $option='', $save_lastsearch_value=-1) + { + global $conf, $langs; - $result=''; - $label = '' . $langs->trans("ShowAccount") . ''; - $label .= '
    ' . $langs->trans('BankAccount') . ': ' . $this->label; - $label .= '
    ' . $langs->trans('AccountNumber') . ': ' . $this->number; - if (! empty($conf->accounting->enabled)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; - $langs->load("accountancy"); - $label .= '
    ' . $langs->trans('AccountAccounting') . ': ' . length_accountg($this->account_number); - $label .= '
    ' . $langs->trans('AccountancyJournal') . ': ' . $this->accountancy_journal; - } - $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + $result=''; + $label = '' . $langs->trans("ShowAccount") . ''; + $label .= '
    ' . $langs->trans('BankAccount') . ': ' . $this->label; + $label .= '
    ' . $langs->trans('AccountNumber') . ': ' . $this->number; + $label .= '
    ' . $langs->trans("AccountCurrency") . ': ' . $this->currency_code; + if (! empty($conf->accounting->enabled)) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + $langs->load("accountancy"); + $label .= '
    ' . $langs->trans('AccountAccounting') . ': ' . length_accountg($this->account_number); + $label .= '
    ' . $langs->trans('AccountancyJournal') . ': ' . $this->accountancy_journal; + } + $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; - if (empty($mode)) - { - $link = ''; - } - else if ($mode == 'receipts') - { - $link = 'ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : '').$linkend; - return $result; - } + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + + $linkstart = 'ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : ''); + $result .= $linkend; + + return $result; + } - // Method after here are common to Account and CompanyBankAccount + // Method after here are common to Account and CompanyBankAccount - /** - * Return if an account has valid information - * - * @return int 1 if correct, <=0 if wrong - */ - function verif() - { - require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; + /** + * Return if an account has valid information for Direct debit payment + * + * @return int 1 if correct, <=0 if wrong + */ + function verif() + { + require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; - // Call function to check BAN - if (! checkBanForAccount($this)) + $this->error_number = 0; + + // Call function to check BAN + + if (! checkIbanForAccount($this) || ! checkSwiftForAccount($this)) + { + $this->error_number = 12; + $this->error_message = 'IBANSWIFTControlError'; + } + /*if (! checkBanForAccount($this)) { $this->error_number = 12; - $this->error_message = 'RIBControlError'; - } + $this->error_message = 'BANControlError'; + }*/ - if ($this->error_number == 0) - { - return 1; - } - else - { - return 0; - } - } + if ($this->error_number == 0) + { + return 1; + } + else + { + return 0; + } + } - /** - * Return account country code - * - * @return string country code - */ - function getCountryCode() - { - global $mysoc; + /** + * Return account country code + * + * @return string country code + */ + function getCountryCode() + { + global $mysoc; - // We return country code of bank account - if (! empty($this->country_code)) return $this->country_code; + // We return country code of bank account + if (! empty($this->country_code)) return $this->country_code; - // For backward compatibility, we try to guess country from other information - if (! empty($this->iban)) - { - // If IBAN defined, we can know country of account from it - if (preg_match("/^([a-zA-Z][a-zA-Z])/i",$this->iban,$reg)) return $reg[1]; - } + // For backward compatibility, we try to guess country from other information + if (! empty($this->iban)) + { + // If IBAN defined, we can know country of account from it + if (preg_match("/^([a-zA-Z][a-zA-Z])/i",$this->iban,$reg)) return $reg[1]; + } - // If this class is linked to a third party - if (! empty($this->socid)) - { - require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; - $company=new Societe($this->db); - $result=$company->fetch($this->socid); - if (! empty($company->country_code)) return $company->country_code; - } + // If this class is linked to a third party + if (! empty($this->socid)) + { + require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; + $company=new Societe($this->db); + $result=$company->fetch($this->socid); + if (! empty($company->country_code)) return $company->country_code; + } - // We return country code of managed company - if (! empty($mysoc->country_code)) return $mysoc->country_code; + // We return country code of managed company + if (! empty($mysoc->country_code)) return $mysoc->country_code; - return ''; - } + return ''; + } - /** - * Return if a bank account is defined with detailed information (bank code, desk code, number and key). - * More information on codes used by countries on page http://en.wikipedia.org/wiki/Bank_code - * - * @return int 0=No bank code need + Account number is enough - * 1=Need 2 fields for bank code: Bank, Desk (France, Spain, ...) + Account number and key - * 2=Need 1 field for bank code: Bank only (Sort code for Great Britain, BSB for Australia) + Account number - */ - function useDetailedBBAN() - { - $country_code=$this->getCountryCode(); + /** + * Return if a bank account is defined with detailed information (bank code, desk code, number and key). + * More information on codes used by countries on page http://en.wikipedia.org/wiki/Bank_code + * + * @return int 0=No bank code need + Account number is enough + * 1=Need 2 fields for bank code: Bank, Desk (France, Spain, ...) + Account number and key + * 2=Need 1 field for bank code: Bank only (Sort code for Great Britain, BSB for Australia) + Account number + */ + function useDetailedBBAN() + { + $country_code=$this->getCountryCode(); - if (in_array($country_code,array('CH','FR','ES','GA','IT','NC'))) return 1; // France, Spain, Gabon, ... - if (in_array($country_code,array('AU','BE','CA','DE','DK','GR','GB','ID','IE','IR','KR','NL','NZ','UK','US'))) return 2; // Australia, England... - return 0; - } + if (in_array($country_code,array('CH','FR','ES','GA','IT','NC'))) return 1; // France, Spain, Gabon, ... + if (in_array($country_code,array('AU','BE','CA','DE','DK','GR','GB','ID','IE','IR','KR','NL','NZ','UK','US'))) return 2; // Australia, England... + return 0; + } - /** - * Return 1 if IBAN / BIC is mandatory (otherwise option) - * - * @return int 1 = mandatory / 0 = Not mandatory - */ - function needIBAN() - { - $country_code=$this->getCountryCode(); + /** + * Return 1 if IBAN / BIC is mandatory (otherwise option) + * + * @return int 1 = mandatory / 0 = Not mandatory + */ + function needIBAN() + { + $country_code=$this->getCountryCode(); - $country_code_in_EEC=array( - 'AT', // Austria - 'BE', // Belgium - 'BG', // Bulgaria - 'CY', // Cyprus - 'CZ', // Czech republic - 'DE', // Germany - 'DK', // Danemark - 'EE', // Estonia - 'ES', // Spain - 'FI', // Finland - 'FR', // France - 'GB', // United Kingdom - 'GR', // Greece - 'HR', // Croatia - 'NL', // Holland - 'HU', // Hungary - 'IE', // Ireland - 'IM', // Isle of Man - Included in UK - 'IT', // Italy - 'LT', // Lithuania - 'LU', // Luxembourg - 'LV', // Latvia - 'MC', // Monaco - Included in France - 'MT', // Malta - //'NO', // Norway - 'PL', // Poland - 'PT', // Portugal - 'RO', // Romania - 'SE', // Sweden - 'SK', // Slovakia - 'SI', // Slovenia - 'UK', // United Kingdom - //'CH', // Switzerland - No. Swizerland in not in EEC - ); + $country_code_in_EEC=array( + 'AT', // Austria + 'BE', // Belgium + 'BG', // Bulgaria + 'CY', // Cyprus + 'CZ', // Czech republic + 'DE', // Germany + 'DK', // Danemark + 'EE', // Estonia + 'ES', // Spain + 'FI', // Finland + 'FR', // France + 'GB', // United Kingdom + 'GR', // Greece + 'HR', // Croatia + 'NL', // Holland + 'HU', // Hungary + 'IE', // Ireland + 'IM', // Isle of Man - Included in UK + 'IT', // Italy + 'LT', // Lithuania + 'LU', // Luxembourg + 'LV', // Latvia + 'MC', // Monaco - Included in France + 'MT', // Malta + //'NO', // Norway + 'PL', // Poland + 'PT', // Portugal + 'RO', // Romania + 'SE', // Sweden + 'SK', // Slovakia + 'SI', // Slovenia + 'UK', // United Kingdom + //'CH', // Switzerland - No. Swizerland in not in EEC + ); - if (in_array($country_code,$country_code_in_EEC)) return 1; // France, Spain, ... - return 0; - } + if (in_array($country_code,$country_code_in_EEC)) return 1; // France, Spain, ... + return 0; + } - /** - * Load miscellaneous information for tab "Info" - * - * @param int $id Id of object to load - * @return void - */ - function info($id) - { + /** + * Load miscellaneous information for tab "Info" + * + * @param int $id Id of object to load + * @return void + */ + function info($id) + { - } + } /** * Returns the fields in order that this bank account should show to the user @@ -1516,32 +1574,32 @@ class Account extends CommonObject } - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - function initAsSpecimen() - { - $this->specimen = 1; - $this->ref = 'MBA'; - $this->label = 'My Big Company Bank account'; - $this->bank = 'MyBank'; - $this->courant = Account::TYPE_CURRENT; - $this->clos = Account::STATUS_OPEN; - $this->code_banque = '123'; - $this->code_guichet = '456'; - $this->number = 'ABC12345'; - $this->cle_rib = 50; - $this->bic = 'AA12'; - $this->iban = 'FR999999999'; - $this->domiciliation = 'My bank address'; - $this->proprio = 'Owner'; - $this->owner_address = 'Owner address'; - $this->country_id = 1; - } + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + $this->specimen = 1; + $this->ref = 'MBA'; + $this->label = 'My Big Company Bank account'; + $this->bank = 'MyBank'; + $this->courant = Account::TYPE_CURRENT; + $this->clos = Account::STATUS_OPEN; + $this->code_banque = '123'; + $this->code_guichet = '456'; + $this->number = 'ABC12345'; + $this->cle_rib = 50; + $this->bic = 'AA12'; + $this->iban = 'FR999999999'; + $this->domiciliation = 'My bank address'; + $this->proprio = 'Owner'; + $this->owner_address = 'Owner address'; + $this->country_id = 1; + } } @@ -1551,122 +1609,122 @@ class Account extends CommonObject */ class AccountLine extends CommonObject { - var $error; - var $db; - var $element='bank'; - var $table_element='bank'; - var $picto = 'generic'; + var $error; + var $db; + var $element='bank'; + var $table_element='bank'; + var $picto = 'generic'; - var $id; - var $ref; - var $datec; - var $dateo; + var $id; + var $ref; + var $datec; + var $dateo; - /** - * Value date - */ - var $datev; - var $amount; - var $label; - var $note; - var $fk_user_author; - var $fk_user_rappro; - var $fk_type; - var $rappro; // Is it conciliated - var $num_releve; // If conciliated, what is bank statement - var $num_chq; // Num of cheque - var $bank_chq; // Bank of cheque - var $fk_bordereau; // Id of cheque receipt + /** + * Value date + */ + var $datev; + var $amount; + var $label; + var $note; + var $fk_user_author; + var $fk_user_rappro; + var $fk_type; + var $rappro; // Is it conciliated + var $num_releve; // If conciliated, what is bank statement + var $num_chq; // Num of cheque + var $bank_chq; // Bank of cheque + var $fk_bordereau; // Id of cheque receipt - var $fk_account; // Id of bank account - var $bank_account_label; // Label of bank account + var $fk_account; // Id of bank account + var $bank_account_label; // Label of bank account - public $emetteur; + public $emetteur; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct(DoliDB $db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct(DoliDB $db) + { + $this->db = $db; + } - /** - * Load into memory content of a bank transaction line - * - * @param int $rowid Id of bank transaction to load - * @param string $ref Ref of bank transaction to load - * @param string $num External num to load (ex: num of transaction for paypal fee) - * @return int <0 if KO, 0 if OK but not found, >0 if OK and found - */ - function fetch($rowid,$ref='',$num='') - { - global $conf; + /** + * Load into memory content of a bank transaction line + * + * @param int $rowid Id of bank transaction to load + * @param string $ref Ref of bank transaction to load + * @param string $num External num to load (ex: num of transaction for paypal fee) + * @return int <0 if KO, 0 if OK but not found, >0 if OK and found + */ + function fetch($rowid,$ref='',$num='') + { + global $conf; - // Check parameters - if (empty($rowid) && empty($ref) && empty($num)) return -1; + // Check parameters + if (empty($rowid) && empty($ref) && empty($num)) return -1; - $sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,"; - $sql.= " b.fk_user_author, b.fk_user_rappro,"; - $sql.= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,"; - $sql.= " b.fk_bordereau, b.banque, b.emetteur,"; - //$sql.= " b.author"; // Is this used ? - $sql.= " ba.ref as bank_account_ref, ba.label as bank_account_label"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; - $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if ($num) $sql.= " AND b.num_chq='".$this->db->escape($num)."'"; - else if ($ref) $sql.= " AND b.rowid='".$this->db->escape($ref)."'"; - else $sql.= " AND b.rowid=".$rowid; + $sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,"; + $sql.= " b.fk_user_author, b.fk_user_rappro,"; + $sql.= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,"; + $sql.= " b.fk_bordereau, b.banque, b.emetteur,"; + //$sql.= " b.author"; // Is this used ? + $sql.= " ba.ref as bank_account_ref, ba.label as bank_account_label"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + if ($num) $sql.= " AND b.num_chq='".$this->db->escape($num)."'"; + else if ($ref) $sql.= " AND b.rowid='".$this->db->escape($ref)."'"; + else $sql.= " AND b.rowid=".$rowid; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $ret=0; + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $ret=0; - $obj = $this->db->fetch_object($result); - if ($obj) - { - $this->id = $obj->rowid; - $this->rowid = $obj->rowid; - $this->ref = $obj->rowid; + $obj = $this->db->fetch_object($result); + if ($obj) + { + $this->id = $obj->rowid; + $this->rowid = $obj->rowid; + $this->ref = $obj->rowid; - $this->datec = $obj->datec; - $this->datev = $obj->datev; - $this->dateo = $obj->dateo; - $this->amount = $obj->amount; - $this->label = $obj->label; - $this->note = $obj->note; + $this->datec = $obj->datec; + $this->datev = $obj->datev; + $this->dateo = $obj->dateo; + $this->amount = $obj->amount; + $this->label = $obj->label; + $this->note = $obj->note; - $this->fk_user_author = $obj->fk_user_author; - $this->fk_user_rappro = $obj->fk_user_rappro; + $this->fk_user_author = $obj->fk_user_author; + $this->fk_user_rappro = $obj->fk_user_rappro; - $this->fk_type = $obj->fk_type; // Type of transaction - $this->rappro = $obj->rappro; - $this->num_releve = $obj->num_releve; + $this->fk_type = $obj->fk_type; // Type of transaction + $this->rappro = $obj->rappro; + $this->num_releve = $obj->num_releve; - $this->num_chq = $obj->num_chq; - $this->bank_chq = $obj->banque; - $this->fk_bordereau = $obj->fk_bordereau; + $this->num_chq = $obj->num_chq; + $this->bank_chq = $obj->banque; + $this->fk_bordereau = $obj->fk_bordereau; - $this->fk_account = $obj->fk_account; - $this->bank_account_ref = $obj->bank_account_ref; - $this->bank_account_label = $obj->bank_account_label; + $this->fk_account = $obj->fk_account; + $this->bank_account_ref = $obj->bank_account_ref; + $this->bank_account_label = $obj->bank_account_label; - $ret=1; - } - $this->db->free($result); - return $ret; - } - else - { - return -1; - } - } + $ret=1; + } + $this->db->free($result); + return $ret; + } + else + { + return -1; + } + } /** * Inserts a transaction to a bank account @@ -1694,9 +1752,9 @@ class AccountLine extends CommonObject $sql .= ", '".$this->db->idate($this->datev)."'"; $sql .= ", '".$this->db->escape($this->label)."'"; $sql .= ", ".price2num($this->amount); - $sql .= ", ".($this->fk_user_author > 0 ? "'".$this->fk_user_author."'":"null"); - $sql .= ", ".($this->num_chq ? "'".$this->num_chq."'" : "null"); - $sql .= ", '".$this->fk_account."'"; + $sql .= ", ".($this->fk_user_author > 0 ? $this->fk_user_author :"null"); + $sql .= ", ".($this->num_chq ? "'".$this->db->escape($this->num_chq)."'" : "null"); + $sql .= ", '".$this->db->escape($this->fk_account)."'"; $sql .= ", '".$this->db->escape($this->fk_type)."'"; $sql .= ", ".($this->emetteur ? "'".$this->db->escape($this->emetteur)."'" : "null"); $sql .= ", ".($this->bank_chq ? "'".$this->db->escape($this->bank_chq)."'" : "null"); @@ -1717,359 +1775,420 @@ class AccountLine extends CommonObject return $this->id; } - /** - * Delete transaction bank line record - * - * @param User $user User object that delete - * @return int <0 if KO, >0 if OK - */ - function delete(User $user = null) - { - $nbko=0; + /** + * Delete transaction bank line record + * + * @param User $user User object that delete + * @return int <0 if KO, >0 if OK + */ + function delete(User $user = null) + { + $nbko=0; - if ($this->rappro) - { - // Protection to avoid any delete of consolidated lines - $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; - return -1; - } + if ($this->rappro) + { + // Protection to avoid any delete of consolidated lines + $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; + return -1; + } - $this->db->begin(); + $this->db->begin(); - // Delete urls - $result=$this->delete_urls($user); - if ($result < 0) - { - $nbko++; - } + // Delete urls + $result=$this->delete_urls($user); + if ($result < 0) + { + $nbko++; + } - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $result = $this->db->query($sql); - if (! $result) $nbko++; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) $nbko++; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $result = $this->db->query($sql); - if (! $result) $nbko++; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) $nbko++; - if (! $nbko) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -$nbko; - } - } + if (! $nbko) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -$nbko; + } + } - /** - * Delete bank line records - * - * @param User $user User object that delete - * @return int <0 if KO, >0 if OK - */ - function delete_urls(User $user = null) - { - $nbko=0; + /** + * Delete bank line records + * + * @param User $user User object that delete + * @return int <0 if KO, >0 if OK + */ + function delete_urls(User $user = null) + { + $nbko=0; - if ($this->rappro) - { - // Protection to avoid any delete of consolidated lines - $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; - return -1; - } + if ($this->rappro) + { + // Protection to avoid any delete of consolidated lines + $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; + return -1; + } - $this->db->begin(); + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid; - dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG); - $result = $this->db->query($sql); - if (! $result) $nbko++; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid; + dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) $nbko++; - if (! $nbko) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -$nbko; - } - } + if (! $nbko) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -$nbko; + } + } - /** - * Update bank account record in database - * - * @param User $user Object user making update - * @param int $notrigger 0=Disable all triggers - * @return int <0 if KO, >0 if OK - */ - function update(User $user, $notrigger = 0) - { - $this->db->begin(); + /** + * Update bank account record in database + * + * @param User $user Object user making update + * @param int $notrigger 0=Disable all triggers + * @return int <0 if KO, >0 if OK + */ + function update(User $user, $notrigger = 0) + { + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " amount = ".price2num($this->amount).","; - $sql.= " datev='".$this->db->idate($this->datev)."',"; - $sql.= " dateo='".$this->db->idate($this->dateo)."'"; - $sql.= " WHERE rowid = ".$this->rowid; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " amount = ".price2num($this->amount).","; + $sql.= " datev='".$this->db->idate($this->datev)."',"; + $sql.= " dateo='".$this->db->idate($this->dateo)."'"; + $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - $this->error=$this->db->error(); - return -1; - } - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + $this->error=$this->db->error(); + return -1; + } + } - /** - * Update conciliation field - * - * @param User $user Objet user making update - * @param int $cat Category id - * @return int <0 if KO, >0 if OK - */ - function update_conciliation(User $user, $cat) - { - global $conf; + /** + * Update conciliation field + * + * @param User $user Objet user making update + * @param int $cat Category id + * @return int <0 if KO, >0 if OK + */ + function update_conciliation(User $user, $cat) + { + global $conf; - $this->db->begin(); + $this->db->begin(); - // Check statement field - if (! empty($conf->global->BANK_STATEMENT_REGEX_RULE)) - { - if (! preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve)) - { - $this->errors[]=$langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE); - return -1; - } - } + // Check statement field + if (! empty($conf->global->BANK_STATEMENT_REGEX_RULE)) + { + if (! preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve)) + { + $this->errors[]=$langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE); + return -1; + } + } - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " rappro = 1"; - $sql.= ", num_releve = '".$this->db->escape($this->num_releve)."'"; - $sql.= ", fk_user_rappro = ".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " rappro = 1"; + $sql.= ", num_releve = '".$this->db->escape($this->num_releve)."'"; + $sql.= ", fk_user_rappro = ".$user->id; + $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (! empty($cat)) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class ("; - $sql.= "lineid"; - $sql.= ", fk_categ"; - $sql.= ") VALUES ("; - $sql.= $this->id; - $sql.= ", ".$cat; - $sql.= ")"; + dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (! empty($cat)) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class ("; + $sql.= "lineid"; + $sql.= ", fk_categ"; + $sql.= ") VALUES ("; + $sql.= $this->id; + $sql.= ", ".$cat; + $sql.= ")"; - dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); - $this->db->query($sql); + dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); + $this->db->query($sql); - // No error check. Can fail if category already affected - } + // No error check. Can fail if category already affected + } - $this->rappro=1; + $this->rappro=1; - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } - /** - * Increase/decrease value date of a rowid - * - * @param int $rowid Id of line - * @param int $sign 1 or -1 - * @return int >0 if OK, 0 if KO - */ - function datev_change($rowid,$sign=1) - { - $sql = "SELECT datev FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; - $resql = $this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $newdate=$this->db->jdate($obj->datev)+(3600*24*$sign); + /** + * Increase/decrease value date of a rowid + * + * @param int $rowid Id of line + * @param int $sign 1 or -1 + * @return int >0 if OK, 0 if KO + */ + function datev_change($rowid,$sign=1) + { + $sql = "SELECT datev FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; + $resql = $this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $newdate=$this->db->jdate($obj->datev)+(3600*24*$sign); - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " datev = '".$this->db->idate($newdate)."'"; - $sql.= " WHERE rowid = ".$rowid; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " datev = '".$this->db->idate($newdate)."'"; + $sql.= " WHERE rowid = ".$rowid; - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->affected_rows($result)) - { - return 1; - } - } - else - { - dol_print_error($this->db); - return 0; - } - } - else dol_print_error($this->db); - return 0; - } + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->affected_rows($result)) + { + return 1; + } + } + else + { + dol_print_error($this->db); + return 0; + } + } + else dol_print_error($this->db); + return 0; + } - /** - * Increase value date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function datev_next($id) - { - return $this->datev_change($id,1); - } + /** + * Increase value date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function datev_next($id) + { + return $this->datev_change($id,1); + } - /** - * Decrease value date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function datev_previous($id) - { - return $this->datev_change($id,-1); - } + /** + * Decrease value date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function datev_previous($id) + { + return $this->datev_change($id,-1); + } - /** - * Load miscellaneous information for tab "Info" - * - * @param int $id Id of object to load - * @return void - */ - function info($id) - { - $sql = 'SELECT b.rowid, b.datec, b.tms as datem,'; - $sql.= ' b.fk_user_author, b.fk_user_rappro'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'bank as b'; - $sql.= ' WHERE b.rowid = '.$id; + /** + * Increase/decrease operation date of a rowid + * + * @param int $rowid Id of line + * @param int $sign 1 or -1 + * @return int >0 if OK, 0 if KO + */ + function dateo_change($rowid,$sign=1) + { + $sql = "SELECT dateo FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; + $resql = $this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $newdate=$this->db->jdate($obj->dateo)+(3600*24*$sign); - $result=$this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " dateo = '".$this->db->idate($newdate)."'"; + $sql.= " WHERE rowid = ".$rowid; - if ($obj->fk_user_author) - { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; - } - if ($obj->fk_user_rappro) - { - $ruser = new User($this->db); - $ruser->fetch($obj->fk_user_rappro); - $this->user_rappro = $ruser; - } + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->affected_rows($result)) + { + return 1; + } + } + else + { + dol_print_error($this->db); + return 0; + } + } + else dol_print_error($this->db); + return 0; + } - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_modification = $this->db->jdate($obj->datem); - //$this->date_rappro = $obj->daterappro; // Not yet managed - } - $this->db->free($result); - } - else - { - dol_print_error($this->db); - } - } + /** + * Increase operation date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function dateo_next($id) + { + return $this->dateo_change($id,1); + } + + /** + * Decrease operation date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function dateo_previous($id) + { + return $this->dateo_change($id,-1); + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $maxlen Longueur max libelle - * @param string $option Option ('showall') - * @return string Chaine avec URL - */ - function getNomUrl($withpicto=0,$maxlen=0,$option='') - { - global $langs; + /** + * Load miscellaneous information for tab "Info" + * + * @param int $id Id of object to load + * @return void + */ + function info($id) + { + $sql = 'SELECT b.rowid, b.datec, b.tms as datem,'; + $sql.= ' b.fk_user_author, b.fk_user_rappro'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'bank as b'; + $sql.= ' WHERE b.rowid = '.$id; - $result=''; - $label=$langs->trans("ShowTransaction").': '.$this->rowid; - $link = ''; - $linkend=''; + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; - if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); - $result.=$link.$this->rowid.$linkend; + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + if ($obj->fk_user_rappro) + { + $ruser = new User($this->db); + $ruser->fetch($obj->fk_user_rappro); + $this->user_rappro = $ruser; + } - if ($option == 'showall' || $option == 'showconciliated') $result.=' ('; - if ($option == 'showall') - { - $result.=$langs->trans("BankAccount").': '; - $accountstatic=new Account($this->db); - $accountstatic->id=$this->fk_account; - $accountstatic->ref=$this->bank_account_ref; - $accountstatic->label=$this->bank_account_label; - $result.=$accountstatic->getNomUrl(0).', '; - } - if ($option == 'showall' || $option == 'showconciliated') - { - $result.=$langs->trans("BankLineConciliated").': '; - $result.=yn($this->rappro); - } - if ($option == 'showall' || $option == 'showconciliated') $result.=')'; - - return $result; - } + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + //$this->date_rappro = $obj->daterappro; // Not yet managed + } + $this->db->free($result); + } + else + { + dol_print_error($this->db); + } + } - /** - * Return label of status (activity, closed) - * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long - * @return string Libelle - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->status,$mode); - } + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $maxlen Longueur max libelle + * @param string $option Option ('showall') + * @return string Chaine avec URL + */ + function getNomUrl($withpicto=0,$maxlen=0,$option='') + { + global $langs; - /** - * Renvoi le libelle d'un statut donne - * - * @param int $statut Id statut - * @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 Libelle du statut - */ - function LibStatut($statut,$mode=0) - { - global $langs; - //$langs->load('companies'); - /* + $result=''; + $label=$langs->trans("ShowTransaction").': '.$this->rowid; + $link = ''; + $linkend=''; + + if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); + $result.=$link.$this->rowid.$linkend; + + if ($option == 'showall' || $option == 'showconciliated') $result.=' ('; + if ($option == 'showall') + { + $result.=$langs->trans("BankAccount").': '; + $accountstatic=new Account($this->db); + $accountstatic->id=$this->fk_account; + $accountstatic->ref=$this->bank_account_ref; + $accountstatic->label=$this->bank_account_label; + $result.=$accountstatic->getNomUrl(0).', '; + } + if ($option == 'showall' || $option == 'showconciliated') + { + $result.=$langs->trans("BankLineConciliated").': '; + $result.=yn($this->rappro); + } + if ($option == 'showall' || $option == 'showconciliated') $result.=')'; + + return $result; + } + + + /** + * Return label of status (activity, closed) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long + * @return string Libelle + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->status,$mode); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $statut Id statut + * @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 Libelle du statut + */ + function LibStatut($statut,$mode=0) + { + global $langs; + //$langs->load('companies'); + /* if ($mode == 0) { if ($statut==0) return $langs->trans("ActivityCeased"); @@ -2100,7 +2219,7 @@ class AccountLine extends CommonObject if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"'); if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"'); }*/ - } + } } diff --git a/htdocs/compta/bank/class/api_bankaccounts.class.php b/htdocs/compta/bank/class/api_bankaccounts.class.php index c6fd3f72def..fa540f43401 100644 --- a/htdocs/compta/bank/class/api_bankaccounts.class.php +++ b/htdocs/compta/bank/class/api_bankaccounts.class.php @@ -61,7 +61,7 @@ class BankAccounts extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') { $list = array(); diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index 1d0568c8064..45ae8d5dd95 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -30,8 +30,9 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; */ class PaymentVarious extends CommonObject { - //public $element='payment_various'; //!< Id that identify managed objects - //public $table_element='payment_various'; //!< Name of table without prefix where object is stored + public $element='variouspayment'; //!< Id that identify managed objects + public $table_element='payment_various'; //!< Name of table without prefix where object is stored + public $picto = 'bill'; var $tms; var $datep; @@ -42,6 +43,7 @@ class PaymentVarious extends CommonObject var $num_payment; var $label; var $accountancy_code; + var $fk_project; var $fk_bank; var $fk_user_author; var $fk_user_modif; @@ -96,6 +98,7 @@ class PaymentVarious extends CommonObject $sql.= " label='".$this->db->escape($this->label)."',"; $sql.= " note='".$this->db->escape($this->note)."',"; $sql.= " accountancy_code='".$this->db->escape($this->accountancy_code)."',"; + $sql.= " fk_projet='".$this->db->escape($this->fk_project)."',"; $sql.= " fk_bank=".($this->fk_bank > 0 ? $this->fk_bank:"null").","; $sql.= " fk_user_author=".$this->fk_user_author.","; $sql.= " fk_user_modif=".$this->fk_user_modif; @@ -154,6 +157,7 @@ class PaymentVarious extends CommonObject $sql.= " v.label,"; $sql.= " v.note,"; $sql.= " v.accountancy_code,"; + $sql.= " v.fk_projet as fk_project,"; $sql.= " v.fk_bank,"; $sql.= " v.fk_user_author,"; $sql.= " v.fk_user_modif,"; @@ -185,6 +189,7 @@ class PaymentVarious extends CommonObject $this->label = $obj->label; $this->note = $obj->note; $this->accountancy_code = $obj->accountancy_code; + $this->fk_project = $obj->fk_project; $this->fk_bank = $obj->fk_bank; $this->fk_user_author = $obj->fk_user_author; $this->fk_user_modif = $obj->fk_user_modif; @@ -317,6 +322,7 @@ class PaymentVarious extends CommonObject if ($this->note) $sql.= ", note"; $sql.= ", label"; $sql.= ", accountancy_code"; + $sql.= ", fk_projet"; $sql.= ", fk_user_author"; $sql.= ", datec"; $sql.= ", fk_bank"; @@ -451,6 +457,63 @@ class PaymentVarious extends CommonObject } + /** + * Retourne le libelle du statut + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Libelle + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut,$mode); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $statut 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 + * @return string Libelle + */ + function LibStatut($statut,$mode=0) + { + global $langs; + + if ($mode == 0) + { + return $langs->trans($this->statuts[$statut]); + } + if ($mode == 1) + { + return $langs->trans($this->statuts_short[$statut]); + } + if ($mode == 2) + { + if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut0').' '.$langs->trans($this->statuts_short[$statut]); + if ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]); + if ($statut==2) return img_picto($langs->trans($this->statuts_short[$statut]),'statut6').' '.$langs->trans($this->statuts_short[$statut]); + } + if ($mode == 3) + { + if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut0'); + if ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4'); + if ($statut==2 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut6'); + } + if ($mode == 4) + { + if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]); + if ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]); + if ($statut==2 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]); + } + if ($mode == 5) + { + if ($statut==0 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut0'); + if ($statut==1 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4'); + if ($statut==2 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6'); + } + } + + /** * Send name clicable (with possibly the picto) * diff --git a/htdocs/compta/bank/document.php b/htdocs/compta/bank/document.php index 40f06895792..2fca317d1c4 100644 --- a/htdocs/compta/bank/document.php +++ b/htdocs/compta/bank/document.php @@ -117,7 +117,7 @@ if ($id > 0 || !empty($ref)) { $totalsize+=$file['size']; } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); diff --git a/htdocs/compta/bank/graph.php b/htdocs/compta/bank/graph.php index 12cfeda7b15..a813a71eeca 100644 --- a/htdocs/compta/bank/graph.php +++ b/htdocs/compta/bank/graph.php @@ -108,7 +108,7 @@ else dol_print_error($db); } if (empty($min)) $min = dol_now - 3600 * 24; - + $log="graph.php: min=".$min." max=".$max; dol_syslog($log); @@ -760,7 +760,7 @@ $head=bank_prepare_head($object); dol_fiche_head($head,'graph',$langs->trans("FinancialAccount"),0,'account'); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; if ($account) { diff --git a/htdocs/compta/bank/info.php b/htdocs/compta/bank/info.php index 15555e45338..832ec95dcd2 100644 --- a/htdocs/compta/bank/info.php +++ b/htdocs/compta/bank/info.php @@ -58,7 +58,7 @@ $h++; dol_fiche_head($head, $hselected, $langs->trans("LineRecord"), -1, 'account'); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'rowid', $linkback); diff --git a/htdocs/compta/bank/ligne.php b/htdocs/compta/bank/ligne.php index 99362167a07..9266e65a872 100644 --- a/htdocs/compta/bank/ligne.php +++ b/htdocs/compta/bank/ligne.php @@ -48,8 +48,8 @@ $action=GETPOST('action','alpha'); $confirm=GETPOST('confirm','alpha'); $rowid=GETPOST("rowid",'int'); $orig_account=GETPOST("orig_account"); -$backtopage=GETPOST('backtopage'); -$cancel=GETPOST('cancel'); +$backtopage=GETPOST('backtopage','alpha'); +$cancel=GETPOST('cancel','alpha'); // Security check $fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref :'')); @@ -71,13 +71,20 @@ if ($cancel) } } -if ($user->rights->banque->consolidate && $action == 'dvnext') + +if ($user->rights->banque->consolidate && $action == 'donext') +{ + $al = new AccountLine($db); + $al->dateo_next($_GET["rowid"]); +}elseif ($user->rights->banque->consolidate && $action == 'doprev') +{ + $al = new AccountLine($db); + $al->dateo_previous($_GET["rowid"]); +}elseif ($user->rights->banque->consolidate && $action == 'dvnext') { $al = new AccountLine($db); $al->datev_next($_GET["rowid"]); -} - -if ($user->rights->banque->consolidate && $action == 'dvprev') +}elseif ($user->rights->banque->consolidate && $action == 'dvprev') { $al = new AccountLine($db); $al->datev_previous($_GET["rowid"]); @@ -145,7 +152,7 @@ if ($user->rights->banque->modifier && $action == "update") { $error++; } - + if (! $error) { $arrayofcategs=GETPOST('custcats', 'array'); @@ -168,8 +175,8 @@ if ($user->rights->banque->modifier && $action == "update") } // $arrayselected will be loaded after in page output } - } - + } + if (! $error) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); @@ -289,14 +296,14 @@ if ($result) print ''; dol_fiche_head($tabs, 0, $langs->trans('LineRecord'), 0, 'account'); - - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($bankline, 'rowid', $linkback); - - print '
    '; + + print '
    '; print '
    '; // Ref @@ -307,7 +314,7 @@ if ($result) print ''; print ''; */ - + $i++; // Bank account @@ -479,6 +486,14 @@ if ($result) { print ''; } else @@ -567,7 +582,7 @@ if ($result) if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) { $langs->load('categories'); - + // Bank line print '
    '; print $form->select_date($db->jdate($objp->do),'dateo','','','','update',1,0,1,$objp->rappro); + if (! $objp->rappro) + { + print '   '; + print ''; + print img_edit_remove() . " "; + print ''; + print img_edit_add() .""; + } print '
    ' . fieldLabel('RubriquesTransactions', 'custcats') . ''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_BANK_LINE, null, 'parent', null, null, 1); @@ -576,28 +591,28 @@ if ($result) } print "
    "; - + dol_fiche_end(); - - + + print '

    '; - + print ""; - - + + // Releve rappro if ($acct->canBeConciliated() > 0) // Si compte rapprochable { print load_fiche_titre($langs->trans("Reconciliation"), '', 'title_bank.png'); print '
    '."\n"; - + print '
    '; print ''; print ''; print ''; print ''; - + print ''; print '"; @@ -637,13 +652,13 @@ if ($result) print '
    '.$langs->trans("Conciliation")."
    '; print '
    '; - + print ''; if ($backtopage) { print '   '; print ''; - } + } print '
    '; print '
    '; diff --git a/htdocs/compta/bank/index.php b/htdocs/compta/bank/list.php similarity index 88% rename from htdocs/compta/bank/index.php rename to htdocs/compta/bank/list.php index da159bec600..23df6a44285 100644 --- a/htdocs/compta/bank/index.php +++ b/htdocs/compta/bank/list.php @@ -19,7 +19,7 @@ */ /** - * \file htdocs/compta/bank/index.php + * \file htdocs/compta/bank/list.php * \ingroup banque * \brief Home page of bank module */ @@ -46,7 +46,7 @@ $toselect = GETPOST('toselect', 'array'); $search_ref=GETPOST('search_ref','alpha'); $search_label=GETPOST('search_label','alpha'); $search_number=GETPOST('search_number','alpha'); -$statut=GETPOST('statut')?GETPOST('statut', 'alpha'):'opened'; // 'all' or ''='opened' +$search_status=GETPOST('search_status')?GETPOST('search_status', 'alpha'):'opened'; // 'all' or ''='opened' $optioncss = GETPOST('optioncss','alpha'); // Security check @@ -92,7 +92,8 @@ $arrayfields=array( 'b.account_number'=>array('label'=>$langs->trans("AccountAccounting"), 'checked'=>$conf->accountancy->enabled), 'b.fk_accountancy_journal'=>array('label'=>$langs->trans("AccountancyJournal"), 'checked'=>$conf->accountancy->enabled), 'toreconcile'=>array('label'=>$langs->trans("TransactionsToConciliate"), 'checked'=>1), - 'b.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'b.currency_code'=>array('label'=>$langs->trans("Currency"), 'checked'=>0), + 'b.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), 'b.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), 'b.clos'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), 'balance'=>array('label'=>$langs->trans("Balance"), 'checked'=>1, 'position'=>1010), @@ -102,7 +103,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -111,8 +112,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -121,13 +122,12 @@ 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','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers +if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $statut = 'all'; $search_ref=''; $search_label=''; $search_number=''; - $search_statut=''; + $search_status=''; } @@ -143,7 +143,7 @@ $title=$langs->trans('BankAccounts'); // Load array of financial accounts (opened by default) $accounts = array(); -$sql = "SELECT b.rowid, b.label, b.courant, b.rappro, b.account_number, b.fk_accountancy_journal, b.datec as date_creation, b.tms as date_update"; +$sql = "SELECT b.rowid, b.label, b.courant, b.rappro, b.account_number, b.fk_accountancy_journal, b.currency_code, b.datec as date_creation, b.tms as date_update"; // Add fields from extrafields foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : ''); // Add fields from hooks @@ -153,8 +153,8 @@ $sql.=$hookmanager->resPrint; $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as b"; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account_extrafields as ef on (b.rowid = ef.fk_object)"; $sql.= " WHERE entity IN (".getEntity('bank_account').")"; -if ($statut == 'opened') $sql.= " AND clos = 0"; -if ($statut == 'closed') $sql.= " AND clos = 1"; +if ($search_status == 'opened') $sql.= " AND clos = 0"; +if ($search_status == 'closed') $sql.= " AND clos = 1"; if ($search_ref != '') $sql.=natural_search('b.ref', $search_ref); if ($search_label != '') $sql.=natural_search('b.label', $search_label); if ($search_number != '') $sql.=natural_search('b.number', $search_number); @@ -222,7 +222,7 @@ if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($search_ref != '') $param.='&search_ref='.$search_ref; if ($search_label != '') $param.='&search_label='.$search_label; if ($search_number != '') $param.='&search_number='.$search_number; -if ($statut != '') $param.='&statut='.$statut; +if ($search_status != '') $param.='&search_status='.$search_status; if ($show_files) $param.='&show_files=' .$show_files; if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields @@ -338,6 +338,12 @@ if (! empty($arrayfields['toreconcile']['checked'])) print '
    '; print ''; + print ''; print ''; @@ -385,7 +391,7 @@ if (! empty($arrayfields['b.clos']['checked'])) 'opened'=>$langs->trans("Opened"), 'closed'=>$langs->trans("Closed") ); - print $form->selectarray("statut", $array, $statut, 1); + print $form->selectarray("search_status", $array, $search_status, 1); print '
    '.$acc->getNomUrl(1).''.$obj->getNomUrl(1).''.$acc->label.''.$obj->label.''; - print $acc->type_lib[$acc->type]; + print $obj->type_lib[$obj->type]; print ''.$acc->number.''.$obj->number.''; + print $obj->currency_code; + print ''; - if ($acc->rappro) + if ($obj->rappro) { - $result=$acc->load_board($user,$acc->id); + $result=$obj->load_board($user,$obj->id); if ($result<0) { - setEventMessages($acc->error, $acc->errors, 'errors'); + setEventMessages($obj->error, $obj->errors, 'errors'); } else { print $result->nbtodo; if ($result->nbtodolate) print '   ('.$result->nbtodolate.img_warning($langs->trans("Late")).')'; @@ -571,7 +587,7 @@ foreach ($accounts as $key=>$type) if (! empty($arrayfields['b.datec']['checked'])) { print ''; - print dol_print_date($acc->date_creation, 'dayhour'); + print dol_print_date($obj->date_creation, 'dayhour'); print ''; - print dol_print_date($acc->date_update, 'dayhour'); + print dol_print_date($obj->date_update, 'dayhour'); print ''.$acc->getLibStatut(5).''.$obj->getLibStatut(5).''; - print ''.price($solde, 0, $langs, 0, 0, -1, $acc->currency_code).''; + print ''.price($solde, 0, $langs, 0, 0, -1, $obj->currency_code).''; print '
    '; print ''; print ''; print ''; print ''; + print ''; print ''; $balancestart=array(); @@ -429,7 +445,20 @@ if (empty($numref)) } else { - print ''; + print ''; + print ''; // Calculate start amount $sql = "SELECT sum(b.amount) as amount"; @@ -459,11 +488,18 @@ if (empty($numref)) } print ''; + print ''; + print ''."\n"; } $i++; } print "
    '.$langs->trans("AccountStatement").''.$langs->trans("InitialBankBalance").''.$langs->trans("EndBankBalance").'
    '.$objp->numr.'
    '; + if ($action != 'editbankreceipt' || $objp->numr != $brref) + { + print ''.$objp->numr.''; + } + else + { + print ''; + print ''; + print ''; + print ''; + } + print ''.price(($balancestart[$objp->numr]+$content[$objp->numr]),'',$langs,1,-1,-1,$conf->currency).''; + if ($user->rights->banque->consolidate && $action != 'editbankreceipt') { + print 'numr.'">'.img_edit().''; + } + print '
    \n"; + print ''; print "\n
    \n"; } diff --git a/htdocs/compta/bank/transfer.php b/htdocs/compta/bank/transfer.php index 1f3ca1cde8e..7696427b059 100644 --- a/htdocs/compta/bank/transfer.php +++ b/htdocs/compta/bank/transfer.php @@ -30,8 +30,7 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); +$langs->loadLangs(array("banks", "categories", "multicurrency")); if (! $user->rights->banque->transfer) accessforbidden(); @@ -44,14 +43,14 @@ $error = 0; * Actions */ -if ($action == 'add_confirm') +if ($action == 'add') { $langs->load("errors"); $dateo = dol_mktime(12,0,0,GETPOST('remonth','int'),GETPOST('reday','int'),GETPOST('reyear','int')); $label = GETPOST('label','alpha'); $amount= GETPOST('amount'); - $amount_to= GETPOST('amount_to'); + $amountto= GETPOST('amountto'); if (! $label) { @@ -83,7 +82,17 @@ if ($action == 'add_confirm') $accountto=new Account($db); $accountto->fetch(GETPOST('account_to','int')); - if ($accountto->id != $accountfrom->id) + if ($accountto->currency_code == $accountfrom->currency_code) { + $amountto=$amount; + } else { + if (! $amountto) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AmountTo")), null, 'errors'); + } + } + + if (($accountto->id != $accountfrom->id) && empty($error)) { $db->begin(); @@ -103,8 +112,7 @@ if ($action == 'add_confirm') if (! $error) $bank_line_id_from = $accountfrom->addline($dateo, $typefrom, $label, -1*price2num($amount), '', '', $user); if (! ($bank_line_id_from > 0)) $error++; - if ((! $error) && ($accountto->currency_code == $accountfrom->currency_code)) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount), '', '', $user); - if ((! $error) && ($accountto->currency_code != $accountfrom->currency_code)) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount_to), '', '', $user); + if (! $error) $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amountto), '', '', $user); if (! ($bank_line_id_to > 0)) $error++; if (! $error) $result=$accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/ligne.php?rowid=', '(banktransfert)', 'banktransfert'); @@ -114,7 +122,7 @@ if ($action == 'add_confirm') if (! $error) { - $mesgs = $langs->trans("TransferFromToDone","id."\">".$accountfrom->label."","id."\">".$accountto->label."",$amount,$langs->transnoentities("Currency".$conf->currency)); + $mesgs = $langs->trans("TransferFromToDone",''.$accountfrom->label."",''.$accountto->label."",$amount,$langs->transnoentities("Currency".$conf->currency)); setEventMessages($mesgs, null, 'mesgs'); $db->commit(); } @@ -139,6 +147,58 @@ if ($action == 'add_confirm') */ llxHeader(); +print ' '; $form=new Form($db); @@ -146,9 +206,8 @@ $account_from=''; $account_to=''; $label=''; $amount=''; -$amount_to=''; -if ($error) +if($error) { $account_from = GETPOST('account_from','int'); $account_to = GETPOST('account_to','int'); @@ -164,21 +223,21 @@ print "

    "; print '
    '; print ''; -print ''; +print ''; print ''; print ''; -print ''; -print ''; +print ''; +print ''; print ''; $var=false; print '"; print "\n"; print "\n"; print ''; print ''; +print ''; + print "
    '.$langs->trans("TransferFrom").''.$langs->trans("TransferTo").''.$langs->trans("Date").''.$langs->trans("Description").''.$langs->trans("Amount").''.$langs->trans("TransferFrom").''.$langs->trans("TransferTo").''.$langs->trans("Date").''.$langs->trans("Description").''.$langs->trans("Amount").'
    '; -$form->select_comptes($account_from,'account_from',0,'',1); +$form->select_comptes($account_from, 'account_from', 0, '', 1, '', empty($conf->multicurrency->enabled)?0:1); print "\n"; -$form->select_comptes($account_to,'account_to',0,'',1); +$form->select_comptes($account_to, 'account_to', 0, '', 1, '', empty($conf->multicurrency->enabled)?0:1); print ""; @@ -186,6 +245,8 @@ $form->select_date((! empty($dateo)?$dateo:''),'','','','','add'); print "
    "; print '
    '; diff --git a/htdocs/compta/bank/treso.php b/htdocs/compta/bank/treso.php index 0e2d3b35f38..cc0d58945e0 100644 --- a/htdocs/compta/bank/treso.php +++ b/htdocs/compta/bank/treso.php @@ -93,14 +93,14 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) $head=bank_prepare_head($object); dol_fiche_head($head, 'cash', $langs->trans("FinancialAccount"), -1, 'account'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); dol_fiche_end(); - + print '
    '; - + $solde = $object->solde(0); // Show next coming entries @@ -120,13 +120,13 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) $var=true; // Current balance - + print ''; print ''.$langs->trans("CurrentBalance").''; print ''.price($solde).''; print ''; - + print ''; print ''.$langs->trans("RemainderToPay").''; print ' '; @@ -295,7 +295,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) // We discard lines with a remainder to pay to 0 if (price2num($total_ttc) != 0) { - + // Show line print ''; @@ -320,7 +320,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) } // Solde actuel - + print ''; print ''.$langs->trans("FutureBalance").' ('.$object->currency_code.')'; print ''.price($solde, 0, $langs, 0, 0, -1, $object->currency_code).''; diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php index 9328b6f599b..4c57ab5f324 100644 --- a/htdocs/compta/bank/various_payment/card.php +++ b/htdocs/compta/bank/various_payment/card.php @@ -29,6 +29,11 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +if (! empty($conf->projet->enabled)) +{ + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; +} $langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy")); @@ -44,6 +49,7 @@ $sens=GETPOST("sens","int"); $amount=GETPOST("amount"); $paymenttype=GETPOST("paymenttype"); $accountancy_code=GETPOST("accountancy_code","int"); +$projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); // Security check $socid = GETPOST("socid","int"); @@ -67,6 +73,13 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { + // Link to a project + if ($action == 'classin' && $user->rights->banque->modifier) + { + $object->fetch($id); + $object->setProject(GETPOST('projectid')); + } + if ($cancel) { if ($action != 'addlink') @@ -98,6 +111,7 @@ if (empty($reshook)) $object->fk_user_author=$user->id; $object->accountancy_code=GETPOST("accountancy_code") > 0 ? GETPOST("accountancy_code","int") : ""; $object->sens=GETPOST('sens'); + $object->fk_project= GETPOST('fk_project'); if (empty($datep) || empty($datev)) { @@ -205,6 +219,7 @@ llxHeader("",$langs->trans("VariousPayment")); $form = new Form($db); if (! empty($conf->accounting->enabled)) $formaccounting = New FormAccounting($db); +if (! empty($conf->projet->enabled)) $formproject = new FormProjets($db); if ($id) { @@ -306,6 +321,21 @@ if ($action == 'create') print ''; } + // Project + if (! empty($conf->projet->enabled)) + { + $formproject=new FormProjets($db); + + // Associated project + $langs->load("projects"); + + print ''.$langs->trans("Project").''; + + $numproject=$formproject->select_projects(-1, $projectid,'fk_project',0,0,1,1); + + print ''; + } + // Other attributes $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook @@ -333,19 +363,52 @@ if ($action == 'create') if ($id) { - $head=various_payment_prepare_head($object); - dol_fiche_head($head, 'card', $langs->trans("VariousPayment"), 0, 'payment'); - - print ''; + dol_fiche_head($head, 'card', $langs->trans("VariousPayment"), -1, 'payment'); + $morehtmlref='
    '; + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.=$langs->trans('Project') . ' '; + if ($user->rights->tax->charges->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects(0, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
    '; $linkback = ''.$langs->trans("BackToList").''; - print ""; - print ''; + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright); + + print '
    '; + print '
    '; + + print '
    '.$langs->trans("Ref").''; - print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', ''); - print '
    '; // Label print ''; @@ -376,7 +439,7 @@ if ($id) $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('',$object->accountancy_code); - print $accountingaccount->getNomUrl(1); + print $accountingaccount->getNomUrl(0,1,1,'',1); } else { print $object->accountancy_code; } @@ -404,6 +467,11 @@ if ($id) print '
    '.$langs->trans("Label").''.$object->label.'
    '; + print '
    '; + print '
    '; + + print '
    '; + dol_fiche_end(); diff --git a/htdocs/compta/bank/various_payment/index.php b/htdocs/compta/bank/various_payment/index.php index b6c50cb9c7f..ce321e00f34 100644 --- a/htdocs/compta/bank/various_payment/index.php +++ b/htdocs/compta/bank/various_payment/index.php @@ -19,7 +19,7 @@ /** * \file htdocs/compta/bank/various_payment/index.php * \ingroup bank - * \brief List of various payments + * \brief List of various payments */ require '../../../main.inc.php'; @@ -92,11 +92,11 @@ $form = new Form($db); $variousstatic = new PaymentVarious($db); $accountstatic = new Account($db); -$sql = "SELECT v.rowid, v.amount, v.label, v.datep as datep, v.datev as datev, v.fk_typepayment as type, v.num_payment, v.fk_bank, v.accountancy_code, v.sens,"; +$sql = "SELECT v.rowid, v.amount, v.label, v.datep as datep, v.datev as datev, v.fk_typepayment as type, v.num_payment, v.fk_bank, v.accountancy_code,"; $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number as bank_account_number, ba.fk_accountancy_journal as accountancy_journal, ba.label as blabel,"; $sql.= " pst.code as payment_code"; $sql.= " FROM ".MAIN_DB_PREFIX."payment_various as v"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id AND pst.entity = " . getEntity('c_paiement'); $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON v.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE v.entity = ".$conf->entity; @@ -192,7 +192,7 @@ if ($result) // Accounting account if (! empty($conf->accounting->enabled)) print ' '; - + // Debit print ''; @@ -232,7 +232,7 @@ if ($result) if (! empty($conf->banque->enabled)) { print ''; - if ($obj->fk_bank > 0) + if ($obj->bid > 0) { $accountstatic->id=$obj->bid; $accountstatic->ref=$obj->bref; @@ -245,7 +245,7 @@ if ($result) $accountingjournal->fetch($obj->accountancy_journal); $accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0,1,1,'',1); } - + $accountstatic->label=$obj->blabel; print $accountstatic->getNomUrl(1); } @@ -260,7 +260,7 @@ if ($result) print ''.$accountingaccount->getNomUrl(0,1,1,'',1).''; } - + // Debit print ""; if ($obj->sens == 0) diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php index c9a58670897..3d67f2bfad1 100644 --- a/htdocs/compta/charges/index.php +++ b/htdocs/compta/charges/index.php @@ -139,7 +139,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id AND pct.entity = " . getEntity('c_paiement'); $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pc.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE cs.fk_type = c.id"; @@ -260,7 +260,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."tva as pv"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pv.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id AND pct.entity = " . getEntity('c_paiement'); $sql.= " WHERE pv.entity = ".$conf->entity; if ($year > 0) { @@ -474,7 +474,7 @@ if (! empty($conf->salaries->enabled) && $user->rights->salaries->read) $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id AND pct.entity = " . getEntity('c_paiement'); $sql.= " , ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE s.entity IN (".getEntity('user').")"; $sql.= " AND u.rowid = s.fk_user"; diff --git a/htdocs/compta/deplacement/class/deplacement.class.php b/htdocs/compta/deplacement/class/deplacement.class.php index ea8b85c55af..c67fce127c2 100644 --- a/htdocs/compta/deplacement/class/deplacement.class.php +++ b/htdocs/compta/deplacement/class/deplacement.class.php @@ -35,7 +35,7 @@ class Deplacement extends CommonObject public $table_element='deplacement'; public $table_element_line = ''; public $fk_element = ''; - protected $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe var $datec; // Creation date var $dated; @@ -107,7 +107,7 @@ class Deplacement extends CommonObject $sql.= ", ".$conf->entity; $sql.= ", ".$user->id; $sql.= ", ".$this->fk_user; - $sql.= ", '".$this->type."'"; + $sql.= ", '".$this->db->escape($this->type)."'"; $sql.= ", ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null"); $sql.= ", ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null"); $sql.= ", ".($this->fk_project > 0? $this->fk_project : 0); diff --git a/htdocs/compta/facture/admin/facture_cust_extrafields.php b/htdocs/compta/facture/admin/facture_cust_extrafields.php index c7a43c737de..2e985c8a009 100644 --- a/htdocs/compta/facture/admin/facture_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_cust_extrafields.php @@ -39,7 +39,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php new file mode 100644 index 00000000000..0cbea0c8d89 --- /dev/null +++ b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php @@ -0,0 +1,121 @@ + +* Copyright (C) 2003 Jean-Louis Bergamo +* Copyright (C) 2004-2011 Laurent Destailleur +* Copyright (C) 2012 Regis Houssin +* Copyright (C) 2013 Jean-Francois FERRY +* Copyright (C) 2017 John BOTELLA +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +/** +* \file htdocs/compta/facture/admin/facture_cust_extrafields.php +* \ingroup invoice +* \brief Page to setup extra fields of customer invoice +*/ + +require '../../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + +$langs->load("companies"); +$langs->load("admin"); +$langs->load("bills"); + +$extrafields = new ExtraFields($db); +$form = new Form($db); + +// List of supported format +$tmptype2label=ExtraFields::$type2label; +$type2label=array(''); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); + +$action=GETPOST('action', 'alpha'); +$attrname=GETPOST('attrname', 'alpha'); +$elementtype='facture_rec'; //Must be the $table_element of the class that manage extrafield + +if (!$user->admin) accessforbidden(); + + +/* +* Actions +*/ + +require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; + + + +/* +* View +*/ + +$textobject=strtolower($langs->transnoentitiesnoconv("BillsCustomers")); + +llxHeader('',$langs->trans("BillsSetup")); + +$linkback=''.$langs->trans("BackToModuleList").''; + +print load_fiche_titre($langs->trans("BillsSetup"),$linkback,'title_setup'); + +$head = invoice_admin_prepare_head(); + +dol_fiche_head($head, 'attributesrec', $langs->trans("Invoices"), -1, 'invoice'); + +require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; + +dol_fiche_end(); + + +// Buttons +if ($action != 'create' && $action != 'edit') +{ + print '
    '; + print "".$langs->trans("NewAttribute").""; + print "
    "; +} + + +/* ************************************************************************** */ +/* */ +/* Creation of an optional field */ +/* */ +/* ************************************************************************** */ + +if ($action == 'create') +{ + print "
    "; + print load_fiche_titre($langs->trans('NewAttribute')); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; +} + +/* ************************************************************************** */ +/* */ +/* Edition of an optional field */ +/* */ +/* ************************************************************************** */ +if ($action == 'edit' && ! empty($attrname)) +{ + $langs->load("members"); + + print "
    "; + print load_fiche_titre($langs->trans("FieldEdition", $attrname)); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; +} + +llxFooter(); + +$db->close(); diff --git a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php index 3a5f8c3387f..b17e3c416d2 100644 --- a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php @@ -40,7 +40,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php new file mode 100644 index 00000000000..0951dff721b --- /dev/null +++ b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php @@ -0,0 +1,119 @@ + +* Copyright (C) 2003 Jean-Louis Bergamo +* Copyright (C) 2004-2011 Laurent Destailleur +* Copyright (C) 2012 Regis Houssin +* Copyright (C) 2013 Jean-Francois FERRY +* Copyright (C) 2013 Florian Henry +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +/** +* \file htdocs/compta/facture/admin/facture_cust_extrafields.php +* \ingroup invoice +* \brief Page to setup extra fields of customer invoice +*/ + +require '../../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + +$langs->load("companies"); +$langs->load("admin"); +$langs->load("bills"); + +$extrafields = new ExtraFields($db); +$form = new Form($db); + +// List of supported format +$tmptype2label=ExtraFields::$type2label; +$type2label=array(''); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); + +$action=GETPOST('action', 'alpha'); +$attrname=GETPOST('attrname', 'alpha'); +$elementtype='facturedet_rec'; //Must be the $table_element of the class that manage extrafield + +if (!$user->admin) accessforbidden(); + + +/* +* Actions +*/ + +require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; + + + +/* +* View +*/ + +$textobject=strtolower($langs->transnoentitiesnoconv("BillsCustomers")); + +llxHeader('',$langs->trans("BillsSetup")); + +$linkback=''.$langs->trans("BackToModuleList").''; + +print load_fiche_titre($langs->trans("BillsSetup"),$linkback,'title_setup'); + +$head = invoice_admin_prepare_head(); + +dol_fiche_head($head, 'attributeslinesrec', $langs->trans("Invoices"), -1, 'invoice'); + +require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; + +dol_fiche_end(); + + +// Buttons +if ($action != 'create' && $action != 'edit') +{ + print '
    '; + print "".$langs->trans("NewAttribute").""; + print "
    "; +} + + +/* ************************************************************************** */ +/* */ +/* Creation d'un champ optionnel +/* */ +/* ************************************************************************** */ + +if ($action == 'create') +{ + print "
    "; + print load_fiche_titre($langs->trans('NewAttribute')); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; +} + +/* ************************************************************************** */ +/* */ +/* Edition d'un champ optionnel */ +/* */ +/* ************************************************************************** */ +if ($action == 'edit' && ! empty($attrname)) +{ + print "
    "; + print load_fiche_titre($langs->trans("FieldEdition", $attrname)); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; +} + +llxFooter(); + +$db->close(); diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index a613581f5aa..8365a52f277 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -38,6 +38,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php'; +require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php'; @@ -73,7 +74,7 @@ if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); if (! empty($conf->margin->enabled)) $langs->load('margins'); -$projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); +$projectid = (GETPOST('projectid','int') ? GETPOST('projectid', 'int') : 0); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility $ref = GETPOST('ref', 'alpha'); @@ -83,7 +84,7 @@ $confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $lineid = GETPOST('lineid', 'int'); $userid = GETPOST('userid', 'int'); -$search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha'); +$search_ref = GETPOST('sf_ref','alpha') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha'); $search_societe = GETPOST('search_societe', 'alpha'); $search_montant_ht = GETPOST('search_montant_ht', 'alpha'); $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha'); @@ -132,7 +133,15 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if ($cancel) $action=''; + if ($cancel) + { + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + $action=''; + } include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once @@ -298,11 +307,11 @@ if (empty($reshook)) $date = dol_mktime(12, 0, 0, $_POST['invoicedatemonth'], $_POST['invoicedateday'], $_POST['invoicedateyear']); if (empty($date)) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate'); - exit; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); + header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate'); + exit; } - $object->date=$date; + $object->date=$date; $new_date_lim_reglement = $object->calculate_date_lim_reglement(); if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement; if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date; @@ -314,7 +323,7 @@ if (empty($reshook)) { $object->fetch($id); $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); - $object->date_pointoftax=$date_pointoftax; + $object->date_pointoftax=$date_pointoftax; $result = $object->update($user); if ($result < 0) dol_print_error($db, $object->error); } @@ -360,14 +369,14 @@ if (empty($reshook)) // Set incoterm elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { - $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - } + { + $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); + } // bank account else if ($action == 'setbankaccount' && $user->rights->facture->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); } else if ($action == 'setremisepercent' && $user->rights->facture->creer) @@ -416,6 +425,22 @@ if (empty($reshook)) } } } + + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $ret = $object->fetch($id); // Reload to get new records + + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'setref_client' && $user->rights->facture->creer) @@ -426,31 +451,56 @@ if (empty($reshook)) // Classify to validated else if ($action == 'confirm_valid' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) ) { - $idwarehouse = GETPOST('idwarehouse'); + $idwarehouse = GETPOST('idwarehouse','int'); $object->fetch($id); $object->fetch_thirdparty(); // Check parameters - // Check for mandatory prof id (but only if country is than than ours) - if ($mysoc->country_id > 0 && $object->thirdparty->country_id == $mysoc->country_id) + // Check for mandatory fields defined into setup + $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL'); + foreach($array_to_check as $key) { - for ($i = 1; $i <= 6; $i++) - { - $idprof_mandatory = 'SOCIETE_IDPROF' . ($i) . '_INVOICE_MANDATORY'; - $idprof = 'idprof' . $i; - if (! $object->thirdparty->$idprof && ! empty($conf->global->$idprof_mandatory)) - { - if (! $error) $langs->load("errors"); - $error++; - setEventMessages($langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId' . $i, $object->thirdparty->country_code)), null, 'errors'); - } - } + $keymin=strtolower($key); + $i=(int) preg_replace('/[^0-9]/','',$key); + $vallabel=$object->thirdparty->$keymin; + + if ($i > 0) + { + if ($object->thirdparty->isACompany()) + { + // Check for mandatory prof id (but only if country is other than ours) + if ($mysoc->country_id > 0 && $object->thirdparty->country_id == $mysoc->country_id) + { + $idprof_mandatory ='SOCIETE_'.$key.'_INVOICE_MANDATORY'; + if (! $vallabel && ! empty($conf->global->$idprof_mandatory)) + { + $langs->load("errors"); + $error++; + setEventMessages($langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $object->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')', null, 'errors'); + } + } + } + } + else + { + //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY); + if ($key == 'EMAIL') + { + // Check for mandatory + if (! empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && ! isValidEMail($object->thirdparty->email)) + { + $langs->load("errors"); + $error++; + setEventMessages($langs->trans("ErrorBadEMail", $object->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").')', null, 'errors'); + } + } + } } $qualified_for_stock_change = 0; @@ -490,7 +540,7 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } } else @@ -504,7 +554,7 @@ if (empty($reshook)) // Go back to draft status (unvalidate) else if ($action == 'confirm_modif' && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) ) { $idwarehouse = GETPOST('idwarehouse'); @@ -555,27 +605,30 @@ if (empty($reshook)) $ventilExportCompta = $object->getVentilExportCompta(); // On verifie si aucun paiement n'a ete effectue - if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0) + if ($ventilExportCompta == 0) { - $result=$object->set_draft($user, $idwarehouse); - if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); - - - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_EDITED) || ($resteapayer == $object->total_ttc && empty($object->paye))) { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + $result=$object->set_draft($user, $idwarehouse); + if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + $ret = $object->fetch($id); // Reload to get new records + + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } } } } @@ -664,9 +717,13 @@ if (empty($reshook)) if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) { // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT - $sql = 'SELECT SUM(pf.amount) as total_paiements - FROM llx_c_paiement as c, llx_paiement_facture as pf, llx_paiement as p - WHERE pf.fk_facture = '.$object->id.' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; + + $sql = 'SELECT SUM(pf.amount) as total_paiements'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'; + $sql.= ' WHERE pf.fk_facture = '.$object->id; + $sql.= ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; + $sql.= ' AND c.entity IN (' . getEntity('c_paiement').')'; + $sql.= ' ORDER BY p.datep, p.tms'; $resql = $db->query($sql); if (! $resql) dol_print_error($db); @@ -774,7 +831,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = $_POST['cond_reglement_id']; $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); @@ -826,7 +883,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = 0; $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); @@ -842,62 +899,62 @@ if (empty($reshook)) if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0) { - $facture_source = new Facture($db); // fetch origin object - if ($facture_source->fetch($object->fk_facture_source)>0) - { - $fk_parent_line = 0; + $facture_source = new Facture($db); // fetch origin object + if ($facture_source->fetch($object->fk_facture_source)>0) + { + $fk_parent_line = 0; - foreach($facture_source->lines as $line) - { - // Reset fk_parent_line for no child products and special product - if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { - $fk_parent_line = 0; - } + foreach($facture_source->lines as $line) + { + // Reset fk_parent_line for no child products and special product + if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { + $fk_parent_line = 0; + } - $line->fk_facture = $object->id; - $line->fk_parent_line = $fk_parent_line; + $line->fk_facture = $object->id; + $line->fk_parent_line = $fk_parent_line; - $line->subprice = -$line->subprice; // invert price for object - $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here - $line->total_ht = -$line->total_ht; - $line->total_tva = -$line->total_tva; - $line->total_ttc = -$line->total_ttc; - $line->total_localtax1 = -$line->total_localtax1; - $line->total_localtax2 = -$line->total_localtax2; + $line->subprice = -$line->subprice; // invert price for object + $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here + $line->total_ht = -$line->total_ht; + $line->total_tva = -$line->total_tva; + $line->total_ttc = -$line->total_ttc; + $line->total_localtax1 = -$line->total_localtax1; + $line->total_localtax2 = -$line->total_localtax2; - $line->multicurrency_subprice = -$line->multicurrency_subprice; - $line->multicurrency_total_ht = -$line->multicurrency_total_ht; - $line->multicurrency_total_tva = -$line->multicurrency_total_tva; - $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc; + $line->multicurrency_subprice = -$line->multicurrency_subprice; + $line->multicurrency_total_ht = -$line->multicurrency_total_ht; + $line->multicurrency_total_tva = -$line->multicurrency_total_tva; + $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc; - $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked + $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked - $object->lines[] = $line; // insert new line in current object + $object->lines[] = $line; // insert new line in current object - // Defined the new fk_parent_line - if ($result > 0 && $line->product_type == 9) { - $fk_parent_line = $result; - } - } + // Defined the new fk_parent_line + if ($result > 0 && $line->product_type == 9) { + $fk_parent_line = $result; + } + } - $object->update_price(1); - } + $object->update_price(1); + } } - if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0) - { - $facture_source = new Facture($db); // fetch origin object if not previously defined - if ($facture_source->fetch($object->fk_facture_source)>0) - { - $totalpaye = $facture_source->getSommePaiement(); - $totalcreditnotes = $facture_source->getSumCreditNotesUsed(); - $totaldeposits = $facture_source->getSumDepositsUsed(); - $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits); + if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0) + { + $facture_source = new Facture($db); // fetch origin object if not previously defined + if ($facture_source->fetch($object->fk_facture_source)>0) + { + $totalpaye = $facture_source->getSommePaiement(); + $totalcreditnotes = $facture_source->getSumCreditNotesUsed(); + $totaldeposits = $facture_source->getSumDepositsUsed(); + $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits); - $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC'); - } - } + $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC'); + } + } } } @@ -928,7 +985,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']); $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->amount = $_POST['amount']; $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; @@ -978,7 +1035,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']); $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->amount = $_POST['amount']; $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; @@ -1060,7 +1117,7 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines or deposit lines"); $result = $srcobject->fetch($object->origin_id); - // If deposit invoice + // If deposit invoice if ($_POST['type'] == Facture::TYPE_DEPOSIT) { $typeamount = GETPOST('typedeposit', 'alpha'); @@ -1110,8 +1167,8 @@ if (empty($reshook)) if ($totalamount != 0) { if ($numlines > 0) $numlines = $numlines-1; - $tva_tx = $lines[$numlines]->tva_tx; - if (! empty($lines[$numlines]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$numlines]->vat_src_code.')'; + $tva_tx = $lines[$numlines]->tva_tx; + if (! empty($lines[$numlines]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$numlines]->vat_src_code.')'; $amountdeposit[$tva_tx] = ($totalamount * $valuedeposit) / 100; } else { $amountdeposit[0] = 0; @@ -1127,8 +1184,17 @@ if (empty($reshook)) foreach ($amountdeposit as $tva => $amount) { + $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); + $descline = $langs->trans('Deposit'); + $descline.= ' - '.$langs->trans($arraylist[$typeamount]); + if ($typeamount=='amount') { + $descline.= ' ('. price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')'; + } elseif ($typeamount=='variable') { + $descline.= ' ('. $valuedeposit.'%)'; + } + $descline.= ' - '.$srcobject->ref; $result = $object->addline( - $langs->trans('Deposit'), + $descline, $amount, // subprice 1, // quantity $tva, // vat rate @@ -1139,7 +1205,7 @@ if (empty($reshook)) 0, // date_start 0, // date_end 0, - $lines[$i]->info_bits, // info_bits + $lines[$i]->info_bits, // info_bits 0, 'HT', 0, @@ -1150,8 +1216,8 @@ if (empty($reshook)) 0, 0, 0, - 0, - $langs->trans('Deposit') + 0 + //,$langs->trans('Deposit') //Deprecated ); } @@ -1301,8 +1367,8 @@ if (empty($reshook)) // modified by hook if ($reshook < 0) { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $error++; + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + $error++; } } else { @@ -1474,16 +1540,16 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error ++; } - if (!$prod_entry_mode) - { - if (GETPOST('type') < 0 && ! GETPOST('search_idprod')) - { - setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors'); - $error ++; - } - } + if (!$prod_entry_mode) + { + if (GETPOST('type') < 0 && ! GETPOST('search_idprod')) + { + setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors'); + $error ++; + } + } if ($prod_entry_mode == 'free' && empty($idprod) && GETPOST('type') < 0) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error ++; } if ($prod_entry_mode == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '') && $price_ht_devise == '') // Unit price can be 0 but not '' @@ -1568,8 +1634,8 @@ if (empty($reshook)) $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility { - if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; - if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; + if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; + if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; if (empty($tva_tx)) $tva_npr=0; } } @@ -1724,18 +1790,18 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); unset($_POST['situations']); unset($_POST['progress']); @@ -1748,7 +1814,7 @@ if (empty($reshook)) } } - elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel')) + elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel','alpha')) { if (! $object->fetch($id) > 0) dol_print_error($db); $object->fetch_thirdparty(); @@ -1758,7 +1824,7 @@ if (empty($reshook)) $date_end = ''; $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - $description = dol_htmlcleanlastbr(GETPOST('product_desc') ? GETPOST('product_desc') : GETPOST('desc')); + $description = dol_htmlcleanlastbr(GETPOST('product_desc','none') ? GETPOST('product_desc','none') : GETPOST('desc','none')); $pu_ht = GETPOST('price_ht'); $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); $qty = GETPOST('qty'); @@ -1900,18 +1966,18 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); unset($_POST['situations']); unset($_POST['progress']); @@ -1943,24 +2009,21 @@ if (empty($reshook)) exit(); } - - /* - * Send mail - */ + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails if (empty($id)) $id=$facid; $trigger_name='BILL_SENTBYMAIL'; $paramname='id'; - $mode='emailfrominvoice'; + $autocopy='MAIN_MAIL_AUTOCOPY_INVOICE_TO'; $trackid='inv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - - // Actions to build doc - $upload_dir = $conf->facture->dir_output; - $permissioncreate=$user->rights->facture->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + // Actions to build doc + $upload_dir = $conf->facture->dir_output; + $permissioncreate=$user->rights->facture->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; if ($action == 'update_extras') { @@ -1978,8 +2041,10 @@ if (empty($reshook)) // some hooks if (empty($reshook)) { $result = $object->insertExtraFields(); - if ($result < 0) { - $error ++; + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; } } else if ($reshook < 0) $error ++; @@ -1989,8 +2054,6 @@ if (empty($reshook)) $action = 'edit_extras'; } - include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->facture->creer) { if ($action == 'addcontact') { $result = $object->fetch($id); @@ -2134,7 +2197,7 @@ if ($action == 'create') $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); @@ -2177,14 +2240,14 @@ if ($action == 'create') if ($origin == 'contrat') { - $langs->load("admin"); - $text=$langs->trans("ToCreateARecurringInvoice"); - $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates")); - if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) - { - $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')); - } - print info_admin($text, 0, 0, 0).'
    '; + $langs->load("admin"); + $text=$langs->trans("ToCreateARecurringInvoice"); + $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates")); + if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) + { + $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')); + } + print info_admin($text, 0, 0, 0).'
    '; } print '
    '; @@ -2207,7 +2270,7 @@ if ($action == 'create') // Thirdparty print '' . $langs->trans('Customer') . ''; - if ($soc->id > 0 && ! GETPOST('fac_rec')) + if ($soc->id > 0 && ! GETPOST('fac_rec','alpha')) { print ''; print $soc->getNomUrl(1); @@ -2242,6 +2305,7 @@ if ($action == 'create') }); '; } + print ' '.$langs->trans("AddThirdParty").''; print ''; } print '' . "\n"; @@ -2251,16 +2315,16 @@ if ($action == 'create') // Overwrite value if creation of invoice is from a predefined invoice if (empty($origin) && empty($originid) && GETPOST('fac_rec','int') > 0) { - $invoice_predefined = new FactureRec($db); - $invoice_predefined->fetch(GETPOST('fac_rec','int')); + $invoice_predefined = new FactureRec($db); + $invoice_predefined->fetch(GETPOST('fac_rec','int')); - $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later - if (empty($projectid)) $projectid = $invoice_predefined->fk_project; - $cond_reglement_id = $invoice_predefined->cond_reglement_id; - $mode_reglement_id = $invoice_predefined->mode_reglement_id; - $fk_account = $invoice_predefined->fk_account; - $note_public = $invoice_predefined->note_public; - $note_private = $invoice_predefined->note_private; + $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later + if (empty($projectid)) $projectid = $invoice_predefined->fk_project; + $cond_reglement_id = $invoice_predefined->cond_reglement_id; + $mode_reglement_id = $invoice_predefined->mode_reglement_id; + $fk_account = $invoice_predefined->fk_account; + $note_public = $invoice_predefined->note_public; + $note_private = $invoice_predefined->note_private; $sql = 'SELECT r.rowid, r.titre, r.total_ttc'; $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as r'; @@ -2283,17 +2347,17 @@ if ($action == 'create') print ''; $i ++; } print ''; // Option to reload page to retrieve customer informations. Note, this clear other input - if (!empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE)) - { - print ''; - } + } print ''; } $db->free($resql); @@ -2371,9 +2435,9 @@ if ($action == 'create') // Deposit if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) { - print '
    '; - $tmp=' '; - print ''; - $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3); - print ''; - if (($origin == 'propal') || ($origin == 'commande')) - { - print ''; - print '
    '; - print $desc; - print ''; - $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); - print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1); - print '' . $langs->trans('Value') . ':'; - } - print '
    '; + $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3); + print ''; + if (($origin == 'propal') || ($origin == 'commande')) + { + print ''; + print '
    '; + print $desc; + print ''; + $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); + print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1); + print '' . $langs->trans('Value') . ':'; + } + print '
    '; - print '
    '; + print '
    '; } } @@ -2428,33 +2492,33 @@ if ($action == 'create') // Replacement if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) { - print ''; - print '
    '; - $tmp=' + print ''; + print '
    '; + $tmp=' jQuery(document).ready(function() { jQuery("#fac_replacement").change(function() { jQuery("#radio_replacement").prop("checked", true); }); }); '; - $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' '; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3); - print $desc; - print '
    '; + $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' '; + $text .= ''; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3); + print $desc; + print '
    '; } } else @@ -2472,15 +2536,15 @@ if ($action == 'create') { if ($socid > 0) { - // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { - print '
    '; - $tmp=' + // Credit note + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) + { + print '
    '; + $tmp=' jQuery(document).ready(function() { if (! jQuery("#radio_creditnote").is(":checked")) { @@ -2494,29 +2558,29 @@ if ($action == 'create') }); }); '; - $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; - // $text.=''; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); - print $desc; + $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; + // $text.=''; + $text .= ''; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); + print $desc; - print '
    '; - print '    0 ? 'checked':'').' /> "; - print '
        0 ? 'checked':'').' /> "; - print '
    '; + print '
    '; + print '    0 ? 'checked':'').' /> "; + print '
        0 ? 'checked':'').' /> "; + print '
    '; - print '
    '; - } + print '
    '; + } } else { @@ -2590,14 +2654,14 @@ if ($action == 'create') $form->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id', 'CRDT'); print ''; - // Bank Account + // Bank Account if (isset($_POST['fk_account'])) { $fk_account = $_POST['fk_account']; } - print '' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print ''; + print '' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; // Project if (! empty($conf->projet->enabled) && $socid > 0) @@ -2614,22 +2678,22 @@ if ($action == 'create') { print ''; print ''; - print ''; - $incoterm_id = GETPOST('incoterm_id'); - $incoterm_location = GETPOST('location_incoterms'); - if (empty($incoterm_id)) - { - $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); - $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); - } - print $form->select_incoterms($incoterm_id, $incoterm_location); + print ''; + $incoterm_id = GETPOST('incoterm_id'); + $incoterm_location = GETPOST('location_incoterms'); + if (empty($incoterm_id)) + { + $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); + $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); + } + print $form->select_incoterms($incoterm_id, $incoterm_location); print ''; } // Other attributes $parameters = array('objectsrc' => $objectsrc,'colspan' => ' colspan="2"', 'cols'=>2); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields, 'edit'); } @@ -2647,8 +2711,8 @@ if ($action == 'create') { print ''; print ''.fieldLabel('Currency','multicurrency_code').''; - print ''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print ''; } @@ -2656,28 +2720,28 @@ if ($action == 'create') $htmltext=''; if (GETPOST('fac_rec','int') > 0) { - $dateexample=($datefacture ? $datefacture : $dateinvoice); - if (empty($dateexample)) $dateexample=dol_now(); - $substitutionarray=array( - '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')', - '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')', - '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')', - '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')', - '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')', - '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')', - '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')', - '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')', - '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')', - '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')', - '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')' - ); + $dateexample=($datefacture ? $datefacture : $dateinvoice); + if (empty($dateexample)) $dateexample=dol_now(); + $substitutionarray=array( + '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')', + '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')', + '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')', + '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')', + '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')', + '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')', + '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')', + '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')', + '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')', + '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')', + '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')' + ); - $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
    '; - foreach($substitutionarray as $key => $val) - { - $htmltext.=$key.' = '.$langs->trans($val).'
    '; - } - $htmltext.='
    '; + $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
    '; + foreach($substitutionarray as $key => $val) + { + $htmltext.=$key.' = '.$langs->trans($val).'
    '; + } + $htmltext.='
    '; } // Public note @@ -2748,8 +2812,8 @@ if ($action == 'create') $cntinvoice=count($objectsrc->linkedObjects['facture']); if ($cntinvoice>=1) { - setEventMessages('WarningBillExist', null, 'warnings'); - echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')'; + setEventMessages('WarningBillExist', null, 'warnings'); + echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')'; } echo ''; print '' . $langs->trans('TotalHT') . '' . price($objectsrc->total_ht) . ''; @@ -3117,34 +3181,34 @@ else if ($id > 0 || ! empty($ref)) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->facture->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } } $morehtmlref.='
    '; @@ -3197,7 +3261,7 @@ else if ($id > 0 || ! empty($ref)) $discount = new DiscountAbsolute($db); $result = $discount->fetch(0, $object->id); if ($result > 0){ - print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).'
    '; + print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).'
    '; } } print ''; @@ -3439,16 +3503,16 @@ else if ($id > 0 || ! empty($ref)) print $langs->trans('BankAccount'); print ''; if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon)) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).''; + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).''; print ''; print ''; if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); } print ""; print ''; @@ -3506,14 +3570,14 @@ else if ($id > 0 || ! empty($ref)) if (!empty($conf->incoterm->enabled)) { print ''; - print '
    '; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->facture->creer) print ''.img_edit().''; - else print ' '; - print '
    '; - print ''; - print ''; + print '
    '; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->facture->creer) print ''.img_edit().''; + else print ' '; + print '
    '; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -3522,7 +3586,7 @@ else if ($id > 0 || ! empty($ref)) { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } // Other attributes @@ -3540,20 +3604,20 @@ else if ($id > 0 || ! empty($ref)) if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { - // Multicurrency Amount HT - print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; - print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount HT + print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; + print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount VAT - print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; - print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount VAT + print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; + print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount TTC - print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; - print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount TTC + print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; + print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; } // Amount @@ -3567,40 +3631,40 @@ else if ($id > 0 || ! empty($ref)) // Amount Local Taxes if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1 { - print '' . $langs->transcountry("AmountLT1", $mysoc->country_code) . ''; - print '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . ''; + print '' . $langs->transcountry("AmountLT1", $mysoc->country_code) . ''; + print '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . ''; } if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2 { - print '' . $langs->transcountry("AmountLT2", $mysoc->country_code) . ''; - print '' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . ''; + print '' . $langs->transcountry("AmountLT2", $mysoc->country_code) . ''; + print '' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . ''; } // Revenue stamp if ($selleruserevenustamp) // Test company use revenue stamp { - print ''; - print ''; - if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer) - { - print ''; - } - print '
    '; - print $langs->trans('RevenueStamp'); - print 'id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '
    '; - print ''; - if ($action == 'editrevenuestamp') { - print '
    '; - print ''; - print ''; - print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code); - // print ''; - print ' '; - print '
    '; - } else { - print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency); - } - print ''; + print ''; + print ''; + if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer) + { + print ''; + } + print '
    '; + print $langs->trans('RevenueStamp'); + print 'id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '
    '; + print ''; + if ($action == 'editrevenuestamp') { + print '
    '; + print ''; + print ''; + print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code); + // print ''; + print ' '; + print '
    '; + } else { + print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency); + } + print ''; } // Total with tax @@ -3613,161 +3677,165 @@ else if ($id > 0 || ! empty($ref)) $sign = 1; if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = - 1; - $nbrows = 8; - $nbcols = 3; - if (! empty($conf->projet->enabled)) - $nbrows ++; - if (! empty($conf->banque->enabled)) { - $nbrows ++; - $nbcols ++; - } - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) - $nbrows ++; - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) - $nbrows ++; - if ($selleruserevenustamp) - $nbrows ++; - if (! empty($conf->multicurrency->enabled)) - $nbrows += 5; - if (! empty($conf->incoterm->enabled)) - $nbrows += 1; + $nbrows = 8; + $nbcols = 3; + if (! empty($conf->projet->enabled)) + $nbrows ++; + if (! empty($conf->banque->enabled)) { + $nbrows ++; + $nbcols ++; + } + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) + $nbrows ++; + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) + $nbrows ++; + if ($selleruserevenustamp) + $nbrows ++; + if (! empty($conf->multicurrency->enabled)) + $nbrows += 5; + if (! empty($conf->incoterm->enabled)) + $nbrows += 1; - if ($object->type == Facture::TYPE_SITUATION && ! empty($conf->global->INVOICE_USE_SITUATION)) - { - if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) - print ''; + if ($object->type == Facture::TYPE_SITUATION && ! empty($conf->global->INVOICE_USE_SITUATION)) + { + if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) + print '
    '; - if (count($object->tab_previous_situation_invoice) > 0) { - // List of previous invoices - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + if (count($object->tab_previous_situation_invoice) > 0) { + // List of previous invoices + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - $total_prev_ht = $total_prev_ttc = 0; - foreach ($object->tab_previous_situation_invoice as $prev_invoice) { - $totalpaye = $prev_invoice->getSommePaiement(); - $total_prev_ht += $prev_invoice->total_ht; - $total_prev_ttc += $prev_invoice->total_ttc; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + $total_prev_ht = $total_prev_ttc = 0; + foreach ($object->tab_previous_situation_invoice as $prev_invoice) { + $totalpaye = $prev_invoice->getSommePaiement(); + $total_prev_ht += $prev_invoice->total_ht; + $total_prev_ttc += $prev_invoice->total_ttc; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - } + } - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; + } - if (count($object->tab_next_situation_invoice) > 0) { - // List of next invoices - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + if (count($object->tab_next_situation_invoice) > 0) { + // List of next invoices + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - $total_next_ht = $total_next_ttc = 0; + $total_next_ht = $total_next_ttc = 0; - foreach ($object->tab_next_situation_invoice as $next_invoice) { - $totalpaye = $next_invoice->getSommePaiement(); - $total_next_ht += $next_invoice->total_ht; - $total_next_ttc += $next_invoice->total_ttc; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + foreach ($object->tab_next_situation_invoice as $next_invoice) { + $totalpaye = $next_invoice->getSommePaiement(); + $total_next_ht += $next_invoice->total_ht; + $total_next_ttc += $next_invoice->total_ttc; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - } + } - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + print ''; + } - if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) - print '
    ' . $langs->trans('ListOfPreviousSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
    ' . $langs->trans('ListOfPreviousSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
    ' . $prev_invoice->getNomUrl(1) . '' . price($prev_invoice->total_ht) . '' . price($prev_invoice->total_ttc) . '' . $prev_invoice->getLibStatut(3, $totalpaye) . '
    ' . $prev_invoice->getNomUrl(1) . '' . price($prev_invoice->total_ht) . '' . price($prev_invoice->total_ttc) . '' . $prev_invoice->getLibStatut(3, $totalpaye) . '
    ' . price($total_prev_ht) . '' . price($total_prev_ttc) . ' 
    ' . price($total_prev_ht) . '' . price($total_prev_ttc) . ' 
    ' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
    ' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
    ' . $next_invoice->getNomUrl(1) . '' . price($next_invoice->total_ht) . '' . price($next_invoice->total_ttc) . '' . $next_invoice->getLibStatut(3, $totalpaye) . '
    ' . $next_invoice->getNomUrl(1) . '' . price($next_invoice->total_ht) . '' . price($next_invoice->total_ttc) . '' . $next_invoice->getLibStatut(3, $totalpaye) . '
    ' . price($total_next_ht) . '' . price($total_next_ttc) . ' 
    ' . price($total_next_ht) . '' . price($total_next_ttc) . ' 
    '; - } + if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) + print ''; + } - // List of payments already done + // List of payments already done - print ''; + print '
    '; - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) { - print ''; - } - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) { + print ''; + } + print ''; + print ''; + print ''; - // Payments already done (from payment on this invoice) - $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,'; - $sql .= ' c.code as payment_code, c.libelle as payment_label,'; - $sql .= ' pf.amount,'; - $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; - $sql .= ' FROM ' . MAIN_DB_PREFIX . 'c_paiement as c, ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p'; - $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; - $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; - $sql .= ' WHERE pf.fk_facture = ' . $object->id . ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; - $sql .= ' ORDER BY p.datep, p.tms'; + // Payments already done (from payment on this invoice) + $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,'; + $sql .= ' c.code as payment_code, c.libelle as payment_label,'; + $sql .= ' pf.amount,'; + $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; + $sql .= ' FROM ' . MAIN_DB_PREFIX . 'c_paiement as c, ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p'; + $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; + $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; + $sql .= ' WHERE pf.fk_facture = ' . $object->id . ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; + $sql .= ' AND c.entity IN (' . getEntity('c_paiement').')'; + $sql .= ' ORDER BY p.datep, p.tms'; - $result = $db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $i = 0; + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; - // if ($object->type != 2) - // { - if ($num > 0) { - while ($i < $num) { - $objp = $db->fetch_object($result); - print ''; - print ''; - $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label; - print ''; - if (! empty($conf->banque->enabled)) { - $bankaccountstatic->id = $objp->baid; - $bankaccountstatic->ref = $objp->baref; - $bankaccountstatic->label = $objp->baref; + // if ($object->type != 2) + // { + if ($num > 0) { + while ($i < $num) { + $objp = $db->fetch_object($result); + + $paymentstatic->id = $objp->rowid; + $paymentstatic->datepaye = $db->jdate($objp->dp); + $paymentstatic->ref = $objp->ref; + $paymentstatic->num_paiement = $objp->num_paiement; + $paymentstatic->payment_code = $objp->payment_code; + + print ''; + print ''; + $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label; + print ''; + if (! empty($conf->banque->enabled)) + { + $bankaccountstatic->id = $objp->baid; + $bankaccountstatic->ref = $objp->baref; + $bankaccountstatic->label = $objp->baref; $bankaccountstatic->number = $objp->banumber; if (! empty($conf->accounting->enabled)) { @@ -3779,155 +3847,155 @@ else if ($id > 0 || ! empty($ref)) } print ''; - } - print ''; - print ''; - print ''; - $i ++; - } - } - /*else { + if ($bankaccountstatic->id) + print $bankaccountstatic->getNomUrl(1, 'transactions'); + print ''; + } + print ''; + print ''; + print ''; + $i ++; + } + } + /*else { print ''; }*/ - // } - $db->free($result); - } else { - dol_print_error($db); - } + // } + $db->free($result); + } else { + dol_print_error($db); + } - if ($object->type != Facture::TYPE_CREDIT_NOTE) { - // Total already paid - print ''; + if ($object->type != Facture::TYPE_CREDIT_NOTE) { + // Total already paid + print ''; - $resteapayeraffiche = $resteapayer; - $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + $resteapayeraffiche = $resteapayer; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; - // Loop on each credit note or deposit amount applied - $creditnoteamount = 0; - $depositamount = 0; - $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_facture_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; - $sql .= " WHERE fk_facture = " . $object->id; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $invoice = new Facture($db); - while ($i < $num) { - $obj = $db->fetch_object($resql); - $invoice->fetch($obj->fk_facture_source); - print ''; - print ''; - print ''; - $i ++; - if ($invoice->type == Facture::TYPE_CREDIT_NOTE) - $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == Facture::TYPE_DEPOSIT) - $depositamount += $obj->amount_ttc; - } - } else { - dol_print_error($db); - } + // Loop on each credit note or deposit amount applied + $creditnoteamount = 0; + $depositamount = 0; + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; + $sql .= " re.description, re.fk_facture_source"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; + $sql .= " WHERE fk_facture = " . $object->id; + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + $invoice = new Facture($db); + while ($i < $num) { + $obj = $db->fetch_object($resql); + $invoice->fetch($obj->fk_facture_source); + print ''; + print ''; + print ''; + $i ++; + if ($invoice->type == Facture::TYPE_CREDIT_NOTE) + $creditnoteamount += $obj->amount_ttc; + if ($invoice->type == Facture::TYPE_DEPOSIT) + $depositamount += $obj->amount_ttc; + } + } else { + dol_print_error($db); + } - // Paye partiellement 'escompte' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { - print ''; - $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; - } - // Paye partiellement ou Abandon 'badcustomer' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') { - print ''; - // $resteapayeraffiche=0; - $cssforamountpaymentcomplete = ''; - } - // Paye partiellement ou Abandon 'product_returned' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') { - print ''; - $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; - } - // Paye partiellement ou Abandon 'abandon' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') { - print ''; - $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; - } + // Paye partiellement 'escompte' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'badcustomer' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') { + print ''; + // $resteapayeraffiche=0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'product_returned' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'abandon' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } - // Billed - print ''; + // Billed + print ''; - // Remainder to pay - print ''; - print ''; - print ''; - } - else // Credit note - { - $cssforamountpaymentcomplete=''; + // Remainder to pay + print ''; + print ''; + print ''; + } + else // Credit note + { + $cssforamountpaymentcomplete=''; - // Total already paid back - print ''; + // Total already paid back + print ''; - // Billed - print ''; + // Billed + print ''; - // Remainder to pay back - print ''; - print ''; - print ''; + // Remainder to pay back + print ''; + print ''; + print ''; - // Sold credit note - // print ''; - // print ''; - } + // Sold credit note + // print ''; + // print ''; + } - print '
    ' . ($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '' . $langs->trans('Date') . '' . $langs->trans('Type') . '' . $langs->trans('BankAccount') . '' . $langs->trans('Amount') . ' 
    ' . ($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '' . $langs->trans('Date') . '' . $langs->trans('Type') . '' . $langs->trans('BankAccount') . '' . $langs->trans('Amount') . ' 
    '; - $paymentstatic->id = $objp->rowid; - $paymentstatic->datepaye = $db->jdate($objp->dp); - $paymentstatic->ref = $objp->ref; - $paymentstatic->num_paiement = $objp->num_paiement; - $paymentstatic->payment_code = $objp->payment_code; - print $paymentstatic->getNomUrl(1); - print '' . dol_print_date($db->jdate($objp->dp), 'day') . '' . $label . ' ' . $objp->num_paiement . '
    '; + print $paymentstatic->getNomUrl(1); + print '' . dol_print_date($db->jdate($objp->dp), 'day') . '' . $label . ' ' . $objp->num_paiement . ''; - if ($bankaccountstatic->id) - print $bankaccountstatic->getNomUrl(1, 'transactions'); - print '' . price($sign * $objp->amount) . ' 
    ' . price($sign * $objp->amount) . ' 
    ' . $langs->trans("None") . '
    '; - if ($object->type != Facture::TYPE_DEPOSIT) - print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); - else - print $langs->trans('AlreadyPaid'); - print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
    '; + if ($object->type != Facture::TYPE_DEPOSIT) + print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); + else + print $langs->trans('AlreadyPaid'); + print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
    '; - if ($invoice->type == Facture::TYPE_CREDIT_NOTE) - print $langs->trans("CreditNote") . ' '; - if ($invoice->type == Facture::TYPE_DEPOSIT) - print $langs->trans("Deposit") . ' '; - print $invoice->getNomUrl(0); - print ' :' . price($obj->amount_ttc) . ''; - print 'rowid . '">' . img_delete() . ''; - print '
    '; + if ($invoice->type == Facture::TYPE_CREDIT_NOTE) + print $langs->trans("CreditNote") . ' '; + if ($invoice->type == Facture::TYPE_DEPOSIT) + print $langs->trans("Deposit") . ' '; + print $invoice->getNomUrl(0); + print ' :' . price($obj->amount_ttc) . ''; + print 'rowid . '">' . img_delete() . ''; + print '
    '; - print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; - print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; - print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; - $text = $langs->trans("HelpAbandonOther"); - if ($object->close_note) - $text .= '

    ' . $langs->trans("Reason") . ':' . $object->close_note; - print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1); - print '
    ' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; + print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1); + print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; + print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1); + print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; + print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1); + print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; + $text = $langs->trans("HelpAbandonOther"); + if ($object->close_note) + $text .= '

    ' . $langs->trans("Reason") . ':' . $object->close_note; + print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1); + print '
    ' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    ' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
    ' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
    '; - if ($resteapayeraffiche >= 0) - print $langs->trans('RemainderToPay'); - else - print $langs->trans('ExcessReceived'); - print ' :' . price($resteapayeraffiche) . ' 
    '; + if ($resteapayeraffiche >= 0) + print $langs->trans('RemainderToPay'); + else + print $langs->trans('ExcessReceived'); + print ' :' . price($resteapayeraffiche) . ' 
    '; - print $langs->trans('AlreadyPaidBack'); - print ' :' . price($sign * $totalpaye) . ' 
    '; + print $langs->trans('AlreadyPaidBack'); + print ' :' . price($sign * $totalpaye) . ' 
    ' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
    ' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
    '; - if ($resteapayeraffiche <= 0) - print $langs->trans('RemainderToPayBack'); - else - print $langs->trans('ExcessPaydBack'); - print ' :' . price($sign * $resteapayeraffiche) . ' 
    '; + if ($resteapayeraffiche <= 0) + print $langs->trans('RemainderToPayBack'); + else + print $langs->trans('ExcessPaydBack'); + print ' :' . price($sign * $resteapayeraffiche) . ' 
    '.$langs->trans('TotalTTC').' :'.price($sign * - // $object->total_ttc).' 
    '.$langs->trans('TotalTTC').' :'.price($sign * + // $object->total_ttc).' 
    '; + print ''; // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } print '
    '; @@ -4018,10 +4086,10 @@ else if ($id > 0 || ! empty($ref)) '; if (! empty($conf->use_javascript_ajax) && $object->statut == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
    '; + print '
    '; print ''; // Show object lines @@ -4044,7 +4112,7 @@ else if ($id > 0 || ! empty($ref)) } print "
    \n"; - print "
    "; + print "
    "; print "\n"; @@ -4061,28 +4129,35 @@ else if ($id > 0 || ! empty($ref)) $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { // Editer une facture deja validee, sans paiement effectue et pas exporte en compta - if ($object->statut == 1) + if ($object->statut == Facture::STATUS_VALIDATED) { // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees $ventilExportCompta = $object->getVentilExportCompta(); - if ($resteapayer == $object->total_ttc && empty($object->paye) && $ventilExportCompta == 0) + if ($ventilExportCompta == 0) { - if (! $objectidnext && $object->is_last_in_cycle()) + if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_EDITED) || ($resteapayer == $object->total_ttc && empty($object->paye))) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + if (! $objectidnext && $object->is_last_in_cycle()) { - print ''; + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + { + print ''; + } else { + print '
    ' . $langs->trans('Modify') . '
    '; + } + } else if (!$object->is_last_in_cycle()) { + print '
    ' . $langs->trans('Modify') . '
    '; } else { - print '
    ' . $langs->trans('Modify') . '
    '; + print '
    ' . $langs->trans('Modify') . '
    '; } - } else if (!$object->is_last_in_cycle()) { - print '
    ' . $langs->trans('Modify') . '
    '; - } else { - print '
    ' . $langs->trans('Modify') . '
    '; } } + else + { + print '
    ' . $langs->trans('Modify') . '
    '; + } } $discount = new DiscountAbsolute($db); @@ -4093,7 +4168,7 @@ else if ($id > 0 || ! empty($ref)) || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id)) || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id))) && ($object->statut == 2 || $object->statut == 3 || ($object->statut == 1 && $object->paye == 1)) // Condition ($object->statut == 1 && $object->paye == 1) should not happened but can be found due to corrupted data - && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->invoice_advance->reopen))) // A paid invoice (partially or completely) + && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->invoice_advance->reopen))) // A paid invoice (partially or completely) { if (! $objectidnext && $object->close_code != 'replaced') // Not replaced by another invoice { @@ -4104,9 +4179,9 @@ else if ($id > 0 || ! empty($ref)) } // Validate - if ($object->statut == 0 && count($object->lines) > 0 && ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0)) || ($object->type == Facture::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) { + if ($object->statut == Facture::STATUS_DRAFT && count($object->lines) > 0 && ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0)) || ($object->type == Facture::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) { print ''; } @@ -4127,22 +4202,22 @@ else if ($id > 0 || ! empty($ref)) // Request a direct debit order if ($object->statut > Facture::STATUS_DRAFT && $object->paye == 0 && $num == 0) { - if ($resteapayer > 0) - { - if ($user->rights->prelevement->bons->creer) - { - $langs->load("withdrawals"); - print ''.$langs->trans("MakeWithdrawRequest").''; - } - else - { - //print ''.$langs->trans("MakeWithdrawRequest").''; - } - } - else - { - //print ''.$langs->trans("MakeWithdrawRequest").''; - } + if ($resteapayer > 0) + { + if ($user->rights->prelevement->bons->creer) + { + $langs->load("withdrawals"); + print ''.$langs->trans("MakeWithdrawRequest").''; + } + else + { + //print ''.$langs->trans("MakeWithdrawRequest").''; + } + } + else + { + //print ''.$langs->trans("MakeWithdrawRequest").''; + } } // Create payment @@ -4260,7 +4335,7 @@ else if ($id > 0 || ! empty($ref)) // Delete if ($user->rights->facture->supprimer) { - if (! $object->is_erasable()) { + if ($object->is_erasable() <= 0) { print ''; } else if ($objectidnext) { print ''; @@ -4279,7 +4354,7 @@ else if ($id > 0 || ! empty($ref)) print '
    '; // Select mail models is same action as presend - if (GETPOST('modelselected')) { + if (GETPOST('modelselected','alpha')) { $action = 'presend'; } if ($action != 'prerelance' && $action != 'presend') @@ -4301,16 +4376,21 @@ else if ($id > 0 || ! empty($ref)) $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - // Link for paypal payment - if (! empty($conf->paypal->enabled) && $object->statut != 0) { - include_once DOL_DOCUMENT_ROOT . '/paypal/lib/paypal.lib.php'; - print showPaypalPaymentUrl('invoice', $object->ref); + + // Show online payment link + $useonlinepayment = (! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled)); + + if ($object->statut != Facture::STATUS_DRAFT && $useonlinepayment) + { + print '
    '."\n"; + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + print showOnlinePaymentUrl('invoice', $object->ref).'
    '; } - // Link for stripe payment - if (! empty($conf->stripe->enabled) && $object->statut != 0) { - include_once DOL_DOCUMENT_ROOT . '/stripe/lib/stripe.lib.php'; - print showStripePaymentUrl('invoice', $object->ref); + if ($object->statut != Facture::STATUS_DRAFT && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) + { + print '
    '."\n"; + print showDirectDownloadLink($object).'
    '; } print '
    '; @@ -4318,147 +4398,19 @@ else if ($id > 0 || ! empty($ref)) // List of actions on element include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'invoice', $socid); + $somethingshown = $formactions->showactions($object, 'invoice', $socid, 1); print '
    '; } - else - { - /* - * Action presend (or prerelance) - */ - $object->fetch_projet(); - // By default if $action=='presend' - $titreform = 'SendBillByMail'; - $topicmail = 'SendBillRef'; - $modelmail = 'facture_send'; + // Presend form + $modelmail='facture_send'; + $defaulttopic='SendBillRef'; + $diroutput = $conf->facture->dir_output; + $trackid = 'inv'.$object->id; - if ($action == 'prerelance') // For backward compatibility - { - $titrefrom = 'SendReminderBillByMail'; - $topicmail = 'SendReminderBillRef'; - $modelmail = 'facture_relance'; - $action = 'relance'; - } else - $action = 'send'; - - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - - if (!empty($newlang)) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($newlang); - $outputlangs->load('bills'); - } - - // Build document if it not exists - if (! $file || ! is_readable($file)) { - $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) { - dol_print_error($db, $object->error, $object->errors); - exit(); - } - $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - } - - print '
    '; - print '
    '; - print '
    '; - print load_fiche_titre($langs->trans($titreform)); - - // Cree l'objet formulaire mail - dol_fiche_head(); - - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - $formmail->trackid='inv'.$object->id; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'inv'.$object->id); - } - $formmail->withfrom = 1; - $liste = array(); - foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) { - $liste [$key] = $value; - } - $formmail->withto = GETPOST('sendto') ? GETPOST('sendto') : $liste; // List suggested for send to - $formmail->withtocc = $liste; // List suggested for CC - $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; - if (empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__REF__'); - } else if (! empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__REF__ (__REFCLIENT__)'); - } - - $formmail->withfile = 2; - $formmail->withbody = 1; - $formmail->withdeliveryreceipt = 1; - $formmail->withcancel = 1; - // Tableau des substitutions - $formmail->setSubstitFromObject($object, $outputlangs); - $formmail->substit['__INVREF__'] = $object->ref; - - // Find the good contact adress - $custcontact = ''; - $contactarr = array(); - $contactarr = $object->liste_contact(- 1, 'external'); - - if (is_array($contactarr) && count($contactarr) > 0) { - foreach ($contactarr as $contact) { - if ($contact['libelle'] == $langs->trans('TypeContact_facture_external_BILLING')) { // TODO Use code and not label - - require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; - - $contactstatic = new Contact($db); - $contactstatic->fetch($contact ['id']); - $custcontact = $contactstatic->getFullName($langs, 1); - } - } - - if (! empty($custcontact)) { - $formmail->substit['__CONTACTCIVNAME__'] = $custcontact; - } - } - - // Tableau des parametres complementaires du post - $formmail->param['action'] = $action; - $formmail->param['models'] = $modelmail; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['facid'] = $object->id; - $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; - - // Init list of files - if (GETPOST("mode") == 'init') { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file, basename($file), dol_mimetype($file)); - } - - print $formmail->get_form(); - - dol_fiche_end(); - } + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } llxFooter(); diff --git a/htdocs/compta/facture/class/api_deprecated_invoice.class.php b/htdocs/compta/facture/class/api_deprecated_invoice.class.php index 360c065a5f2..ac2086fc87e 100644 --- a/htdocs/compta/facture/class/api_deprecated_invoice.class.php +++ b/htdocs/compta/facture/class/api_deprecated_invoice.class.php @@ -23,7 +23,7 @@ * API class for invoice object * * @smart-auto-routing false - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} * @deprecated Use Invoices instead (defined in api_invoices.class.php) */ @@ -31,7 +31,7 @@ class InvoiceApi extends DolibarrApi { /** * - * @var array $FIELDS Mandatory fields, checked when create and update object + * @var array $FIELDS Mandatory fields, checked when create and update object */ static $FIELDS = array( 'socid' @@ -46,7 +46,7 @@ class InvoiceApi extends DolibarrApi * Constructor Warning: Deprecated * * @url GET invoice/ - * + * */ function __construct() { @@ -59,7 +59,7 @@ class InvoiceApi extends DolibarrApi * Get properties of a invoice object Warning: Deprecated * * Return an array with invoice informations - * + * * @param int $id ID of invoice * @return array|mixed data without useless information * @@ -67,16 +67,16 @@ class InvoiceApi extends DolibarrApi * @throws RestException */ function get($id) - { + { if(! DolibarrApiAccess::$user->rights->facture->lire) { throw new RestException(401); } - + $result = $this->invoice->fetch($id); if( ! $result ) { throw new RestException(404, 'Facture not found'); } - + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -86,9 +86,9 @@ class InvoiceApi extends DolibarrApi /** * List invoices Warning: Deprecated - * + * * Get a list of invoices - * + * * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list @@ -101,15 +101,15 @@ class InvoiceApi extends DolibarrApi * @url GET invoice/list * @url GET invoice/list/{mode} * @url GET thirdparty/{socid}/invoice/list - * @url GET thirdparty/{socid}/invoice/list/{mode} + * @url GET thirdparty/{socid}/invoice/list/{mode} */ - function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $socid=0, $mode='') { + function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $socid=0, $mode='') { global $db, $conf; - + $obj_ret = array(); - + $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $socid; - + // If the internal user must only see his customers, force searching by him $search_sale = 0; if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; @@ -117,27 +117,27 @@ class InvoiceApi extends DolibarrApi $sql = "SELECT s.rowid"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) $sql.= " FROM ".MAIN_DB_PREFIX."facture as s"; - + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale $sql.= ' WHERE s.entity IN ('.getEntity('facture').')'; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND s.fk_soc = sc.fk_soc"; if ($socid) $sql.= " AND s.fk_soc = ".$socid; if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - - + + // Example of use $mode if ($mode == 'draft') $sql.= " AND s.fk_statut IN (0)"; if ($mode == 'unpaid') $sql.= " AND s.fk_statut IN (1)"; if ($mode == 'paid') $sql.= " AND s.fk_statut IN (2)"; if ($mode == 'cancelled') $sql.= " AND s.fk_statut IN (3)"; - + // Insert sale filter if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } - + $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { @@ -180,10 +180,10 @@ class InvoiceApi extends DolibarrApi } return $obj_ret; } - + /** * Create invoice object Warning: Deprecated - * + * * @param array $request_data Request datas * @return int ID of invoice * @@ -196,7 +196,7 @@ class InvoiceApi extends DolibarrApi } // Check mandatory fields $result = $this->_validate($request_data); - + foreach($request_data as $field => $value) { $this->invoice->$field = $value; } @@ -213,9 +213,9 @@ class InvoiceApi extends DolibarrApi * Update invoice Warning: Deprecated * * @param int $id Id of invoice to update - * @param array $request_data Datas - * @return int - * + * @param array $request_data Datas + * @return int + * * @url PUT invoice/{id} */ function put($id, $request_data = NULL) @@ -223,12 +223,12 @@ class InvoiceApi extends DolibarrApi if(! DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); } - + $result = $this->invoice->fetch($id); if( ! $result ) { throw new RestException(404, 'Facture not found'); } - + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -237,20 +237,20 @@ class InvoiceApi extends DolibarrApi if ($field == 'id') continue; $this->invoice->$field = $value; } - + if($this->invoice->update($id, DolibarrApiAccess::$user)) return $this->get ($id); - + return false; } - + /** * Delete invoice Warning: Deprecated * * @param int $id Invoice ID * @return type - * - * @url DELETE invoice/{id} + * + * @url DELETE invoice/{id} */ function delete($id) { @@ -261,31 +261,31 @@ class InvoiceApi extends DolibarrApi if( ! $result ) { throw new RestException(404, 'Facture not found'); } - + if( ! DolibarrApi::_checkAccessToResource('facture',$this->facture->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + if( !$this->invoice->delete(DolibarrApiAccess::$user)) { throw new RestException(500); } - + return array( 'success' => array( 'code' => 200, 'message' => 'Facture deleted' ) ); - + } - + /** * Validate fields before create or update object - * + * * @param array $data Datas to validate * @return array - * + * * @throws RestException */ function _validate($data) diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index 6c55e24f788..222404411d7 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -71,6 +71,12 @@ class Invoices extends DolibarrApi throw new RestException(404, 'Invoice not found'); } + // Get payment details + $this->invoice->totalpaye = $this->invoice->getSommePaiement(); + $this->invoice->totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); + $this->invoice->totaldeposits = $this->invoice->getSumDepositsUsed(); + $this->invoice->resteapayer = price2num($this->invoice->total_ttc - $this->invoice->totalpaye - $this->invoice->totalcreditnotes - $this->invoice->totaldeposits, 'MT'); + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -95,7 +101,7 @@ class Invoices extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -193,7 +199,7 @@ class Invoices extends DolibarrApi foreach($request_data as $field => $value) { $this->invoice->$field = $value; } - if(! array_keys($request_data,'date')) { + if(! array_key_exists('date', $request_data)) { $this->invoice->date = dol_now(); } /* We keep lines as an array @@ -241,69 +247,6 @@ class Invoices extends DolibarrApi return $result; } - /** - * Add a line to a given invoice - * - * @param int $id Id of invoice to update - * @param array $request_data InvoiceLine data - * - * @url POST {id}/lines - * - * @return int - */ - function postLine($id, $request_data = NULL) { - if(! DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Invoice not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->invoice->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - $request_data->date_start, - $request_data->date_end, - 0, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $request_data->origin, - $request_data->origin_id, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->situation_percent, - $request_data->prev_id, - $request_data->fk_unit, - $request_data->multicurrency_subprice - ); - - if ($updateRes > 0) { - return $updateRes; - - } - return false; - } - /** * Update a line to a given invoice * @@ -364,35 +307,50 @@ class Invoices extends DolibarrApi } /** - * Delete a line to a given invoice + * Deletes a line of a given invoice * + * @param int $id Id of invoice + * @param int $lineid Id of the line to delete * - * @param int $id Id of invoice to update - * @param int $lineid Id of line to delete + * @url DELETE {id}/lines/{lineid} * - * @url DELETE {id}/lines/{lineid} - * - * @return int + * @return array + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 405 */ - function delLine($id, $lineid) { + function deleteLine($id, $lineid) { + if(! DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); } + if(empty($lineid)) { + throw new RestException(400, 'Line ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } $result = $this->invoice->fetch($id); if( ! $result ) { throw new RestException(404, 'Invoice not found'); } - if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + $result = $this->invoice->deleteline($lineid); + if( $result < 0) { + throw new RestException(405, $this->invoice->error); } - $request_data = (object) $request_data; - $updateRes = $this->invoice->deleteline($lineid); - if ($updateRes > 0) { - return $this->get($id); + + $result = $this->invoice->fetch($id); + + $this->invoice->getLinesArray(); + $result = array(); + foreach ($this->invoice->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); } - return false; + return $result; } /** @@ -461,6 +419,129 @@ class Invoices extends DolibarrApi ); } + /** + * Add a line to a given invoice + * + * Exemple of POST query : { "desc": "Desc", "subprice": "1.00000000", "qty": "1", "tva_tx": "20.000", "localtax1_tx": "0.000", "localtax2_tx": "0.000", "fk_product": "1", "remise_percent": "0", "date_start": "", "date_end": "", "fk_code_ventilation": 0, "info_bits": "0", "fk_remise_except": null, "product_type": "1", "rang": "-1", "special_code": "0", "fk_parent_line": null, "fk_fournprice": null, "pa_ht": "0.00000000", "label": "", "array_options": [], "situation_percent": "100", "fk_prev_id": null, "fk_unit": null } + * + * @param int $id Id of invoice + * @param array $request_data InvoiceLine data + * + * @url POST {id}/lines + * + * @return int + */ + function postLine($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + + // Reset fk_parent_line for no child products and special product + if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) { + $request_data->fk_parent_line = 0; + } + + $updateRes = $this->invoice->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->date_start, + $request_data->date_end, + $request_data->fk_code_ventilation, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + 'facture', + $id, + $request_data->fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->situation_percent, + $request_data->fk_prev_id, + $request_data->fk_unit + ); + + if ($updateRes > 0) { + return $updateRes; + + } + throw new RestException(400, 'Unable to insert the new line. Check your inputs.'); + } + + /** + * Sets an invoice as draft + * + * @param int $id Order ID + * @param int $idwarehouse Warehouse ID + * + * @url POST {id}/settodraft + * + * @return array + * + * @throws 200 + * @throws 304 + * @throws 401 + * @throws 404 + * @throws 500 + * + */ + function settodraft($id, $idwarehouse=-1) + { + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->set_draft(DolibarrApiAccess::$user, $idwarehouse); + if ($result == 0) { + throw new RestException(304, 'Nothing done.'); + } + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->invoice->error); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + /** * Validate an invoice * @@ -495,18 +576,321 @@ class Invoices extends DolibarrApi $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger); if ($result == 0) { - throw new RestException(500, 'Error nothing done. May be object is already validated'); + throw new RestException(304, 'Error nothing done. May be object is already validated'); } if ($result < 0) { throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error); } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Invoice validated (Ref='.$this->invoice->ref.')' - ) - ); + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($this->invoice); + + + } + + /** + * Sets an invoice as paid + * + * @param int $id Order ID + * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple) + * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple) + * + * @url POST {id}/settopaid + * + * @return array An invoice object + * + * @throws 200 + * @throws 304 + * @throws 401 + * @throws 404 + * @throws 500 + */ + function settopaid($id, $close_code='', $close_note='') + { + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->set_paid(DolibarrApiAccess::$user, $close_code, $close_note); + if ($result == 0) { + throw new RestException(304, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->invoice->error); + } + + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($this->invoice); + + + } + + + /** + * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) + * + * @param int $id Id of invoice + * @param int $discountid Id of discount + * + * @url POST {id}/usediscount/{discountid} + * + * @return int + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 405 + */ + function useDiscount($id, $discountid) { + + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + if(empty($discountid)) { + throw new RestException(400, 'Discount ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + $result = $this->invoice->insert_discount($discountid); + if( $result < 0) { + throw new RestException(405, $this->invoice->error); + } + + return $result; + } + + /** + * Add an available credit note discount to payments of an existing invoice (Consume the credit note) + * + * @param int $id Id of invoice + * @param int $discountid Id of a discount coming from a credit note + * + * @url POST {id}/usecreditnote/{discountid} + * + * @return int + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 405 + */ + function useCreditNote($id, $discountid) { + + require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php'; + + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + if(empty($discountid)) { + throw new RestException(400, 'Credit ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $discount = new DiscountAbsolute($this->db); + $result = $discount->fetch($discountid); + if( ! $result ) { + throw new RestException(404, 'Credit not found'); + } + + $result = $discount->link_to_invoice(0, $id); + if( $result < 0) { + throw new RestException(405, $discount->error); + } + + return $result; + } + + /** + * Get list of payments of a given invoice + * + * @param int $id Id of invoice + * + * @url GET {id}/payments + * + * @return array + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 405 + */ + function getPayments($id) { + + if(! DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + $result = $this->invoice->getListOfPayments(); + if( $result < 0) { + throw new RestException(405, $this->invoice->error); + } + + return $result; + } + + /** + * Add payment line to a specific invoice + * + * The model schema is defined by the PaymentData class. + * + * @param int $id Id of invoice + * @param string $datepaye {@from body} Payment date {@type timestamp} + * @param int $paiementid {@from body} Payment mode Id {@min 1} + * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} + * @param int $accountid {@from body} Account Id {@min 1} + * @param string $num_paiement {@from body} Payment number (optional) + * @param string $comment {@from body} Note (optional) + * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') + * @param string $chqbank {@from body} Issuer bank name (optional) + * + * @url POST {id}/payments + * + * @return int Payment ID + * @throws 400 + * @throws 401 + * @throws 404 + */ + function addPayment($id, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement='', $comment='', $chqemetteur='', $chqbank='') { + global $conf; + + require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php'; + + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $payment_data; + + if (! empty($conf->banque->enabled)) { + if(empty($accountid)) { + throw new RestException(400, 'Account ID is mandatory'); + } + } + + if(empty($paiementid)) { + throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); + } + + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + // Calculate amount to pay + $totalpaye = $this->invoice->getSommePaiement(); + $totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); + $totaldeposits = $this->invoice->getSumDepositsUsed(); + $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); + + $this->db->begin(); + // Clean parameters amount if payment is for a credit note + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $resteapayer = price2num($resteapayer,'MT'); + $amounts[$id] = -$resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); + $multicurrency_amounts[$id] = -$newvalue; + } else { + $resteapayer = price2num($resteapayer,'MT'); + $amounts[$id] = $resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); + $multicurrency_amounts[$id] = $newvalue; + } + + + // Creation of payment line + $paiement = new Paiement($this->db); + $paiement->datepaye = $datepaye; + $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id + $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching + $paiement->paiementid = $paiementid; + $paiement->paiementcode = dol_getIdFromCode($this->db,$paiementid,'c_paiement','id','code',1); + $paiement->num_paiement = $num_paiement; + $paiement->note = $comment; + + $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices=='yes'?1:0)); // This include closing invoices + if ($paiement_id < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Payment error : '.$paiement->error); + } + + if (! empty($conf->banque->enabled)) { + $label='(CustomerInvoicePayment)'; + + if($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) { + throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode); + } + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label='(CustomerInvoicePaymentBack)'; // Refund of a credit note + $result=$paiement->addPaymentToBank(DolibarrApiAccess::$user,'payment',$label,$accountid,$chqemetteur,$chqbank); + if ($result < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Add payment to bank error : '.$paiement->error); + } + } + $this->db->commit(); + return $paiement_id; } /** @@ -520,6 +904,10 @@ class Invoices extends DolibarrApi $object = parent::_cleanObjectDatas($object); unset($object->address); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); return $object; } diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 779f4545f77..b46c249d1b0 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -141,7 +141,7 @@ class FactureRec extends CommonInvoice $sql.= ", nb_gen_max"; $sql.= ", auto_validate"; $sql.= ") VALUES ("; - $sql.= "'".$this->titre."'"; + $sql.= "'".$this->db->escape($this->titre)."'"; $sql.= ", ".$facsrc->socid; $sql.= ", ".$conf->entity; $sql.= ", '".$this->db->idate($now)."'"; @@ -149,11 +149,11 @@ class FactureRec extends CommonInvoice $sql.= ", ".(!empty($facsrc->remise)?$this->remise:'0'); $sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL"); $sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL"); - $sql.= ", '".$user->id."'"; + $sql.= ", '".$this->db->escape($user->id)."'"; $sql.= ", ".(! empty($facsrc->fk_project)?"'".$facsrc->fk_project."'":"null"); $sql.= ", ".(! empty($facsrc->fk_account)?"'".$facsrc->fk_account."'":"null"); - $sql.= ", '".$facsrc->cond_reglement_id."'"; - $sql.= ", '".$facsrc->mode_reglement_id."'"; + $sql.= ", ".($facsrc->cond_reglement_id > 0 ? $this->db->escape($facsrc->cond_reglement_id) : "null"); + $sql.= ", ".($facsrc->mode_reglement_id > 0 ? $this->db->escape($facsrc->mode_reglement_id) : "null"); $sql.= ", ".$this->usenewprice; $sql.= ", ".$this->frequency; $sql.= ", '".$this->db->escape($this->unit_frequency)."'"; @@ -272,7 +272,7 @@ class FactureRec extends CommonInvoice */ function fetch($rowid, $ref='', $ref_ext='', $ref_int='') { - $sql = 'SELECT f.rowid, f.entity, f.titre, f.fk_soc, f.amount, f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc'; + $sql = 'SELECT f.rowid, f.entity, f.titre, f.suspended, f.fk_soc, f.amount, f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc'; $sql.= ', f.remise_percent, f.remise_absolue, f.remise'; $sql.= ', f.date_lim_reglement as dlr'; $sql.= ', f.note_private, f.note_public, f.fk_user_author'; @@ -283,8 +283,8 @@ class FactureRec extends CommonInvoice $sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc'; //$sql.= ', el.fk_source'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN (' . getEntity('c_payment_term').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement').')'; //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'"; if ($rowid) $sql.= ' WHERE f.rowid='.$rowid; elseif ($ref) $sql.= " WHERE f.titre='".$this->db->escape($ref)."'"; @@ -305,6 +305,7 @@ class FactureRec extends CommonInvoice $this->titre = $obj->titre; $this->ref = $obj->titre; $this->ref_client = $obj->ref_client; + $this->suspended = $obj->suspended; $this->type = $obj->type; $this->datep = $obj->dp; $this->date = $obj->df; @@ -321,7 +322,6 @@ class FactureRec extends CommonInvoice $this->close_code = $obj->close_code; $this->close_note = $obj->close_note; $this->socid = $obj->fk_soc; - $this->statut = $obj->fk_statut; $this->date_lim_reglement = $this->db->jdate($obj->dlr); $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; @@ -350,6 +350,13 @@ class FactureRec extends CommonInvoice if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; + // Retreive all extrafield for thirdparty + // fetch optionals attributes and labels + require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + $this->fetch_optionals($this->id,$extralabels); + /* * Lines */ @@ -420,7 +427,7 @@ class FactureRec extends CommonInvoice while ($i < $num) { $objp = $this->db->fetch_object($result); - $line = new FactureLigne($this->db); + $line = new FactureLigneRec($this->db); $line->id = $objp->rowid; $line->rowid = $objp->rowid; @@ -460,6 +467,14 @@ class FactureRec extends CommonInvoice $line->price = $objp->price; $line->remise = $objp->remise; + // Retreive all extrafield for thirdparty + // fetch optionals attributes and labels + require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); + $extrafieldsline=new ExtraFields($line->db); + $extrafieldsline=$extrafieldsline->fetch_name_optionals_label($line->table_element,true); + $extralabelsline = $line->fetch_optionals($line->id,$extrafieldsline); + + $this->lines[$i] = $line; $i++; @@ -484,7 +499,7 @@ class FactureRec extends CommonInvoice * @param int $idwarehouse Id warehouse to use for stock change. * @return int <0 if KO, >0 if OK */ - function delete($user, $notrigger=0, $idwarehouse=-1) + function delete(User $user, $notrigger=0, $idwarehouse=-1) { $rowid=$this->id; @@ -674,9 +689,10 @@ class FactureRec extends CommonInvoice dol_syslog(get_class($this)."::addline", LOG_DEBUG); if ($this->db->query($sql)) { + $lineId = $this->db->last_insert_id(MAIN_DB_PREFIX."facturedet_rec"); $this->id=$facid; $this->update_price(); - return 1; + return $lineId; } else { @@ -718,6 +734,9 @@ class FactureRec extends CommonInvoice dol_syslog(get_class($this)."::updateline facid=".$facid." rowid=$rowid,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva,txlocaltax1=$txlocaltax1,txlocaltax2=$txlocaltax2,fk_product=$fk_product,remise_percent=$remise_percent,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type,fk_unit=$fk_unit", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + // Clean parameters + if (empty($remise_percent)) $remise_percent = 0; + // Check parameters if ($type < 0) return -1; @@ -825,6 +844,30 @@ class FactureRec extends CommonInvoice return dol_time_plus_duree($this->date_when, $this->frequency, $this->unit_frequency); } + /** + * Return if maximum number of generation is reached + * + * @return boolean False by default, True if maximum number of generation is reached + */ + function isMaxNbGenReached() + { + $ret = false; + if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) $ret = true; + return $ret; + } + + /** + * Format string to output with by striking the string if max number of generation was reached + * + * @param string $ret Default value to output + * @return boolean False by default, True if maximum number of generation is reached + */ + function strikeIfMaxNbGenReached($ret) + { + // Special case to strike the date + return ($this->isMaxNbGenReached()?'':'').$ret.($this->isMaxNbGenReached()?'':''); + } + /** * Create all recurrents invoices (for all entities if multicompany is used). * A result may also be provided into this->output. @@ -888,6 +931,7 @@ class FactureRec extends CommonInvoice $facture->brouillon = 1; $facture->date = $facturerec->date_when; // We could also use dol_now here but we prefer date_when so invoice has real date when we would like even if we generate later. $facture->socid = $facturerec->socid; + $facture->suspended = 0; $invoiceidgenerated = $facture->create($user); if ($invoiceidgenerated <= 0) @@ -965,6 +1009,95 @@ class FactureRec extends CommonInvoice return $result; } + /** + * Return label of object status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto + * @param integer $alreadypaid Not used + * @return string Label + */ + function getLibStatut($mode=0,$alreadypaid=-1) + { + return $this->LibStatut($this->frequency?1:0, $this->suspended, $mode, $alreadypaid, $this->type); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $recur Is it a recurring invoice ? + * @param int $status Id status (suspended or not) + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=long label + picto + * @param int $alreadypaid Not used + * @param int $type Type invoice + * @return string Libelle du statut + */ + function LibStatut($recur,$status,$mode=0,$alreadypaid=-1,$type=0) + { + global $langs; + $langs->load('bills'); + + //print "$recur,$status,$mode,$alreadypaid,$type"; + if ($mode == 0) + { + $prefix=''; + if ($recur) + { + if ($status == 1) return $langs->trans('Suspended'); // credit note + else return $langs->trans('Active'); + } + else return $langs->trans("Draft"); + } + if ($mode == 1) + { + $prefix='Short'; + if ($recur) + { + if ($status == 1) return $langs->trans('Suspended'); + else return $langs->trans('Active'); + } + else return $langs->trans("Draft"); + } + if ($mode == 2) + { + if ($recur) + { + if ($status == 1) return img_picto($langs->trans('Suspended'),'statut6').' '.$langs->trans('Suspended'); + else return img_picto($langs->trans('Active'),'statut4').' '.$langs->trans('Active'); + } + else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft'); + } + if ($mode == 3) + { + if ($recur) + { + $prefix='Short'; + if ($status == 1) return img_picto($langs->trans('Suspended'),'statut6'); + else return img_picto($langs->trans('Active'),'statut4'); + } + else return img_picto($langs->trans('Draft'),'statut0'); + } + if ($mode == 4) + { + $prefix=''; + if ($recur) + { + if ($type == 1) return img_picto($langs->trans('Suspended'),'statut6').' '.$langs->trans('Suspended'); + else return img_picto($langs->trans('Active'),'statut4').' '.$langs->trans('Active'); + } + else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft'); + } + if ($mode == 5 || $mode == 6) + { + $prefix=''; + if ($mode == 5) $prefix='Short'; + if ($recur) + { + if ($status == 1) return ''.$langs->trans('Suspended').' '.img_picto($langs->trans('Suspended'),'statut6'); + else return ''.$langs->trans('Active').' '.img_picto($langs->trans('Active'),'statut4'); + } + else return $langs->trans('Draft').' '.img_picto($langs->trans('Active'),'statut0'); + } + } /** * Initialise an instance with random values. @@ -1268,43 +1401,205 @@ class FactureRec extends CommonInvoice */ class FactureLigneRec extends CommonInvoiceLine { + public $element='facturedetrec'; + public $table_element='facturedet_rec'; /** * Delete line in database * - * @return int <0 if KO, >0 if OK + * @param User $user Object user + * @param int $notrigger Disable triggers + * @return int <0 if KO, >0 if OK */ - function delete() + function delete(User $user, $notrigger = false) { - global $conf,$langs,$user; + $error=0; - $error=0; + $this->db->begin(); - $this->db->begin(); + if (! $error) { + if (! $notrigger) { + // Call triggers + $result=$this->call_trigger('LINEBILLREC_DELETE', $user); + if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail + // End call triggers + } + } - // Call trigger - /*$result=$this->call_trigger('LINEBILLREC_DELETE',$user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - }*/ - // End call triggers + if (! $error) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; + + $res = $this->db->query($sql); + if($res===false) { + $error++; + $this->errors[] = $this->db->lasterror(); + } + } + + // Commit or rollback + if ($error) { + $this->db->rollback(); + return -1; + } else { + $this->db->commit(); + return 1; + } + } - $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE rowid = ".($this->rowid > 0 ? $this->rowid : $this->id); - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if ($this->db->query($sql) ) - { - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error()." sql=".$sql; - $this->db->rollback(); - return -1; - } + /** + * Recupere les lignes de factures predefinies dans this->lines + * + * @param int $rowid Id of invoice + * @return int 1 if OK, < 0 if KO + */ + function fetch($rowid) + { + $sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; + $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; + $sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; + $sql.= ' l.rang, l.special_code,'; + $sql.= ' l.fk_unit, l.fk_contract_line,'; + $sql.= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; + $sql.= ' WHERE l.rowid = '.$rowid; + $sql.= ' ORDER BY l.rang'; + + dol_syslog('FactureRec::fetch', LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + + $objp = $this->db->fetch_object($result); + + $this->id = $objp->rowid; + $this->label = $objp->custom_label; // Label line + $this->desc = $objp->description; // Description line + $this->description = $objp->description; // Description line + $this->product_type = $objp->product_type; // Type of line + $this->ref = $objp->product_ref; // Ref product + $this->product_ref = $objp->product_ref; // Ref product + $this->libelle = $objp->product_label; // deprecated + $this->product_label = $objp->product_label; // Label product + $this->product_desc = $objp->product_desc; // Description product + $this->fk_product_type = $objp->fk_product_type; // Type of product + $this->qty = $objp->qty; + $this->price = $objp->price; + $this->subprice = $objp->subprice; + $this->fk_facture = $objp->fk_facture; + $this->vat_src_code = $objp->vat_src_code; + $this->tva_tx = $objp->tva_tx; + $this->localtax1_tx = $objp->localtax1_tx; + $this->localtax2_tx = $objp->localtax2_tx; + $this->localtax1_type = $objp->localtax1_type; + $this->localtax2_type = $objp->localtax2_type; + $this->remise_percent = $objp->remise_percent; + $this->fk_remise_except = $objp->fk_remise_except; + $this->fk_product = $objp->fk_product; + $this->info_bits = $objp->info_bits; + $this->total_ht = $objp->total_ht; + $this->total_tva = $objp->total_tva; + $this->total_ttc = $objp->total_ttc; + $this->code_ventilation = $objp->fk_code_ventilation; + $this->rang = $objp->rang; + $this->special_code = $objp->special_code; + $this->fk_unit = $objp->fk_unit; + $this->fk_contract_line = $objp->fk_contract_line; + + + $this->db->free($result); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + return -3; + } + } + + + /** + * Update a line to invoice_rec. + * + * @return int <0 if KO, Id of line if OK + */ + function update() + { + global $user; + + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + + if ($fk_product) + { + $product=new Product($this->db); + $result=$product->fetch($fk_product); + $product_type=$product->type; + } + + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET "; + $sql.= " fk_facture = ".$this->fk_facture; + $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); + $sql.= ", description='".$this->db->escape($this->desc)."'"; + $sql.= ", price=".price2num($this->price); + $sql.= ", qty=".price2num($this->qty); + $sql.= ", tva_tx=".price2num($this->tva_tx); + $sql.= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'"; + $sql.= ", localtax1_tx=".price2num($this->localtax1_tx); + $sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; + $sql.= ", localtax2_tx=".price2num($this->localtax2_tx); + $sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; + $sql.= ", fk_product=".($this->fk_product > 0 ? $this->fk_product :"null"); + $sql.= ", product_type=".$this->product_type; + $sql.= ", remise_percent='".price2num($this->remise_percent)."'"; + $sql.= ", subprice='".price2num($this->subprice)."'"; + $sql.= ", total_ht='".price2num($this->total_ht)."'"; + $sql.= ", total_tva='".price2num($this->total_tva)."'"; + $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'"; + $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'"; + $sql.= ", total_ttc='".price2num($this->total_ttc)."'"; + $sql.= ", rang=".$this->rang; + $sql.= ", special_code=".$this->special_code; + $sql.= ", fk_unit=".($this->fk_unit ?"'".$this->db->escape($this->fk_unit )."'":"null"); + $sql.= ", fk_contract_line=".($this->fk_contract_line?$this->fk_contract_line:"null"); + + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::updateline", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINEBILL_REC_UPDATE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -2; + } + // End call triggers + } + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -2; + } + } } diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index c0be06da6bd..9801726246b 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -52,7 +52,7 @@ class Facture extends CommonInvoice public $table_element='facture'; public $table_element_line = 'facturedet'; public $fk_element = 'fk_facture'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='bill'; /** @@ -79,6 +79,8 @@ class Facture extends CommonInvoice public $remise_percent; public $total_ht=0; public $total_tva=0; + public $total_localtax1=0; + public $total_localtax2=0; public $total_ttc=0; public $revenuestamp; @@ -244,7 +246,7 @@ class Facture extends CommonInvoice $this->brouillon = 1; if (empty($this->entity)) $this->entity = $conf->entity; - // Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate) + // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate) if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); if (empty($this->fk_multicurrency)) @@ -286,13 +288,15 @@ class Facture extends CommonInvoice $result=$_facrec->fetch($this->fac_rec); $result=$_facrec->fetchObjectLinked(); // This load $_facrec->linkedObjectsIds + $originaldatewhen = $_facrec->date_when; + $this->socid = $_facrec->socid; // Invoice created on same thirdparty than template $this->entity = $_facrec->entity; // Invoice created in same entity than template // Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI $this->fk_project = GETPOST('projectid','int') > 0 ? GETPOST('projectid','int') : $_facrec->fk_project; - $this->note_public = GETPOST('note_public') ? GETPOST('note_public') : $_facrec->note_public; - $this->note_private = GETPOST('note_private') ? GETPOST('note_private') : $_facrec->note_private; + $this->note_public = GETPOST('note_public','none') ? GETPOST('note_public','none') : $_facrec->note_public; + $this->note_private = GETPOST('note_private','none') ? GETPOST('note_private','none') : $_facrec->note_private; $this->modelpdf = GETPOST('model') ? GETPOST('model') : $_facrec->modelpdf; $this->cond_reglement_id = GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id; $this->mode_reglement_id = GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id; @@ -315,6 +319,8 @@ class Facture extends CommonInvoice $this->note_private=trim($this->note_private); $this->note_private=dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref)); + $this->array_options=$_facrec->array_options; + //if (! $this->remise) $this->remise = 0; if (! $this->mode_reglement_id) $this->mode_reglement_id = 0; $this->brouillon = 1; @@ -347,19 +353,21 @@ class Facture extends CommonInvoice } // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) - $substitutionarray=array( - '__TOTAL_HT__' => price($this->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency_code), - '__TOTAL_TTC__' => price($this->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency_code), - '__INVOICE_PREVIOUS_MONTH__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m'), - '__INVOICE_MONTH__' => dol_print_date($this->date, '%m'), - '__INVOICE_NEXT_MONTH__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m'), - '__INVOICE_PREVIOUS_MONTH_TEXT__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B'), - '__INVOICE_MONTH_TEXT__' => dol_print_date($this->date, '%B'), - '__INVOICE_NEXT_MONTH_TEXT__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B'), - '__INVOICE_PREVIOUS_YEAR__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y'), - '__INVOICE_YEAR__' => dol_print_date($this->date, '%Y'), - '__INVOICE_NEXT_YEAR__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y'), - ); + $substitutionarray=getCommonSubstitutionArray($outputlangs, 0, null, $this); + $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m'); + $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m'); + $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m'); + $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B'); + $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B'); + $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B'); + $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y'); + $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y'); + $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y'); + // Only for tempalte invoice + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = dol_print_date($originaldatewhen, 'dayhour'); + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date(dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency), 'dayhour'); + + //var_dump($substitutionarray);exit; $substitutionisok=true; complete_substitutions_array($substitutionarray, $outputlangs); @@ -658,7 +666,7 @@ class Facture extends CommonInvoice null, 0, $_facrec->lines[$i]->label, - null, + empty($_facrec->lines[$i]->array_options)?null:$_facrec->lines[$i]->array_options, $_facrec->lines[$i]->situation_percent, '', $_facrec->lines[$i]->fk_unit @@ -746,7 +754,7 @@ class Facture extends CommonInvoice * @param int $invertdetail Reverse sign of amounts for lines * @return int <0 if KO, >0 if OK */ - function createFromCurrent($user,$invertdetail=0) + function createFromCurrent(User $user, $invertdetail=0) { global $conf; @@ -947,11 +955,12 @@ class Facture extends CommonInvoice * Load an object from an order and create a new invoice into database * * @param Object $object Object source + * @param User $user Object user * @return int <0 if KO, 0 if nothing done, 1 if OK */ - function createFromOrder($object) + function createFromOrder($object, User $user) { - global $user,$hookmanager; + global $hookmanager; $error=0; @@ -970,6 +979,8 @@ class Facture extends CommonInvoice $line->subprice = $object->lines[$i]->subprice; $line->total_ht = $object->lines[$i]->total_ht; $line->total_tva = $object->lines[$i]->total_tva; + $line->total_localtax1 = $object->lines[$i]->total_localtax1; + $line->total_localtax2 = $object->lines[$i]->total_localtax2; $line->total_ttc = $object->lines[$i]->total_ttc; $line->vat_src_code = $object->lines[$i]->vat_src_code; $line->tva_tx = $object->lines[$i]->tva_tx; @@ -1048,18 +1059,43 @@ class Facture extends CommonInvoice } /** - * Return clicable link of object (with eventually picto) + * Return link to download file from a direct external access * - * @param int $withpicto Add picto into link - * @param string $option Where point the link - * @param int $max Maxlength of ref - * @param int $short 1=Return just URL - * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip - * @param int $addlinktonotes 1=Add link to notes - * @return string String with URL + * @param int $withpicto Add download picto into link + * @return string HTML link to file */ - function getNomUrl($withpicto=0,$option='',$max=0,$short=0,$moretitle='',$notooltip=0,$addlinktonotes=0) + function getDirectExternalLink($withpicto=0) + { + global $dolibarr_main_url_root; + + // Define $urlwithroot + $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); + $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 + + // TODO Read into ecmfile table to get entry and hash exists (PS: If not found, add it) + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile=new EcmFiles($this->db); + //$result = $ecmfile->get(); + + $hashp='todo'; + return ''.$this->ref.''; + } + + /** + * Return clicable link of object (with eventually picto) + * + * @param int $withpicto Add picto into link + * @param string $option Where point the link + * @param int $max Maxlength of ref + * @param int $short 1=Return just URL + * @param string $moretitle Add more text to title tooltip + * @param int $notooltip 1=Disable tooltip + * @param int $addlinktonotes 1=Add link to notes + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + function getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1) { global $langs, $conf, $user, $form; @@ -1072,6 +1108,14 @@ class Facture extends CommonInvoice if ($short) return $url; + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + $picto='bill'; if ($this->type == self::TYPE_REPLACEMENT) $picto.='r'; // Replacement invoice if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a'; // Credit note @@ -1088,6 +1132,10 @@ class Facture extends CommonInvoice $label.= '
    ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); if (! empty($this->total_tva)) $label.= '
    ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_tva)) + $label.= '
    ' . $langs->trans('LT1') . ': ' . price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_tva)) + $label.= '
    ' . $langs->trans('LT2') . ': ' . price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency); if (! empty($this->total_ttc)) $label.= '
    ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref; @@ -1113,9 +1161,10 @@ class Facture extends CommonInvoice $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$linkstart.($max?dol_trunc($this->ref,$max):$this->ref).$linkend; + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), $picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= ($max?dol_trunc($this->ref,$max):$this->ref); + $result .= $linkend; if ($addlinktonotes) { @@ -1158,7 +1207,7 @@ class Facture extends CommonInvoice $sql.= ', f.datec as datec'; $sql.= ', f.date_valid as datev'; $sql.= ', f.tms as datem'; - $sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf'; + $sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf, f.last_main_doc'; $sql.= ', f.fk_facture_source'; $sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet, f.extraparams'; $sql.= ', f.situation_cycle_ref, f.situation_counter, f.situation_final'; @@ -1169,8 +1218,8 @@ class Facture extends CommonInvoice $sql.= ', f.fk_incoterms, f.location_incoterms'; $sql.= ", i.libelle as libelle_incoterms"; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN (' . getEntity('c_payment_term').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement').')'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid'; $sql.= ' WHERE f.entity = '.$conf->entity; if ($rowid) $sql.= " AND f.rowid=".$rowid; @@ -1227,6 +1276,7 @@ class Facture extends CommonInvoice $this->user_author = $obj->fk_user_author; $this->user_valid = $obj->fk_user_valid; $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; $this->situation_cycle_ref = $obj->situation_cycle_ref; $this->situation_counter = $obj->situation_counter; $this->situation_final = $obj->situation_final; @@ -1541,7 +1591,7 @@ class Facture extends CommonInvoice /** - * Add a discount line into invoice using an existing absolute discount + * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) * * @param int $idremise Id of absolute discount * @return int >0 if OK, <0 if KO @@ -1607,7 +1657,7 @@ class Facture extends CommonInvoice $result=$this->update_price(1); if ($result > 0) { - // Create linke between discount and invoice line + // Create link between discount and invoice line $result=$remise->link_to_invoice($lineid,0); if ($result < 0) { @@ -1709,20 +1759,24 @@ class Facture extends CommonInvoice * @param User $user User making the deletion. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @param int $idwarehouse Id warehouse to use for stock change. - * @return int <0 if KO, >0 if OK + * @return int <0 if KO, 0=Refused, >0 if OK */ function delete($user, $notrigger=0, $idwarehouse=-1) { global $langs,$conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (empty($rowid)) $rowid=$this->id; + $rowid=$this->id; - dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); + dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".$this->thirdparty->name, LOG_DEBUG); - // TODO Test if there is at least one payment. If yes, refuse to delete. + // Test to avoid invoice deletion (allowed if draft) + $test = $this->is_erasable(); + + if ($test <= 0) return $test; $error=0; + $this->db->begin(); if (! $error && ! $notrigger) @@ -2044,7 +2098,7 @@ class Facture extends CommonInvoice * @param string $force_number Reference to force on invoice * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease) * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK + * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK */ function validate($user, $force_number='', $idwarehouse=0, $notrigger=0) { @@ -2066,7 +2120,12 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING); return 0; } - + if (count($this->lines) <= 0) + { + $langs->load("errors"); + $this->error=$langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); + return -1; + } if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer)) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) { @@ -2660,7 +2719,7 @@ class Facture extends CommonInvoice * @param double $remise_percent Pourcentage de remise de la ligne * @param int $date_start Date de debut de validite du service * @param int $date_end Date de fin de validite du service - * @param double $txtva VAT Rate + * @param double $txtva VAT Rate (Can be '8.5', '8.5 (ABC)') * @param double $txlocaltax1 Local tax 1 rate * @param double $txlocaltax2 Local tax 2 rate * @param string $price_base_type HT or TTC @@ -3134,12 +3193,13 @@ class Facture extends CommonInvoice $field2='fk_paiementfourn'; } - $sql = 'SELECT pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code'; + $sql = 'SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code'; $sql.= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t'; $sql.= ' WHERE pf.'.$field.' = '.$this->id; //$sql.= ' WHERE pf.'.$field.' = 1'; $sql.= ' AND pf.'.$field2.' = p.rowid'; $sql.= ' AND p.fk_paiement = t.id'; + $sql.= ' AND t.entity IN (' . getEntity('c_paiement').')'; if ($filtertype) $sql.=" AND t.code='PRE'"; dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG); @@ -3151,7 +3211,7 @@ class Facture extends CommonInvoice while ($i < $num) { $obj = $this->db->fetch_object($resql); - $retarray[]=array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num); + $retarray[]=array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref); $i++; } $this->db->free($resql); @@ -3186,6 +3246,8 @@ class Facture extends CommonInvoice if (! empty($conf->global->FACTURE_ADDON)) { + dol_syslog("Call getNextNumRef with FACTURE_ADDON = ".$conf->global->FACTURE_ADDON.", thirdparty=".$soc->nom.", type=".$soc->typent_code, LOG_DEBUG); + $mybool=false; $file = $conf->global->FACTURE_ADDON.".php"; @@ -3329,40 +3391,49 @@ class Facture extends CommonInvoice /** * Return if an invoice can be deleted * Rule is: - * If hidden option INVOICE_CAN_ALWAYS_BE_REMOVED is on, we can - * If invoice has a definitive ref, is last, without payment and not dipatched into accountancy -> yes end of rule * If invoice is draft and ha a temporary ref -> yes + * If hidden option INVOICE_CAN_ALWAYS_BE_REMOVED is on, we can. If hidden option INVOICE_CAN_NEVER_BE_REMOVED is on, we can't. + * If invoice has a definitive ref, is last, without payment and not dipatched into accountancy -> yes end of rule * - * @return int <0 if KO, 0=no, 1=yes + * @return int <0 if KO, 0=no, >0=yes */ function is_erasable() { global $conf; - if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) return 1; + // we check if invoice is a temporary number (PROVxxxx) + $tmppart = substr($this->ref, 1, 4); + + if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') // If draft invoice and ref not yet defined + { + return 1; + } + + if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) return 2; if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0; - // on verifie si la facture est en numerotation provisoire - $facref = substr($this->ref, 1, 4); + // TODO Test if there is at least one payment. If yes, refuse to delete. + // ... // If not a draft invoice and not temporary invoice - if ($facref != 'PROV') + if ($tmppart !== 'PROV') { + // We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag). + if (empty($this->thirdparty)) $this->fetch_thirdparty(); + $maxfacnumber = $this->getNextNumRef($this->thirdparty,'last'); $ventilExportCompta = $this->getVentilExportCompta(); + // If there is no invoice into the reset range and not already dispatched, we can delete - if ($maxfacnumber == '' && $ventilExportCompta == 0) return 1; + if ($maxfacnumber == '' && $ventilExportCompta == 0) return 3; // If invoice to delete is last one and not already dispatched, we can delete - if ($maxfacnumber == $this->ref && $ventilExportCompta == 0) return 1; + if ($maxfacnumber == $this->ref && $ventilExportCompta == 0) return 4; + if ($this->situation_cycle_ref) { $last = $this->is_last_in_cycle(); return $last; } } - else if ($this->statut == self::STATUS_DRAFT && $facref == 'PROV') // Si facture brouillon et provisoire - { - return 1; - } return 0; } @@ -3443,11 +3514,12 @@ class Facture extends CommonInvoice /** - * Renvoi liste des factures remplacables - * Statut validee ou abandonnee pour raison autre + non payee + aucun paiement + pas deja remplacee + * Return list of invoices qualified to be replaced by another invoice. + * Invoices matching the following rules are returned: + * (Status validated or abandonned for a reason 'other') + not payed + no payment at all + not already replaced * - * @param int $socid Id societe - * @return array Tableau des factures ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1) + * @param int $socid Id thirdparty + * @return array Array of invoices ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1) */ function list_replacable_invoices($socid=0) { @@ -3490,12 +3562,12 @@ class Facture extends CommonInvoice /** - * Renvoi liste des factures qualifiables pour correction par avoir - * Les factures qui respectent les regles suivantes sont retournees: - * (validee + paiement en cours) ou classee (payee completement ou payee partiellement) + pas deja remplacee + pas deja avoir + * Return list of invoices qualified to be corrected by a credit note. + * Invoices matching the following rules are returned: + * (validated + payment on process) or classified (payed completely or payed partiely) + not already replaced + not already a credit note * - * @param int $socid Id societe - * @return array Tableau des factures ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>) + * @param int $socid Id thirdparty + * @return array Array of invoices ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>) */ function list_qualified_avoir_invoices($socid=0) { @@ -3622,7 +3694,7 @@ class Facture extends CommonInvoice if (! $error) { // Force payment mode of invoice to withdraw - $payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement'); + $payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement', 'code', 'id', 1); if ($payment_mode_id > 0) { $result=$this->setPaymentMethods($payment_mode_id); @@ -3885,15 +3957,17 @@ class Facture extends CommonInvoice } $this->lines[$xnbp]=$line; - $xnbp++; $this->total_ht += $line->total_ht; $this->total_tva += $line->total_tva; $this->total_ttc += $line->total_ttc; + $this->multicurrency_total_ht += $line->multicurrency_total_ht; $this->multicurrency_total_tva += $line->multicurrency_total_tva; $this->multicurrency_total_ttc += $line->multicurrency_total_ttc; + + $xnbp++; } $this->revenuestamp = 0; @@ -4446,16 +4520,16 @@ class FactureLigne extends CommonInvoiceLine $sql.= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; $sql.= ')'; $sql.= " VALUES (".$this->fk_facture.","; - $sql.= " ".($this->fk_parent_line>0?"'".$this->fk_parent_line."'":"null").","; + $sql.= " ".($this->fk_parent_line>0 ? $this->fk_parent_line:"null").","; $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; $sql.= " '".$this->db->escape($this->desc)."',"; $sql.= " ".price2num($this->qty).","; - $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->vat_src_code."'").","; + $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").","; $sql.= " ".price2num($this->tva_tx).","; $sql.= " ".price2num($this->localtax1_tx).","; $sql.= " ".price2num($this->localtax2_tx).","; - $sql.= " '".$this->localtax1_type."',"; - $sql.= " '".$this->localtax2_type."',"; + $sql.= " '".$this->db->escape($this->localtax1_type)."',"; + $sql.= " '".$this->db->escape($this->localtax2_type)."',"; $sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").','; $sql.= " ".$this->product_type.","; $sql.= " ".price2num($this->remise_percent).","; @@ -4468,7 +4542,7 @@ class FactureLigne extends CommonInvoiceLine $sql.= ' '.$this->special_code.','; $sql.= ' '.(! empty($this->fk_fournprice)?$this->fk_fournprice:"null").','; $sql.= ' '.price2num($this->pa_ht).','; - $sql.= " '".$this->info_bits."',"; + $sql.= " '".$this->db->escape($this->info_bits)."',"; $sql.= " ".price2num($this->total_ht).","; $sql.= " ".price2num($this->total_tva).","; $sql.= " ".price2num($this->total_ttc).","; diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index 2899e3fae56..bc13b0d5876 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -85,14 +85,13 @@ class PaymentTerm // extends CommonObject if (isset($this->decalage)) $this->decalage=trim($this->decalage); - // Check parameters // Put here code to add control on parameters values // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_payment_term("; - $sql.= "rowid,"; + $sql.= "entity,"; $sql.= "code,"; $sql.= "sortorder,"; $sql.= "active,"; @@ -101,21 +100,17 @@ class PaymentTerm // extends CommonObject $sql.= "type_cdr,"; $sql.= "nbjour,"; $sql.= "decalage"; - - $sql.= ") VALUES ("; - - $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->rowid."'").","; + $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").","; + $sql.= " ".(! isset($this->entity)?getEntity('c_payment_term'):"'".$this->db->escape($this->entity)."'").","; $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; - $sql.= " ".(! isset($this->sortorder)?'NULL':"'".$this->sortorder."'").","; - $sql.= " ".(! isset($this->active)?'NULL':"'".$this->active."'").","; + $sql.= " ".(! isset($this->sortorder)?'NULL':"'".$this->db->escape($this->sortorder)."'").","; + $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'").","; $sql.= " ".(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").","; $sql.= " ".(! isset($this->libelle_facture)?'NULL':"'".$this->db->escape($this->libelle_facture)."'").","; - $sql.= " ".(! isset($this->type_cdr)?'NULL':"'".$this->type_cdr."'").","; - $sql.= " ".(! isset($this->nbjour)?'NULL':"'".$this->nbjour."'").","; - $sql.= " ".(! isset($this->decalage)?'NULL':"'".$this->decalage."'").""; - - + $sql.= " ".(! isset($this->type_cdr)?'NULL':"'".$this->db->escape($this->type_cdr)."'").","; + $sql.= " ".(! isset($this->nbjour)?'NULL':"'".$this->db->escape($this->nbjour)."'").","; + $sql.= " ".(! isset($this->decalage)?'NULL':"'".$this->db->escape($this->decalage)."'").""; $sql.= ")"; $this->db->begin(); @@ -172,6 +167,7 @@ class PaymentTerm // extends CommonObject global $langs; $sql = "SELECT"; $sql.= " t.rowid,"; + $sql.= " t.entity"; $sql.= " t.code,"; $sql.= " t.sortorder,"; @@ -185,6 +181,7 @@ class PaymentTerm // extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; $sql.= " WHERE t.rowid = ".$id; + $sql.= " AND t.entity = " . getEntity('c_payment_term'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -234,6 +231,7 @@ class PaymentTerm // extends CommonObject $sql.= " t.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; $sql.= " WHERE t.code = 'RECEP'"; + $sql.= " AND t.entity = " . getEntity('c_payment_term'); dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG); $resql=$this->db->query($sql); @@ -262,9 +260,10 @@ class PaymentTerm // extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=null, $notrigger=0) - { - global $conf, $langs; + function update($user=null, $notrigger=0) + { + global $conf, $langs; + $error=0; // Clean parameters @@ -283,9 +282,8 @@ class PaymentTerm // extends CommonObject // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."c_payment_term SET"; - + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."c_payment_term SET"; $sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").","; $sql.= " sortorder=".(isset($this->sortorder)?$this->sortorder:"null").","; $sql.= " active=".(isset($this->active)?$this->active:"null").","; @@ -294,39 +292,38 @@ class PaymentTerm // extends CommonObject $sql.= " type_cdr=".(isset($this->type_cdr)?$this->type_cdr:"null").","; $sql.= " nbjour=".(isset($this->nbjour)?$this->nbjour:"null").","; $sql.= " decalage=".(isset($this->decalage)?$this->decalage:"null").""; - - - $sql.= " WHERE rowid=".$this->id; + $sql.= " WHERE rowid = " . $this->id; + $sql.= " AND entity = " . getEntity('c_payment_term'); $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } if (! $error) { if (! $notrigger) { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action call a trigger. + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. - //// Call triggers - //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } + // Call triggers + //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + // End call triggers + } } - // Commit or rollback + // Commit or rollback if ($error) { foreach($this->errors as $errmsg) { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); } $this->db->rollback(); return -1*$error; @@ -336,7 +333,7 @@ class PaymentTerm // extends CommonObject $this->db->commit(); return 1; } - } + } /** @@ -352,7 +349,8 @@ class PaymentTerm // extends CommonObject $error=0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_payment_term"; - $sql.= " WHERE rowid=".$this->id; + $sql.= " WHERE rowid = " . $this->id; + $sql.= " AND t.entity = " . getEntity('c_payment_term'); $this->db->begin(); diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php index 93b23834e9f..5ac71ef03ca 100644 --- a/htdocs/compta/facture/contact.php +++ b/htdocs/compta/facture/contact.php @@ -139,13 +139,13 @@ if ($id > 0 || ! empty($ref)) $head = facture_prepare_head($object); $totalpaye = $object->getSommePaiement(); - + dol_fiche_head($head, 'contact', $langs->trans('InvoiceCustomer'), -1, 'bill'); // Invoice content - - $linkback = '' . $langs->trans("BackToList") . ''; - + + $linkback = '' . $langs->trans("BackToList") . ''; + $morehtmlref='
    '; // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -186,11 +186,11 @@ if ($id > 0 || ! empty($ref)) } } $morehtmlref.='
    '; - + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status - + dol_banner_tab($object, 'ref', $linkback, 1, 'facnumber', 'ref', $morehtmlref, '', 0, '', '', 1); - + dol_fiche_end(); print '
    '; diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php index 1ab0d7ceb93..fc824046a42 100644 --- a/htdocs/compta/facture/document.php +++ b/htdocs/compta/facture/document.php @@ -113,7 +113,7 @@ if ($id > 0 || ! empty($ref)) // Invoice content - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; // Ref customer diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php index 0bfdc134258..622b1bc7731 100644 --- a/htdocs/compta/facture/fiche-rec.php +++ b/htdocs/compta/facture/fiche-rec.php @@ -34,12 +34,13 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; - //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; + require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; } require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; $langs->load('bills'); $langs->load('compta'); @@ -69,13 +70,17 @@ $search_societe=GETPOST('search_societe'); $search_montant_ht=GETPOST('search_montant_ht'); $search_montant_vat=GETPOST('search_montant_vat'); $search_montant_ttc=GETPOST('search_montant_ttc'); +$search_payment_mode=GETPOST('search_payment_mode'); +$search_payment_term=GETPOST('search_payment_term'); $day=GETPOST('day'); $year=GETPOST('year'); $month=GETPOST('month'); $day_date_when=GETPOST('day_date_when'); $year_date_when=GETPOST('year_date_when'); $month_date_when=GETPOST('month_date_when'); -$search_frequency=GETPOST('search_frequency'); +$search_recurring=GETPOST('search_recurring','int'); +$search_frequency=GETPOST('search_frequency','alpha'); +$search_unit_frequency=GETPOST('search_unit_frequency','alpha'); $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -103,42 +108,20 @@ $hookmanager->initHooks(array('invoicereccard','globalcard')); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels -$extralabels = $extrafields->fetch_name_optionals_label('facture'); +$extralabels = $extrafields->fetch_name_optionals_label('facture_rec'); $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); $permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php $permissiondellink=$user->rights->facture->creer; // Used by the include of actions_dellink.inc.php $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php -$arrayfields=array( - 'f.titre'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 'f.total'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'f.tva'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>1), - 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>1), - 'f.frequency'=>array('label'=>$langs->trans("RecurringInvoiceTemplate"), 'checked'=>1), - 'f.nb_gen_done'=>array('label'=>$langs->trans("NbOfGenerationDone"), 'checked'=>1), - 'f.date_last_gen'=>array('label'=>$langs->trans("DateLastGeneration"), 'checked'=>1), - 'f.date_when'=>array('label'=>$langs->trans("NextDateToExecution"), 'checked'=>1), - 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), -); -// Extra fields -if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) -{ - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } -} - /* * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks @@ -146,500 +129,520 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if (GETPOST('cancel')) $action=''; + if (GETPOST('cancel','alpha')) $action=''; - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Set note - include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + // Set note + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - // Do we click on purge search criteria ? - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers - { - $search_ref=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $day=''; - $year=''; - $month=''; - $day_date_when=''; - $year_date_when=''; - $month_date_when=''; - $search_frequency=''; - $search_array_options=array(); - } + // Do we click on purge search criteria ? + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers + { + $search_ref=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_montant_mode=''; + $search_montant_term=''; + $day=''; + $year=''; + $month=''; + $day_date_when=''; + $year_date_when=''; + $month_date_when=''; + $search_recurring=''; + $search_frequency=''; + $search_unit_frequency=''; + $search_array_options=array(); + } - // Mass actions - /*$objectclass='MyObject'; + // Mass actions + /*$objectclass='MyObject'; $objectlabel='MyObject'; $permtoread = $user->rights->mymodule->read; $permtodelete = $user->rights->mymodule->delete; $uploaddir = $conf->mymodule->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/ - // Create predefined invoice - if ($action == 'add') - { - if (! GETPOST('titre')) - { - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Title")), null, 'errors'); - $action = "create"; - $error++; - } + // Create predefined invoice + if ($action == 'add') + { + if (! GETPOST('titre')) + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Title")), null, 'errors'); + $action = "create"; + $error++; + } - $frequency=GETPOST('frequency', 'int'); - $reyear=GETPOST('reyear'); - $remonth=GETPOST('remonth'); - $reday=GETPOST('reday'); - $rehour=GETPOST('rehour'); - $remin=GETPOST('remin'); - $nb_gen_max=GETPOST('nb_gen_max', 'int'); - //if (empty($nb_gen_max)) $nb_gen_max =0; + $frequency=GETPOST('frequency', 'int'); + $reyear=GETPOST('reyear'); + $remonth=GETPOST('remonth'); + $reday=GETPOST('reday'); + $rehour=GETPOST('rehour'); + $remin=GETPOST('remin'); + $nb_gen_max=GETPOST('nb_gen_max', 'int'); + //if (empty($nb_gen_max)) $nb_gen_max =0; - if (GETPOST('frequency')) - { - if (empty($reyear) || empty($remonth) || empty($reday)) - { - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Date")), null, 'errors'); - $action = "create"; - $error++; - } - if ($nb_gen_max === '') - { - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("MaxPeriodNumber")), null, 'errors'); - $action = "create"; - $error++; - } - } + if (GETPOST('frequency')) + { + if (empty($reyear) || empty($remonth) || empty($reday)) + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Date")), null, 'errors'); + $action = "create"; + $error++; + } + if ($nb_gen_max === '') + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("MaxPeriodNumber")), null, 'errors'); + $action = "create"; + $error++; + } + } - if (! $error) - { - $object->titre = GETPOST('titre', 'alpha'); - $object->note_private = GETPOST('note_private'); - $object->note_public = GETPOST('note_public'); - $object->usenewprice = GETPOST('usenewprice'); + if (! $error) + { + $object->titre = GETPOST('titre', 'alpha'); + $object->note_private = GETPOST('note_private','none'); + $object->note_public = GETPOST('note_public','none'); + $object->usenewprice = GETPOST('usenewprice'); - $object->frequency = $frequency; - $object->unit_frequency = GETPOST('unit_frequency', 'alpha'); - $object->nb_gen_max = $nb_gen_max; - $object->auto_validate = GETPOST('auto_validate', 'int'); + $object->frequency = $frequency; + $object->unit_frequency = GETPOST('unit_frequency', 'alpha'); + $object->nb_gen_max = $nb_gen_max; + $object->auto_validate = GETPOST('auto_validate', 'int'); - $object->fk_project = $projectid; + $object->fk_project = $projectid; - $date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear); - $object->date_when = $date_next_execution; + $date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear); + $object->date_when = $date_next_execution; - // Get first contract linked to invoice used to generate template - if ($id > 0) - { - $srcObject = new Facture($db); - $srcObject->fetch(GETPOST('facid','int')); + // Get first contract linked to invoice used to generate template + if ($id > 0) + { + $srcObject = new Facture($db); + $srcObject->fetch(GETPOST('facid','int')); - $srcObject->fetchObjectLinked(); + $srcObject->fetchObjectLinked(); - if (! empty($srcObject->linkedObjectsIds['contrat'])) - { - $contractidid = reset($srcObject->linkedObjectsIds['contrat']); + if (! empty($srcObject->linkedObjectsIds['contrat'])) + { + $contractidid = reset($srcObject->linkedObjectsIds['contrat']); - $object->origin = 'contrat'; - $object->origin_id = $contractidid; - $object->linked_objects[$object->origin] = $object->origin_id; - } - } + $object->origin = 'contrat'; + $object->origin_id = $contractidid; + $object->linked_objects[$object->origin] = $object->origin_id; + } + } - $db->begin(); + $db->begin(); - $oldinvoice = new Facture($db); - $oldinvoice->fetch($id); + $oldinvoice = new Facture($db); + $oldinvoice->fetch($id); - $result = $object->create($user, $oldinvoice->id); - if ($result > 0) - { - $result=$oldinvoice->delete($user, 1); - if ($result < 0) - { - $error++; - setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors'); - $action = "create"; - } - } - else - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; - } + $result = $object->create($user, $oldinvoice->id); + if ($result > 0) + { + $result=$oldinvoice->delete($user, 1); + if ($result < 0) + { + $error++; + setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors'); + $action = "create"; + } + } + else + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; + } - if (! $error) - { - $db->commit(); + if (! $error) + { + $db->commit(); - header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id); - exit; - } - else - { - $db->rollback(); + header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id); + exit; + } + else + { + $db->rollback(); - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; - } - } - } + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; + } + } + } - // Delete - if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) - { - $object->delete(); - header("Location: " . $_SERVER['PHP_SELF'] ); - exit; - } + // Delete + if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) + { + $object->delete($user); + header("Location: " . $_SERVER['PHP_SELF'] ); + exit; + } - // Update field - // Set condition - if ($action == 'setconditions' && $user->rights->facture->creer) - { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); + // Update field + // Set condition + if ($action == 'setconditions' && $user->rights->facture->creer) + { + $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); - } - // Set mode - elseif ($action == 'setmode' && $user->rights->facture->creer) - { - $result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - } - // Set project - elseif ($action == 'classin' && $user->rights->facture->creer) - { - $object->setProject(GETPOST('projectid', 'int')); - } - // Set bank account - elseif ($action == 'setref' && $user->rights->facture->creer) - { - //var_dump(GETPOST('ref', 'alpha'));exit; - $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY'); - if ($result > 0) - { - $object->titre = GETPOST('ref', 'alpha'); - $object->ref = $object->titre; - } - else dol_print_error($db, $object->error, $object->errors); - } - // Set bank account - elseif ($action == 'setbankaccount' && $user->rights->facture->creer) - { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); - } - // Set frequency and unit frequency - elseif ($action == 'setfrequency' && $user->rights->facture->creer) - { - $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha')); - } - // Set next date of execution - elseif ($action == 'setdate_when' && $user->rights->facture->creer) - { - $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear')); - if (!empty($date)) $object->setNextDate($date); - } - // Set max period - elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) - { - $object->setMaxPeriod(GETPOST('nb_gen_max', 'int')); - } - // Set auto validate - elseif ($action == 'setauto_validate' && $user->rights->facture->creer) - { - $object->setAutoValidate(GETPOST('auto_validate', 'int')); - } + } + // Set mode + elseif ($action == 'setmode' && $user->rights->facture->creer) + { + $result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + } + // Set project + elseif ($action == 'classin' && $user->rights->facture->creer) + { + $object->setProject(GETPOST('projectid', 'int')); + } + // Set bank account + elseif ($action == 'setref' && $user->rights->facture->creer) + { + //var_dump(GETPOST('ref', 'alpha'));exit; + $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY'); + if ($result > 0) + { + $object->titre = GETPOST('ref', 'alpha'); + $object->ref = $object->titre; + } + else dol_print_error($db, $object->error, $object->errors); + } + // Set bank account + elseif ($action == 'setbankaccount' && $user->rights->facture->creer) + { + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + } + // Set frequency and unit frequency + elseif ($action == 'setfrequency' && $user->rights->facture->creer) + { + $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha')); + } + // Set next date of execution + elseif ($action == 'setdate_when' && $user->rights->facture->creer) + { + $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear')); + if (!empty($date)) $object->setNextDate($date); + } + // Set max period + elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) + { + $object->setMaxPeriod(GETPOST('nb_gen_max', 'int')); + } + // Set auto validate + elseif ($action == 'setauto_validate' && $user->rights->facture->creer) + { + $object->setAutoValidate(GETPOST('auto_validate', 'int')); + } - // Delete line - if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) - { - $object->fetch($id); - $object->fetch_thirdparty(); + // Delete line + if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) + { + $object->fetch($id); + $object->fetch_thirdparty(); - $db->begin(); + $db->begin(); - $line=new FactureLigneRec($db); + $line=new FactureLigneRec($db); - // For triggers - $line->id = $lineid; + // For triggers + $line->id = $lineid; - if ($line->delete() > 0) - { - $result=$object->update_price(1); + if ($line->delete($user) > 0) + { + $result=$object->update_price(1); - if ($result > 0) - { - $db->commit(); - $object->fetch($object->id); // Reload lines - } - else - { - $db->rollback(); - setEventMessages($db->lasterror(), null, 'errors'); - } - } - else - { - $db->rollback(); - setEventMessages($line->error, $line->errors, 'errors'); - } - } + if ($result > 0) + { + $db->commit(); + $object->fetch($object->id); // Reload lines + } + else + { + $db->rollback(); + setEventMessages($db->lasterror(), null, 'errors'); + } + } + else + { + $db->rollback(); + setEventMessages($line->error, $line->errors, 'errors'); + } + } + else if ($action == 'update_extras') + { + // Fill array 'array_options' with data from update form + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); + if ($ret < 0) $error++; - // Add a new line - if ($action == 'addline' && $user->rights->facture->creer) - { - $langs->load('errors'); - $error = 0; + if (! $error) { + $result = $object->insertExtraFields(); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } + } - // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); - $price_ht = GETPOST('price_ht'); - if (GETPOST('prod_entry_mode') == 'free') - { - $idprod=0; - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - } - else - { - $idprod=GETPOST('idprod', 'int'); - $tva_tx = ''; - } + // Add a new line + if ($action == 'addline' && $user->rights->facture->creer) + { + $langs->load('errors'); + $error = 0; - $qty = GETPOST('qty' . $predef); - $remise_percent = GETPOST('remise_percent' . $predef); + // Set if we used free entry or predefined product + $predef=''; + $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $price_ht = GETPOST('price_ht'); + if (GETPOST('prod_entry_mode') == 'free') + { + $idprod=0; + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + } + else + { + $idprod=GETPOST('idprod', 'int'); + $tva_tx = ''; + } - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - // Unset extrafield - if (is_array($extralabelsline)) - { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key . $predef]); - } - } + $qty = GETPOST('qty' . $predef); + $remise_percent = GETPOST('remise_percent' . $predef); - if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) { - setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error ++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); - $error ++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not '' - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); - $error ++; - } - if ($qty == '') { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error ++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); - $error ++; - } - if ($qty < 0) { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); - $error ++; - } + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) + { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key . $predef]); + } + } - if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) - { - $ret = $object->fetch($id); - if ($ret < 0) { - dol_print_error($db, $object->error); - exit(); - } - $ret = $object->fetch_thirdparty(); + if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) { + setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error ++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); + $error ++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not '' + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); + $error ++; + } + if ($qty == '') { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error ++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); + $error ++; + } + if ($qty < 0) { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); + $error ++; + } - // Clean parameters - $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); - $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); - $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT'); + if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) + { + $ret = $object->fetch($id); + if ($ret < 0) { + dol_print_error($db, $object->error); + exit(); + } + $ret = $object->fetch_thirdparty(); - // Define special_code for special lines - $special_code = 0; - // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices + // Clean parameters + $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); + $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); + $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT'); - // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $tva_tx par celui du produit - // Ecrase $base_price_type par celui du produit - // Replaces $fk_unit with the product's - if (! empty($idprod)) - { - $prod = new Product($db); - $prod->fetch($idprod); + // Define special_code for special lines + $special_code = 0; + // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices - $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); + // Ecrase $pu par celui du produit + // Ecrase $desc par celui du produit + // Ecrase $tva_tx par celui du produit + // Ecrase $base_price_type par celui du produit + // Replaces $fk_unit with the product's + if (! empty($idprod)) + { + $prod = new Product($db); + $prod->fetch($idprod); - // Update if prices fields are defined - $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); - $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr=0; + $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; + // Update if prices fields are defined + $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); + $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); + if (empty($tva_tx)) $tva_npr=0; - // We define price for product - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) - { - $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; - $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; - $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; - $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility - { - if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; - if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; - if (empty($tva_tx)) $tva_npr=0; - } - } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) - { - require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; + $pu_ht = $prod->price; + $pu_ttc = $prod->price_ttc; + $price_min = $prod->price_min; + $price_base_type = $prod->price_base_type; - $prodcustprice = new Productcustomerprice($db); + // We define price for product + if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + { + $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; + $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; + $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; + $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; + if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility + { + if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; + if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; + if (empty($tva_tx)) $tva_npr=0; + } + } + elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) + { + require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; - $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); + $prodcustprice = new Productcustomerprice($db); - $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); - if ($result) - { - if (count($prodcustprice->lines) > 0) - { - $pu_ht = price($prodcustprice->lines[0]->price); - $pu_ttc = price($prodcustprice->lines[0]->price_ttc); - $price_base_type = $prodcustprice->lines[0]->price_base_type; - $tva_tx = $prodcustprice->lines[0]->tva_tx; - } - } - } + $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); + + $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); + if ($result) + { + if (count($prodcustprice->lines) > 0) + { + $pu_ht = price($prodcustprice->lines[0]->price); + $pu_ttc = price($prodcustprice->lines[0]->price_ttc); + $price_base_type = $prodcustprice->lines[0]->price_base_type; + $tva_tx = $prodcustprice->lines[0]->tva_tx; + } + } + } $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx)); $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); - // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? - if (! empty($price_ht)) - { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); - } - // On reevalue prix selon taux tva car taux tva transaction peut etre different - // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - elseif ($tmpvat != $tmpprodvat) - { - if ($price_base_type != 'HT') - { - $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); - } - else - { - $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); - } - } + // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? + if (! empty($price_ht)) + { + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); + } + // On reevalue prix selon taux tva car taux tva transaction peut etre different + // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). + elseif ($tmpvat != $tmpprodvat) + { + if ($price_base_type != 'HT') + { + $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); + } + else + { + $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); + } + } - $desc = ''; + $desc = ''; - // Define output language - if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { - $outputlangs = $langs; - $newlang = ''; - if (empty($newlang) && GETPOST('lang_id','aZ09')) - $newlang = GETPOST('lang_id','aZ09'); - if (empty($newlang)) - $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } + // Define output language + if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) + { + $outputlangs = $langs; + $newlang = ''; + if (empty($newlang) && GETPOST('lang_id','aZ09')) + $newlang = GETPOST('lang_id','aZ09'); + if (empty($newlang)) + $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) + { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } - $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description; - } - else - { - $desc = $prod->description; - } + $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description; + } + else + { + $desc = $prod->description; + } - $desc = dol_concatdesc($desc, $product_desc); + $desc = dol_concatdesc($desc, $product_desc); - // Add custom code and origin country into description - if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) - { - $tmptxt = '('; - if (! empty($prod->customcode)) - $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) - $tmptxt .= ' - '; - if (! empty($prod->country_code)) - $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); - $tmptxt .= ')'; - $desc = dol_concatdesc($desc, $tmptxt); + // Add custom code and origin country into description + if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) + { + $tmptxt = '('; + if (! empty($prod->customcode)) + $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; + if (! empty($prod->customcode) && ! empty($prod->country_code)) + $tmptxt .= ' - '; + if (! empty($prod->country_code)) + $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); + $tmptxt .= ')'; + $desc = dol_concatdesc($desc, $tmptxt); - } + } - $type = $prod->type; - $fk_unit = $prod->fk_unit; + $type = $prod->type; + $fk_unit = $prod->fk_unit; - } - else - { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); - $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); - $tva_tx = str_replace('*', '', $tva_tx); - if (empty($tva_tx)) $tva_npr=0; - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - $desc = $product_desc; - $type = GETPOST('type'); - $fk_unit= GETPOST('units', 'alpha'); - } + } + else + { + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); + $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); + $tva_tx = str_replace('*', '', $tva_tx); + if (empty($tva_tx)) $tva_npr=0; + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + $desc = $product_desc; + $type = GETPOST('type'); + $fk_unit= GETPOST('units', 'alpha'); + } - // Margin - $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); - $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value + // Margin + $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); + $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value - // Local Taxes - $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr); - $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr); + // Local Taxes + $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr); + $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr); - $info_bits = 0; - if ($tva_npr) - $info_bits |= 0x01; + $info_bits = 0; + if ($tva_npr) + $info_bits |= 0x01; - if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))) - { - $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); - setEventMessages($mesg, null, 'errors'); - } - else - { - // Insert line - $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit); + if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))) + { + $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); + setEventMessages($mesg, null, 'errors'); + } + else + { + // Insert line + $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit); - if ($result > 0) - { - /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + if ($result > 0) + { + /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; @@ -656,102 +659,114 @@ if (empty($reshook)) $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); }*/ - $object->fetch($object->id); // Reload lines + $object->fetch($object->id); // Reload lines - unset($_POST['prod_entry_mode']); + unset($_POST['prod_entry_mode']); - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['remise_percent']); - unset($_POST['price_ht']); - unset($_POST['multicurrency_price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['product_ref']); - unset($_POST['product_label']); - unset($_POST['product_desc']); - unset($_POST['fournprice']); - unset($_POST['buying_price']); - unset($_POST['np_marginRate']); - unset($_POST['np_markRate']); - unset($_POST['dp_desc']); - unset($_POST['idprod']); - unset($_POST['units']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['multicurrency_price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); + unset($_POST['dp_desc']); + unset($_POST['idprod']); + unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); - unset($_POST['situations']); - unset($_POST['progress']); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + unset($_POST['situations']); + unset($_POST['progress']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } - $action = ''; - } - } - } + $action = ''; + } + } + } - elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel')) - { - if (! $object->fetch($id) > 0) dol_print_error($db); - $object->fetch_thirdparty(); + elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel','alpha')) + { + if (! $object->fetch($id) > 0) dol_print_error($db); + $object->fetch_thirdparty(); - // Clean parameters - $date_start = ''; - $date_end = ''; - //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - $description = dol_htmlcleanlastbr(GETPOST('product_desc') ? GETPOST('product_desc') : GETPOST('desc')); - $pu_ht = GETPOST('price_ht'); - $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - $qty = GETPOST('qty'); + // Clean parameters + $date_start = ''; + $date_end = ''; + //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + $description = dol_htmlcleanlastbr(GETPOST('product_desc','none') ? GETPOST('product_desc','none') : GETPOST('desc','none')); + $pu_ht = GETPOST('price_ht'); + $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + $qty = GETPOST('qty'); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) - $info_bits |= 0x01; + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $vat_rate)) + $info_bits |= 0x01; - // Define vat_rate - $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty); - $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty); + // Define vat_rate + $vat_rate = str_replace('*', '', $vat_rate); + $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty); + $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty); - // Add buying price - $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); - $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value + // Add buying price + $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); + $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); - // Unset extrafield - if (is_array($extralabelsline)) - { - // Get extra fields - foreach ($extralabelsline as $key => $value) - { - unset($_POST["options_" . $key]); - } - } + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); - // Define special_code for special lines - $special_code=GETPOST('special_code'); - if (! GETPOST('qty')) $special_code=3; + $objectline = new FactureLigneRec($db); + if ($objectline->fetch(GETPOST('lineid'))) + { + $objectline->array_options=$array_options; + $result=$objectline->insertExtraFields(); + if ($result < 0) + { + setEventMessages($langs->trans('Error').$result, null, 'errors'); + } + } - /*$line = new FactureLigne($db); + // Unset extrafield + if (is_array($extralabelsline)) + { + // Get extra fields + foreach ($extralabelsline as $key => $value) + { + unset($_POST["options_" . $key]); + } + } + + // Define special_code for special lines + $special_code=GETPOST('special_code'); + if (! GETPOST('qty')) $special_code=3; + + /*$line = new FactureLigne($db); $line->fetch(GETPOST('lineid')); $percent = $line->get_prev_progress($object->id); @@ -763,69 +778,69 @@ if (empty($reshook)) $result = -1; }*/ - // Check minimum price - $productid = GETPOST('productid', 'int'); - if (! empty($productid)) - { - $product = new Product($db); - $product->fetch($productid); + // Check minimum price + $productid = GETPOST('productid', 'int'); + if (! empty($productid)) + { + $product = new Product($db); + $product->fetch($productid); - $type = $product->type; + $type = $product->type; - $price_min = $product->price_min; - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) - $price_min = $product->multiprices_min [$object->thirdparty->price_level]; + $price_min = $product->price_min; + if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + $price_min = $product->multiprices_min [$object->thirdparty->price_level]; - $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); + $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); - // Check price is not lower than minimum (check is done only for standard or replacement invoices) - if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))) { - setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); - $error ++; - } - } else { - $type = GETPOST('type'); - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + // Check price is not lower than minimum (check is done only for standard or replacement invoices) + if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))) { + setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); + $error ++; + } + } else { + $type = GETPOST('type'); + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - // Check parameters - if (GETPOST('type') < 0) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error ++; - } - } - if ($qty < 0) { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); - $error ++; - } + // Check parameters + if (GETPOST('type') < 0) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $error ++; + } + } + if ($qty < 0) { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); + $error ++; + } - // Update line - if (! $error) - { - $result = $object->updateline( - GETPOST('lineid'), - $description, - $pu_ht, - $qty, - $vat_rate, - $localtax1_rate, - $localtax1_rate, - GETPOST('productid'), - GETPOST('remise_percent'), - 'HT', - $info_bits, - 0, - 0, - $type, - 0, - $special_code, - $label, - GETPOST('units') - ); + // Update line + if (! $error) + { + $result = $object->updateline( + GETPOST('lineid'), + $description, + $pu_ht, + $qty, + $vat_rate, + $localtax1_rate, + $localtax1_rate, + GETPOST('productid'), + GETPOST('remise_percent'), + 'HT', + $info_bits, + 0, + 0, + $type, + 0, + $special_code, + $label, + GETPOST('units') + ); - if ($result >= 0) - { - /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + if ($result >= 0) + { + /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; $newlang = ''; @@ -842,50 +857,50 @@ if (empty($reshook)) $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); }*/ - $object->fetch($object->id); // Reload lines + $object->fetch($object->id); // Reload lines - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['productid']); - unset($_POST['remise_percent']); - unset($_POST['price_ht']); - unset($_POST['multicurrency_price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['product_ref']); - unset($_POST['product_label']); - unset($_POST['product_desc']); - unset($_POST['fournprice']); - unset($_POST['buying_price']); - unset($_POST['np_marginRate']); - unset($_POST['np_markRate']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['productid']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['multicurrency_price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); - unset($_POST['dp_desc']); - unset($_POST['idprod']); - unset($_POST['units']); + unset($_POST['dp_desc']); + unset($_POST['idprod']); + unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); - unset($_POST['situations']); - unset($_POST['progress']); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - } + unset($_POST['situations']); + unset($_POST['progress']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } } @@ -899,6 +914,7 @@ $form = new Form($db); $formother = new FormOther($db); if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } $companystatic = new Societe($db); +$invoicerectmp = new FactureRec($db); $now = dol_now(); $tmparray=dol_getdate($now); @@ -943,29 +959,29 @@ if ($action == 'create') print ''.$langs->trans("Customer").''.$object->thirdparty->getNomUrl(1,'customer').''; print ''; - $note_public=GETPOST('note_public')?GETPOST('note_public'):$object->note_public; - $note_private=GETPOST('note_private')?GETPOST('note_private'):$object->note_private; + $note_public=GETPOST('note_public','none')?GETPOST('note_public','none'):$object->note_public; + $note_private=GETPOST('note_private','none')?GETPOST('note_private','none'):$object->note_private; // Help of substitution key - $substitutionarray=array( - '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($object->total_ht).')', - '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($object->total_ttc).')', - '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%m').')', - '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%m').')', - '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'),'%m').')', - '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%B').')', - '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%B').')', - '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B').')', - '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'y'),'%Y').')', - '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%Y').')', - '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'y'),'%Y').')' - ); - $substitutionarray['__(TransKey)__']=$langs->trans("TransKey"); + $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object); + + $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%m').')'; + $substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%m').')'; + $substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'),'%m').')'; + $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%B').')'; + $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%B').')'; + $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B').')'; + $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'y'),'%Y').')'; + $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%Y').')'; + $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'y'),'%Y').')'; + // Only on template invoices + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date($object->date_when, 'dayhour').')'; + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date_when, $object->frequency, $object->unit_frequency),'dayhour').')'; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
    '; foreach($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
    '; + $htmltext.=$key.' = '.$langs->trans($val).'
    '; } $htmltext.='
    '; @@ -976,20 +992,20 @@ if ($action == 'create') print ''; print ''; $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); + print $doleditor->Create(1); // Private note if (empty($user->societe_id)) { - print ''; - print ''; - print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'); - print ''; - print ''; - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - // print ' - print ''; + print ''; + print ''; + print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'); + print ''; + print ''; + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + // print ' + print ''; } // Author @@ -1002,7 +1018,7 @@ if ($action == 'create') // Payment mode print "".$langs->trans("PaymentMode").""; - $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none', '', 1); print ""; // Project @@ -1019,7 +1035,7 @@ if ($action == 'create') // Bank account if ($object->fk_account > 0) { - print "".$langs->trans('RIB').""; + print "".$langs->trans('BankAccount').""; $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); print ""; } @@ -1037,7 +1053,7 @@ if ($action == 'create') print ''; - // Frequency + // Frequency + unit print '"; @@ -1061,7 +1077,7 @@ if ($action == 'create') print "
    '.$form->textwithpicto($langs->trans("Frequency"), $langs->transnoentitiesnoconv('toolTipFrequency')).""; print " ".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), (GETPOST('unit_frequency')?GETPOST('unit_frequency'):'m')); print "
    "; - dol_fiche_end(); + dol_fiche_end(); $title = $langs->trans("ProductsAndServices"); @@ -1075,17 +1091,19 @@ if ($action == 'create') /* * Invoice lines */ + print '
    '; print ''; // Show object lines if (! empty($object->lines)) { - $disableedit=1; - $disablemove=1; - $disableremove=1; - $ret = $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice + $disableedit=1; + $disablemove=1; + $disableremove=1; + $ret = $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } print "
    \n"; + print '
    '; print ''; @@ -1101,9 +1119,9 @@ if ($action == 'create') print "\n"; print '
    '; - print '     '; - print ''; - print '
    '; + print '     '; + print ''; + print '
    '; print "\n"; } else @@ -1141,59 +1159,59 @@ else // Recurring invoice content - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref=''; if ($action != 'editref') $morehtmlref.=$form->editfieldkey($object->ref, 'ref', $object->ref, $object, $user->rights->facture->creer, '', '', 0, 2); else $morehtmlref.= $form->editfieldval('', 'ref', $object->ref, $object, $user->rights->facture->creer, 'string'); - $morehtmlref.='
    '; - // Ref customer - //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1); - //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
    '; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
    '; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - } - $morehtmlref.='
    '; + $morehtmlref.='
    '; + // Ref customer + //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1); + //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->facture->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
    '; - dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright); + dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright); - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; print '"; @@ -1266,25 +1284,26 @@ else // Help of substitution key $dateexample=dol_now(); if (! empty($object->frequency) && ! empty($object->date_when)) $dateexample=$object->date_when; - $substitutionarray=array( - '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($object->total_ht).')', - '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($object->total_ttc).')', - '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')', - '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')', - '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')', - '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')', - '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')', - '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')', - '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')', - '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')', - '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')' - ); - $substitutionarray['__(TransKey)__']=$langs->trans("TransKey"); + + $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object); + + $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')'; + $substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')'; + $substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')'; + $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')'; + $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')'; + $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')'; + $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')'; + $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')'; + $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')'; + // Only on template invoices + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date($object->date_when, 'dayhour').')'; + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date_when, $object->frequency, $object->unit_frequency),'dayhour').')'; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
    '; foreach($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
    '; + $htmltext.=$key.' = '.$langs->trans($val).'
    '; } $htmltext.='
    '; @@ -1312,26 +1331,31 @@ else print $langs->trans('RIB'); print ''; + print ''; print '
    '.$langs->trans("Author").''.$author->getFullName($langs)."
    '; if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon)) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; print ''; if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); } print ""; print ''; - print ''; - print '
    '; - print '
    '; - print '
    '; - print '
    '; + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print ''; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; /* @@ -1367,13 +1391,13 @@ else } else { - if ($object->frequency > 0) - { - print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency); - } - else - { - print $langs->trans("NotARecurringInvoiceTemplate"); + if ($object->frequency > 0) + { + print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency); + } + else + { + print $langs->trans("NotARecurringInvoiceTemplate"); } } print ''; @@ -1382,16 +1406,16 @@ else print ''; if ($action == 'date_when' || $object->frequency > 0) { - print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day'); + print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day'); } else { - print $langs->trans("NextDateToExecution"); + print $langs->trans("NextDateToExecution"); } print ''; if ($action == 'date_when' || $object->frequency > 0) { - print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day'); + print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached'); } print ''; print ''; @@ -1400,20 +1424,20 @@ else print ''; if ($action == 'nb_gen_max' || $object->frequency > 0) { - print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer); + print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer); } else { - print $langs->trans("MaxPeriodNumber"); + print $langs->trans("MaxPeriodNumber"); } print ''; if ($action == 'nb_gen_max' || $object->frequency > 0) { - print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max?$object->nb_gen_max:'', $object, $user->rights->facture->creer); + print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max?$object->nb_gen_max:'', $object, $user->rights->facture->creer); } else { - print ''; + print ''; } print ''; print ''; @@ -1421,51 +1445,51 @@ else // Status of generated invoices print ''; if ($action == 'auto_validate' || $object->frequency > 0) - print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer); + print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer); else - print $langs->trans("StatusOfGeneratedInvoices"); + print $langs->trans("StatusOfGeneratedInvoices"); print ''; - $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated'); + $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated'); if ($action == 'auto_validate' || $object->frequency > 0) { - print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select); + print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select); } print ''; print ''; print ''; - // Frequencry/Recurring section - if ($object->frequency > 0) - { - print '
    '; + // Frequencry/Recurring section + if ($object->frequency > 0) + { + print '
    '; - if (empty($conf->cron->enabled)) - { - print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"))); - } + if (empty($conf->cron->enabled)) + { + print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"))); + } - print '
    '; - print ''; + print '
    '; + print '
    '; - // Nb of generation already done - print ''; - print ''; - print ''; + // Nb of generation already done + print ''; + print ''; + print ''; - // Date last - print ''; - print ''; + // Date last + print ''; + print ''; - print '
    '.$langs->trans("NbOfGenerationDone").''; - print $object->nb_gen_done?$object->nb_gen_done:'0'; - print '
    '.$langs->trans("NbOfGenerationDone").''; + print $object->nb_gen_done?$object->nb_gen_done:'0'; + print '
    '; - print $langs->trans("DateLastGeneration"); - print ''; - print dol_print_date($object->date_last_gen, 'dayhour'); - print '
    '; + print $langs->trans("DateLastGeneration"); + print ''; + print dol_print_date($object->date_last_gen, 'dayhour'); + print '
    '; + print ''; - print '
    '; + print '
    '; } print '
    '; @@ -1484,34 +1508,34 @@ else '; if (! empty($conf->use_javascript_ajax) && $object->statut == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } + print '
    '; print ''; // Show object lines if (! empty($object->lines)) { - //$disableedit=1; - //$disablemove=1; - $ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice + //$disableedit=1; + //$disablemove=1; + $ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } // Form to add new line if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline') { - if ($action != 'editline') - { - $var = true; + if ($action != 'editline') + { + // Add free products/services + $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice - // Add free products/services - $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice - - $parameters = array(); - $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - } + $parameters = array(); + $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + } } print "
    \n"; + print '
    '; print "\n"; @@ -1540,13 +1564,13 @@ else else { print ''; - } - } + } + } } else { print ''; - } + } //} //if ($object->statut == Facture::STATUS_DRAFT && $user->rights->facture->supprimer) @@ -1564,372 +1588,14 @@ else // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice')); + $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
    '; + print '
    '; } - else - { - /* - * List mode - */ - $sql = "SELECT s.nom as name, s.rowid as socid, f.rowid as facid, f.titre, f.total, f.tva as total_vat, f.total_ttc, f.frequency,"; - $sql.= " f.nb_gen_done, f.nb_gen_max, f.date_last_gen, f.date_when,"; - $sql.= " f.datec, f.tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f"; - if (! $user->rights->societe->client->voir && ! $socid) { - $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - } - $sql.= " WHERE f.fk_soc = s.rowid"; - $sql.= " AND f.entity = ".$conf->entity; - if (! $user->rights->societe->client->voir && ! $socid) { - $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - } - if ($search_ref) $sql .= natural_search('f.titre', $search_ref); - if ($search_societe) $sql .= natural_search('s.nom', $search_societe); - if ($search_montant_ht != '') $sql.= natural_search('f.total', $search_montant_ht, 1); - if ($search_montant_vat != '') $sql.= natural_search('f.tva', $search_montant_vat, 1); - if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1); - if ($search_frequency > 0) $sql.= natural_search('f.frequency', $search_frequency); - if ($search_frequency == '1') $sql.= ' AND f.frequency > 0'; - if ($search_frequency == '0') $sql.= ' AND (f.frequency IS NULL or f.frequency = 0)'; - - if ($month > 0) - { - if ($year > 0 && empty($day)) - $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(f.date_last_gen, '%m') = '".$month."'"; - } - else if ($year > 0) - { - $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; - } - if ($month_date_when > 0) - { - if ($year_date_when > 0 && empty($day_date_when)) - $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,$month_date_when,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,$month_date_when,false))."'"; - else if ($year_date_when > 0 && ! empty($day_date_when)) - $sql.= " AND f.date_date_when_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date_when, $day_date_when, $year_date_when))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date_when, $day_date_when, $year_date_when))."'"; - else - $sql.= " AND date_format(f.date_when, '%m') = '".$month_date_when."'"; - } - else if ($year_date_when > 0) - { - $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,1,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,12,false))."'"; - } - - $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - } - - $sql.= $db->order($sortfield, $sortorder); - $sql.= $db->plimit($limit+1,$offset); - - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($socid) $param.='&socid='.$socid; - if ($day) $param.='&day='.$day; - if ($month) $param.='&month='.$month; - if ($year) $param.='&year=' .$year; - if ($day_date_when) $param.='&day_date_when='.$day_date_when; - if ($month_date_when) $param.='&month_date_when='.$month_date_when; - if ($year_date_when) $param.='&year_date_when=' .$year_date_when; - if ($search_ref) $param.='&search_ref=' .$search_ref; - if ($search_societe) $param.='&search_societe=' .$search_societe; - if ($search_montant_ht != '') $param.='&search_montant_ht='.$search_montant_ht; - if ($search_montant_vat != '') $param.='&search_montant_vat='.$search_montant_vat; - if ($search_montant_ttc != '') $param.='&search_montant_ttc='.$search_montant_ttc; - if ($search_frequency > 0) $param.='&search_frequency=' .$search_frequency; - if ($option) $param.="&option=".$option; - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - $massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); - - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - //$selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - - print '
    '."\n"; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($langs->trans("RepeatableInvoices"),$page,$_SERVER['PHP_SELF'],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords,'title_accountancy.png',0,'','',$limit); - - print $langs->trans("ToCreateAPredefinedInvoice", $langs->transnoentitiesnoconv("ChangeIntoRepeatableInvoice")).'

    '; - - $i = 0; - - print '
    '; - print ''."\n"; - - // Filters lines - print ''; - // Ref - if (! empty($arrayfields['f.titre']['checked'])) - { - print ''; - } - // Thirpdarty - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - if (! empty($arrayfields['f.total']['checked'])) - { - // Amount - print ''; - } - if (! empty($arrayfields['f.tva']['checked'])) - { - // Amount - print ''; - } - if (! empty($arrayfields['f.total_ttc']['checked'])) - { - // Amount - print ''; - } - if (! empty($arrayfields['f.frequency']['checked'])) - { - // Recurring or not - print ''; - } - if (! empty($arrayfields['f.nb_gen_done']['checked'])) - { - // Nb generation - print ''; - } - // Date invoice - if (! empty($arrayfields['f.date_last_gen']['checked'])) - { - print ''; - } - // Date due - if (! empty($arrayfields['f.date_when']['checked'])) - { - print ''; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['f.datec']['checked'])) - { - print ''; - } - // Date modification - if (! empty($arrayfields['f.tms']['checked'])) - { - print ''; - } - // Action column - print ''; - print "\n"; - - - print ''; - if (! empty($arrayfields['f.titre']['checked'])) print_liste_field_titre($arrayfields['f.titre']['label'],$_SERVER['PHP_SELF'],"f.titre","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER['PHP_SELF'],"s.nom","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['f.total']['checked'])) print_liste_field_titre($arrayfields['f.total']['label'],$_SERVER['PHP_SELF'],"f.total","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.tva']['checked'])) print_liste_field_titre($arrayfields['f.tva']['label'],$_SERVER['PHP_SELF'],"f.tva","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],"f.total_ttc","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.frequency']['checked'])) print_liste_field_titre($arrayfields['f.frequency']['label'],$_SERVER['PHP_SELF'],"f.frequency","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.nb_gen_done']['checked'])) print_liste_field_titre($arrayfields['f.nb_gen_done']['label'],$_SERVER['PHP_SELF'],"f.nb_gen_done","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.date_last_gen']['checked'])) print_liste_field_titre($arrayfields['f.date_last_gen']['label'],$_SERVER['PHP_SELF'],"f.date_last_gen","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.date_when']['checked'])) print_liste_field_titre($arrayfields['f.date_when']['label'],$_SERVER['PHP_SELF'],"f.date_when","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER['PHP_SELF'],"f.date_when","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER['PHP_SELF'],"f.date_when","",$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; - print "\n"; - - - if ($num > 0) - { - $var=true; - while ($i < min($num,$limit)) - { - $objp = $db->fetch_object($resql); - - $companystatic->id=$objp->socid; - $companystatic->name=$objp->name; - - print ''; - - if (! empty($arrayfields['f.titre']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - if (! empty($arrayfields['f.total']['checked'])) - { - print ''."\n"; - } - if (! empty($arrayfields['f.tva']['checked'])) - { - print ''."\n"; - } - if (! empty($arrayfields['f.total_ttc']['checked'])) - { - print ''."\n"; - } - if (! empty($arrayfields['f.frequency']['checked'])) - { - print ''; - } - if (! empty($arrayfields['f.nb_gen_done']['checked'])) - { - print ''; - } - if (! empty($arrayfields['f.date_last_gen']['checked'])) - { - print ''; - } - if (! empty($arrayfields['f.date_when']['checked'])) - { - print ''; - } - if (! empty($arrayfields['f.datec']['checked'])) - { - print ''; - } - if (! empty($arrayfields['f.tms']['checked'])) - { - print ''; - } - // Action column - print '"; - print "\n"; - $i++; - } - } - else - { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } - print ''; - } - - print "
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print $form->selectyesno('search_frequency', $search_frequency, 1, false, 1); - print ''; - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year_date_when?$year_date_when:-1,'year_date_when',1, 20, 5); - 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 ''; - $searchpicto=$form->showFilterAndCheckAddButtons(0, 'checkforselect', 1); - print $searchpicto; - print '
    '.img_object($langs->trans("ShowBill"),"bill").' '.$objp->titre; - print "'.$companystatic->getNomUrl(1,'customer').''.price($objp->total).''.price($objp->total_vat).''.price($objp->total_ttc).''.yn($objp->frequency?1:0).''; - print ($objp->frequency ? $objp->nb_gen_done.($objp->nb_gen_max>0?' / '. $objp->nb_gen_max:'') : ''.$langs->trans('NA').''); - print ''; - print ($objp->frequency ? dol_print_date($db->jdate($objp->date_last_gen),'day') : ''.$langs->trans('NA').''); - print ''; - print ($objp->frequency ? dol_print_date($db->jdate($objp->date_when),'day') : ''.$langs->trans('NA').''); - print ''; - print dol_print_date($db->jdate($objp->datec),'dayhour'); - print ''; - print dol_print_date($db->jdate($objp->tms),'dayhour'); - print ''; - if ($user->rights->facture->creer) - { - if (empty($objp->frequency) || $db->jdate($objp->date_when) <= $today) - { - print ''; - print $langs->trans("CreateBill").''; - } - else - { - print $langs->trans("DateIsNotEnough"); - } - } - else - { - print " "; - } - print "
    '.$langs->trans("NoRecordFound").'
    "; - print "
    "; - print "
    "; - - $db->free($resql); - } - else - { - dol_print_error($db); - } - } - } llxFooter(); diff --git a/htdocs/compta/facture/info.php b/htdocs/compta/facture/info.php index fd43cc42982..49e5e77e7be 100644 --- a/htdocs/compta/facture/info.php +++ b/htdocs/compta/facture/info.php @@ -58,7 +58,7 @@ $totalpaye = $object->getSommePaiement(); // Invoice content -$linkback = '' . $langs->trans("BackToList") . ''; +$linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; // Ref customer diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php new file mode 100644 index 00000000000..b1b95b99f7b --- /dev/null +++ b/htdocs/compta/facture/invoicetemplate_list.php @@ -0,0 +1,702 @@ + + * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2013 Florian Henry + * Copyright (C) 2013 Juanjo Menent + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2012 Cedric Salvador + * Copyright (C) 2015 Alexandre Spangaro + * Copyright (C) 2016 Meziane Sof + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/compta/facture/invoicetemplate_list.php + * \ingroup facture + * \brief Page to show list of template/recurring invoices + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +if (! empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; +} +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; + +$langs->load('bills'); +$langs->load('compta'); +$langs->load('admin'); +$langs->load('other'); + +$action = GETPOST('action','alpha'); +$massaction = GETPOST('massaction','alpha'); +$show_files = GETPOST('show_files','int'); +$confirm = GETPOST('confirm','alpha'); +$cancel = GETPOST('cancel', 'alpha'); +$toselect = GETPOST('toselect', 'array'); +$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'invoicetemplatelist'; // To manage different context of search + +// Security check +$id=(GETPOST('facid','int')?GETPOST('facid','int'):GETPOST('id','int')); +$lineid=GETPOST('lineid','int'); +$ref=GETPOST('ref','alpha'); +if ($user->societe_id) $socid=$user->societe_id; +$objecttype = 'facture_rec'; +if ($action == "create" || $action == "add") $objecttype = ''; +$result = restrictedArea($user, 'facture', $id, $objecttype); +$projectid = GETPOST('projectid','int'); + +$search_ref=GETPOST('search_ref'); +$search_societe=GETPOST('search_societe'); +$search_montant_ht=GETPOST('search_montant_ht'); +$search_montant_vat=GETPOST('search_montant_vat'); +$search_montant_ttc=GETPOST('search_montant_ttc'); +$search_payment_mode=GETPOST('search_payment_mode'); +$search_payment_term=GETPOST('search_payment_term'); +$day=GETPOST('day'); +$year=GETPOST('year'); +$month=GETPOST('month'); +$day_date_when=GETPOST('day_date_when'); +$year_date_when=GETPOST('year_date_when'); +$month_date_when=GETPOST('month_date_when'); +$search_recurring=GETPOST('search_recurring','int'); +$search_frequency=GETPOST('search_frequency','alpha'); +$search_unit_frequency=GETPOST('search_unit_frequency','alpha'); + +$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +if (! $sortorder) $sortorder='DESC'; +if (! $sortfield) $sortfield='f.titre'; +$pageprev = $page - 1; +$pagenext = $page + 1; + +$object = new FactureRec($db); +if (($id > 0 || $ref) && $action != 'create' && $action != 'add') +{ + $ret = $object->fetch($id, $ref); + if (!$ret) + { + setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors'); + } +} + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('invoicereccard','globalcard')); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('facture_rec'); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); + +$permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php +$permissiondellink=$user->rights->facture->creer; // Used by the include of actions_dellink.inc.php +$permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php + +$arrayfields=array( + 'f.titre'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 'f.total'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'f.tva'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>1), + 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>1), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>0), + 'f.fk_cond_reglement'=>array('label'=>$langs->trans("PaymentTerm"), 'checked'=>0), + 'recurring'=>array('label'=>$langs->trans("RecurringInvoiceTemplate"), 'checked'=>1), + 'f.frequency'=>array('label'=>$langs->trans("Frequency"), 'checked'=>1), + 'f.unit_frequency'=>array('label'=>$langs->trans("FrequencyUnit"), 'checked'=>1), + 'f.nb_gen_done'=>array('label'=>$langs->trans("NbOfGenerationDoneShort"), 'checked'=>1), + 'f.date_last_gen'=>array('label'=>$langs->trans("DateLastGeneration"), 'checked'=>1), + 'f.date_when'=>array('label'=>$langs->trans("NextDateToExecution"), 'checked'=>1), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>100), + 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), +); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } +} + + +/* + * Actions + */ + +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters = array('socid' => $socid); +$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)) +{ + if (GETPOST('cancel','alpha')) $action=''; + + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Do we click on purge search criteria ? + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers + { + $search_ref=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_payment_mode=''; + $search_payment_term=''; + $day=''; + $year=''; + $month=''; + $day_date_when=''; + $year_date_when=''; + $month_date_when=''; + $search_recurring=''; + $search_frequency=''; + $search_unit_frequency=''; + $search_array_options=array(); + } + + // Mass actions + /*$objectclass='MyObject'; + $objectlabel='MyObject'; + $permtoread = $user->rights->mymodule->read; + $permtodelete = $user->rights->mymodule->delete; + $uploaddir = $conf->mymodule->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/ + +} + + +/* + * View + */ + +llxHeader('',$langs->trans("RepeatableInvoices"),'ch-facture.html#s-fac-facture-rec'); + +$form = new Form($db); +$formother = new FormOther($db); +if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +$companystatic = new Societe($db); +$invoicerectmp = new FactureRec($db); + +$now = dol_now(); +$tmparray=dol_getdate($now); +$today = dol_mktime(23,59,59,$tmparray['mon'],$tmparray['mday'],$tmparray['year']); // Today is last second of current day + + +/* + * List mode + */ +$sql = "SELECT s.nom as name, s.rowid as socid, f.rowid as facid, f.titre, f.total, f.tva as total_vat, f.total_ttc, f.frequency, f.unit_frequency,"; +$sql.= " f.nb_gen_done, f.nb_gen_max, f.date_last_gen, f.date_when,"; +$sql.= " f.datec, f.tms,"; +$sql.= " f.fk_cond_reglement, f.fk_mode_reglement"; +$sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f"; +if (! $user->rights->societe->client->voir && ! $socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} +$sql.= " WHERE f.fk_soc = s.rowid"; +$sql.= ' AND f.entity IN ('.getEntity('facture').')'; +if (! $user->rights->societe->client->voir && ! $socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($search_ref) $sql .= natural_search('f.titre', $search_ref); +if ($search_societe) $sql .= natural_search('s.nom', $search_societe); +if ($search_montant_ht != '') $sql .= natural_search('f.total', $search_montant_ht, 1); +if ($search_montant_vat != '') $sql .= natural_search('f.tva', $search_montant_vat, 1); +if ($search_montant_ttc != '') $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1); +if (! empty($search_payment_mode) && $search_payment_mode != '-1') $sql .= natural_search('f.fk_mode_reglement', $search_payment_mode, 1); +if (! empty($search_payment_term) && $search_payment_term != '-1') $sql .= natural_search('f.fk_cond_reglement', $search_payment_term, 1); +if ($search_recurring == '1') $sql .= ' AND f.frequency > 0'; +if ($search_recurring == '0') $sql .= ' AND (f.frequency IS NULL or f.frequency = 0)'; +if ($search_frequency != '') $sql .= natural_search('f.frequency', $search_frequency, 1); +if ($search_unit_frequency != '') $sql .= natural_search('f.unit_frequency', $search_unit_frequency); + +if ($month > 0) +{ + if ($year > 0 && empty($day)) + $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(f.date_last_gen, '%m') = '".$month."'"; +} +else if ($year > 0) +{ + $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; +} +if ($month_date_when > 0) +{ + if ($year_date_when > 0 && empty($day_date_when)) + $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,$month_date_when,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,$month_date_when,false))."'"; + else if ($year_date_when > 0 && ! empty($day_date_when)) + $sql.= " AND f.date_date_when_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date_when, $day_date_when, $year_date_when))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date_when, $day_date_when, $year_date_when))."'"; + else + $sql.= " AND date_format(f.date_when, '%m') = '".$month_date_when."'"; +} +else if ($year_date_when > 0) +{ + $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,1,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,12,false))."'"; +} + +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} + +$sql.= $db->order($sortfield, $sortorder); +$sql.= $db->plimit($limit+1,$offset); + +$resql = $db->query($sql); +if ($resql) +{ + $num = $db->num_rows($resql); + + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); + if ($socid) $param.='&socid='.urlencode($socid); + if ($day) $param.='&day='.urlencode($day); + if ($month) $param.='&month='.urlencode($month); + if ($year) $param.='&year=' .urlencode($year); + if ($day_date_when) $param.='&day_date_when='.urlencode($day_date_when); + if ($month_date_when) $param.='&month_date_when='.urlencode($month_date_when); + if ($year_date_when) $param.='&year_date_when=' .urlencode($year_date_when); + if ($search_ref) $param.='&search_ref=' .urlencode($search_ref); + if ($search_societe) $param.='&search_societe=' .urlencode($search_societe); + if ($search_montant_ht != '') $param.='&search_montant_ht=' .urlencode($search_montant_ht); + if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); + if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); + if ($search_payment_mode != '') $param.='&search_payment_mode='.urlencode($search_payment_mode); + if ($search_payment_type != '') $param.='&search_payment_type='.urlencode($search_payment_type); + if ($search_recurring != '' && $search_recurrning != '-1') $param.='&search_recurring=' .urlencode($search_recurring); + if ($search_frequency > 0) $param.='&search_frequency=' .urlencode($search_frequency); + if ($search_unit_frequency > 0) $param.='&search_unit_frequency='.urlencode($search_unit_frequency); + if ($option) $param.="&option=".urlencode($option); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } + + $massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); + + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + //$selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + + print '
    '; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print_barre_liste($langs->trans("RepeatableInvoices"),$page,$_SERVER['PHP_SELF'],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords,'title_accountancy.png',0,'','', $limit); + + print $langs->trans("ToCreateAPredefinedInvoice", $langs->transnoentitiesnoconv("ChangeIntoRepeatableInvoice")).'

    '; + + $i = 0; + + print '
    '; + print ''."\n"; + + // Filters lines + print ''; + // Ref + if (! empty($arrayfields['f.titre']['checked'])) + { + print ''; + } + // Thirpdarty + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + } + if (! empty($arrayfields['f.total']['checked'])) + { + // Amount net + print ''; + } + if (! empty($arrayfields['f.tva']['checked'])) + { + // Amount Vat + print ''; + } + if (! empty($arrayfields['f.total_ttc']['checked'])) + { + // Amount + print ''; + } + if (! empty($arrayfields['f.fk_cond_reglement']['checked'])) + { + // Payment term + print '"; + } + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) + { + // Payment mode + print ''; + } + if (! empty($arrayfields['recurring']['checked'])) + { + // Recurring or not + print ''; + } + if (! empty($arrayfields['f.frequency']['checked'])) + { + // Recurring or not + print ''; + } + if (! empty($arrayfields['f.unit_frequency']['checked'])) + { + // Frequency unit + print ''; + } + if (! empty($arrayfields['f.nb_gen_done']['checked'])) + { + // Nb generation + print ''; + } + // Date invoice + if (! empty($arrayfields['f.date_last_gen']['checked'])) + { + print ''; + } + // Date due + if (! empty($arrayfields['f.date_when']['checked'])) + { + print ''; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['f.datec']['checked'])) + { + print ''; + } + // Date modification + if (! empty($arrayfields['f.tms']['checked'])) + { + print ''; + } + // Status + if (! empty($arrayfields['status']['checked'])) + { + print ''; + } + // Action column + print ''; + print "\n"; + + + print ''; + if (! empty($arrayfields['f.titre']['checked'])) print_liste_field_titre($arrayfields['f.titre']['label'],$_SERVER['PHP_SELF'],"f.titre","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER['PHP_SELF'],"s.nom","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['f.total']['checked'])) print_liste_field_titre($arrayfields['f.total']['label'],$_SERVER['PHP_SELF'],"f.total","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.tva']['checked'])) print_liste_field_titre($arrayfields['f.tva']['label'],$_SERVER['PHP_SELF'],"f.tva","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],"f.total_ttc","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'],$_SERVER['PHP_SELF'],"f.fk_cond_reglement","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'],$_SERVER['PHP_SELF'],"f.fk_mode_reglement","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['recurring']['checked'])) print_liste_field_titre($arrayfields['recurring']['label'],$_SERVER['PHP_SELF'],"recurring","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.frequency']['checked'])) print_liste_field_titre($arrayfields['f.frequency']['label'],$_SERVER['PHP_SELF'],"f.frequency","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.unit_frequency']['checked'])) print_liste_field_titre($arrayfields['f.unit_frequency']['label'],$_SERVER['PHP_SELF'],"f.unit_frequency","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.nb_gen_done']['checked'])) print_liste_field_titre($arrayfields['f.nb_gen_done']['label'],$_SERVER['PHP_SELF'],"f.nb_gen_done","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.date_last_gen']['checked'])) print_liste_field_titre($arrayfields['f.date_last_gen']['label'],$_SERVER['PHP_SELF'],"f.date_last_gen","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.date_when']['checked'])) print_liste_field_titre($arrayfields['f.date_when']['label'],$_SERVER['PHP_SELF'],"f.date_when","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER['PHP_SELF'],"f.datec","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER['PHP_SELF'],"f.tms","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'],$_SERVER['PHP_SELF'],"","",$param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'nomaxwidthsearch ')."\n"; + print "\n"; + + if ($num > 0) + { + $i=0; + $totalarray=array(); + while ($i < min($num,$limit)) + { + $objp = $db->fetch_object($resql); + if (empty($objp)) break; + + $companystatic->id=$objp->socid; + $companystatic->name=$objp->name; + + $invoicerectmp->id=$objp->id; + $invoicerectmp->frequency=$objp->frequency; + $invoicerectmp->suspend=$objp->suspend; + $invoicerectmp->unit_frequency=$objp->unit_frequency; + $invoicerectmp->nb_gen_max=$objp->nb_gen_max; + $invoicerectmp->nb_gen_done=$objp->nb_gen_done; + + print ''; + + if (! empty($arrayfields['f.titre']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['f.total']['checked'])) + { + print ''."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='f.total'; + $totalarray['val']['f.total'] += $objp->total; + } + if (! empty($arrayfields['f.tva']['checked'])) + { + print ''."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='f.tva'; + $totalarray['val']['f.tva'] += $objp->total_vat; + } + if (! empty($arrayfields['f.total_ttc']['checked'])) + { + print ''."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='f.total_ttc'; + $totalarray['val']['f.total_ttc'] += $objp->total_ttc; + } + // Payment term + if (! empty($arrayfields['f.fk_cond_reglement']['checked'])) + { + print ''."\n"; + if (! $i) $totalarray['nbfield']++; + } + // Payment mode + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) + { + print ''."\n"; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['recurring']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['f.frequency']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['f.unit_frequency']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['f.nb_gen_done']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['f.date_last_gen']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['f.date_when']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['f.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['f.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['status']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Action column + print '"; + + print "\n"; + + $i++; + } + } + else + { + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print ''; + } + + //var_dump($totalarray); + // Show total line + if (isset($totalarray['pos'])) + { + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if (! empty($totalarray['pos'][$i])) print ''; + else + { + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + else print ''; + } + } + print ''; + } + + print "
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print $form->select_conditions_paiements($search_payment_term, 'search_payment_term', -1, 1, 1, 'maxwidth100'); + print "'; + print $form->select_types_paiements($search_payment_mode, 'search_payment_mode', '', 0, 1, 1, 0, 1, 'maxwidth100'); + print ''; + print $form->selectyesno('search_recurring', $search_recurring, 1, false, 1); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year_date_when?$year_date_when:-1,'year_date_when',1, 20, 5); + 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 ''; + print ''; + $searchpicto=$form->showFilterAndCheckAddButtons(0, 'checkforselect', 1); + print $searchpicto; + print '
    '.img_object($langs->trans("ShowBill"),"bill").' '.$objp->titre; + print "'.$companystatic->getNomUrl(1,'customer').''.price($objp->total).''.price($objp->total_vat).''.price($objp->total_ttc).''; + print $form->form_conditions_reglement('', $objp->fk_cond_reglement, 'none'); + print ''; + print $form->form_modes_reglement('', $objp->fk_mode_reglement, 'none'); + print ''.yn($objp->frequency?1:0).''.($objp->frequency > 0 ? $objp->frequency : '').''.($objp->frequency > 0 ? $objp->unit_frequency : '').''; + print ($objp->frequency ? $objp->nb_gen_done.($objp->nb_gen_max>0?' / '. $objp->nb_gen_max:'') : ''.$langs->trans('NA').''); + print ''; + print ($objp->frequency ? dol_print_date($db->jdate($objp->date_last_gen),'day') : ''.$langs->trans('NA').''); + print ''; + print ($objp->frequency ? ($invoicerectmp->isMaxNbGenReached()?'':'').dol_print_date($db->jdate($objp->date_when),'day').($invoicerectmp->isMaxNbGenReached()?'':'') : ''.$langs->trans('NA').''); + print ''; + print dol_print_date($db->jdate($objp->datec),'dayhour'); + print ''; + print dol_print_date($db->jdate($objp->tms),'dayhour'); + print ''; + print $invoicerectmp->getLibStatut(3,0); + print ''; + if ($user->rights->facture->creer) + { + if (empty($objp->frequency) || $db->jdate($objp->date_when) <= $today) + { + print ''; + print $langs->trans("CreateBill").''; + } + else + { + print $langs->trans("DateIsNotEnough"); + } + } + else + { + print " "; + } + if (! $i) $totalarray['nbfield']++; + print "
    '.$langs->trans("NoRecordFound").'
    '.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").'
    "; + print "
    "; + print "
    "; + + $db->free($resql); +} +else +{ + dol_print_error($db); +} + +llxFooter(); + +$db->close(); diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 8563572da7c..1f45a7cec3e 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -112,8 +112,8 @@ if (! $sortfield) $sortfield='f.datef'; $pageprev = $page - 1; $pagenext = $page + 1; -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$contextpage='invoicelist'; +// Initialize technical object to manage context to save list fields +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'invoicelist'; // Security check $fieldid = (! empty($ref)?'facnumber':'rowid'); @@ -136,46 +136,46 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'f.facnumber'=>'Ref', - 'f.ref_client'=>'RefCustomer', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'f.note_public'=>'NotePublic', + 'f.facnumber'=>'Ref', + 'f.ref_client'=>'RefCustomer', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'f.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'f.facnumber'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'f.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), - 'f.date'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), - 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), - 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), - 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), - 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'dynamount_payed'=>array('label'=>$langs->trans("Received"), 'checked'=>0), - 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), - 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'f.facnumber'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'f.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), + 'f.date'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), + 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), + 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), + 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), + 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'dynamount_payed'=>array('label'=>$langs->trans("Received"), 'checked'=>0), + 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), + 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } } @@ -183,8 +183,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -195,44 +195,45 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','alpha') || GETPOST('button_removefilter.x','alpha')) // All tests are required to be compatible with all browsers { - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_refcustomer=''; - $search_type=''; - $search_project=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_localtax1=''; - $search_montant_localtax2=''; - $search_montant_ttc=''; - $search_status=''; - $search_paymentmode=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $day=''; - $year=''; - $month=''; - $option=''; - $filter=''; - $day_lim=''; - $year_lim=''; - $month_lim=''; - $toselect=''; - $search_array_options=array(); + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=''; + $search_refcustomer=''; + $search_type=''; + $search_project=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_localtax1=''; + $search_montant_localtax2=''; + $search_montant_ttc=''; + $search_status=''; + $search_paymentmode=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $day=''; + $year=''; + $month=''; + $option=''; + $filter=''; + $day_lim=''; + $year_lim=''; + $month_lim=''; + $toselect=''; + $search_array_options=array(); } if (empty($reshook)) { $objectclass='Facture'; $objectlabel='Invoices'; - $permtoread = $user->rights->facture->lire; + $permtoread = $user->rights->facture->lire; + $permtocreate = $user->rights->facture->creer; $permtodelete = $user->rights->facture->supprimer; $uploaddir = $conf->facture->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; @@ -240,98 +241,98 @@ if (empty($reshook)) if ($massaction == 'withdrawrequest') { - $langs->load("withdrawals"); + $langs->load("withdrawals"); - if (!$user->rights->prelevement->bons->creer) - { - $error++; - setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); - } - else - { - //Checking error - $error = 0; + if (!$user->rights->prelevement->bons->creer) + { + $error++; + setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); + } + else + { + //Checking error + $error = 0; - $arrayofselected=is_array($toselect)?$toselect:array(); - $listofbills=array(); - foreach($arrayofselected as $toselectid) - { - $objecttmp=new Facture($db); - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $totalpaye = $objecttmp->getSommePaiement(); - $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); - $totaldeposits = $objecttmp->getSumDepositsUsed(); - $objecttmp->resteapayer = price2num($objecttmp->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT'); - $listofbills[] = $objecttmp; - if($objecttmp->paye || $objecttmp->resteapayer==0){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("AlreadyPaid"), $objecttmp->errors, 'errors'); - } else if($objecttmp->resteapayer<0){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors'); - } - if(!($objecttmp->statut > Facture::STATUS_DRAFT)){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors'); - } + $arrayofselected=is_array($toselect)?$toselect:array(); + $listofbills=array(); + foreach($arrayofselected as $toselectid) + { + $objecttmp=new Facture($db); + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $totalpaye = $objecttmp->getSommePaiement(); + $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); + $totaldeposits = $objecttmp->getSumDepositsUsed(); + $objecttmp->resteapayer = price2num($objecttmp->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT'); + $listofbills[] = $objecttmp; + if($objecttmp->paye || $objecttmp->resteapayer==0){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("AlreadyPaid"), $objecttmp->errors, 'errors'); + } else if($objecttmp->resteapayer<0){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors'); + } + if(!($objecttmp->statut > Facture::STATUS_DRAFT)){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors'); + } - $rsql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande"; - $rsql .= " , pfd.date_traite as date_traite"; - $rsql .= " , pfd.amount"; - $rsql .= " , u.rowid as user_id, u.lastname, u.firstname, u.login"; - $rsql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - $rsql .= " , ".MAIN_DB_PREFIX."user as u"; - $rsql .= " WHERE fk_facture = ".$objecttmp->id; - $rsql .= " AND pfd.fk_user_demande = u.rowid"; - $rsql .= " AND pfd.traite = 0"; - $rsql .= " ORDER BY pfd.date_demande DESC"; + $rsql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande"; + $rsql .= " , pfd.date_traite as date_traite"; + $rsql .= " , pfd.amount"; + $rsql .= " , u.rowid as user_id, u.lastname, u.firstname, u.login"; + $rsql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + $rsql .= " , ".MAIN_DB_PREFIX."user as u"; + $rsql .= " WHERE fk_facture = ".$objecttmp->id; + $rsql .= " AND pfd.fk_user_demande = u.rowid"; + $rsql .= " AND pfd.traite = 0"; + $rsql .= " ORDER BY pfd.date_demande DESC"; - $result_sql = $db->query($rsql); - if ($result_sql) - { - $numprlv = $db->num_rows($result_sql); - } + $result_sql = $db->query($rsql); + if ($result_sql) + { + $numprlv = $db->num_rows($result_sql); + } - if($numprlv>0){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors'); - } - if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); - } + if($numprlv>0){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors'); + } + if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); + } - } - } + } + } - //Massive withdraw request - if(!empty($listofbills) && empty($error)) - { - $nbwithdrawrequestok=0; - foreach($listofbills as $aBill) - { - $db->begin(); - $result = $aBill->demande_prelevement($user, $aBill->resteapayer); - if ($result > 0) - { - $db->commit(); - $nbwithdrawrequestok++; - } - else - { + //Massive withdraw request + if(!empty($listofbills) && empty($error)) + { + $nbwithdrawrequestok=0; + foreach($listofbills as $aBill) + { + $db->begin(); + $result = $aBill->demande_prelevement($user, $aBill->resteapayer); + if ($result > 0) + { + $db->commit(); + $nbwithdrawrequestok++; + } + else + { - $db->rollback(); - setEventMessages($aBill->error, $aBill->errors, 'errors'); - } - } - if ($nbwithdrawrequestok > 0) - { - setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs'); - } - } - } + $db->rollback(); + setEventMessages($aBill->error, $aBill->errors, 'errors'); + } + } + if ($nbwithdrawrequestok > 0) + { + setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs'); + } + } + } } @@ -347,6 +348,7 @@ $formfile = new FormFile($db); $bankaccountstatic=new Account($db); $facturestatic=new Facture($db); $formcompany=new FormCompany($db); +$thirdpartystatic=new Societe($db); llxHeader('',$langs->trans('CustomersInvoices'),'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes'); @@ -357,7 +359,7 @@ $sql.= ' f.localtax1 as total_localtax1, f.localtax2 as total_localtax2,'; $sql.= ' f.datef as df, f.date_lim_reglement as datelimite,'; $sql.= ' f.paye as paye, f.fk_statut,'; $sql.= ' f.datec as date_creation, f.tms as date_update,'; -$sql.= ' s.rowid as socid, s.nom as name, s.town, s.zip, s.fk_pays, s.client, s.code_client, '; +$sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, '; $sql.= " typent.code as typent_code,"; $sql.= " state.code_departement as state_code, state.nom as state_name"; // We need dynamount_payed to be able to sort on status (value is surely wrong because we can count several lines several times due to other left join or link with contacts. But what we need is just 0 or > 0) @@ -382,8 +384,8 @@ if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE f.fk_soc = s.rowid'; $sql.= ' AND f.entity IN ('.getEntity('facture').')'; @@ -392,28 +394,28 @@ if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$db->escape($s if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; if ($userid) { - if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL'; - else $sql.=' AND f.fk_user_author = '.$userid; + if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL'; + else $sql.=' AND f.fk_user_author = '.$userid; } if ($filtre) { - $aFilter = explode(',', $filtre); - foreach ($aFilter as $filter) - { - $filt = explode(':', $filter); - $sql .= ' AND ' . $db->escape(trim($filt[0])) . ' = ' . $db->escape(trim($filt[1])); - } + $aFilter = explode(',', $filtre); + foreach ($aFilter as $filter) + { + $filt = explode(':', $filter); + $sql .= ' AND ' . $db->escape(trim($filt[0])) . ' = ' . $db->escape(trim($filt[1])); + } } if ($search_ref) $sql .= natural_search('f.facnumber', $search_ref); if ($search_refcustomer) $sql .= natural_search('f.ref_client', $search_refcustomer); if ($search_type != '' && $search_type >= 0) { - if ($search_type == '0') $sql.=" AND f.type = 0"; // standard - if ($search_type == '1') $sql.=" AND f.type = 1"; // replacement - if ($search_type == '2') $sql.=" AND f.type = 2"; // credit note - if ($search_type == '3') $sql.=" AND f.type = 3"; // deposit - if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma - if ($search_type == '5') $sql.=" AND f.type = 5"; // situation + if ($search_type == '0') $sql.=" AND f.type = 0"; // standard + if ($search_type == '1') $sql.=" AND f.type = 1"; // replacement + if ($search_type == '2') $sql.=" AND f.type = 2"; // credit note + if ($search_type == '3') $sql.=" AND f.type = 3"; // deposit + if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma + if ($search_type == '5') $sql.=" AND f.type = 5"; // situation } if ($search_project) $sql .= natural_search('p.ref', $search_project); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); @@ -430,24 +432,24 @@ if ($search_montant_localtax2 != '') $sql.= natural_search('f.localtax2', $searc if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1); if ($search_status != '' && $search_status >= 0) { - if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft - if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed - if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) - if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned + if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft + if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed + if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) + if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned } if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$db->escape($search_paymentmode); if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(f.datef, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(f.datef, '%m') = '".$month."'"; } else if ($year > 0) { - $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($month_lim > 0) { @@ -466,21 +468,21 @@ if ($option == 'late') $sql.=" AND f.date_lim_reglement < '".$db->idate(dol_now( if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) { - $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; + $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -489,22 +491,22 @@ $sql.=$hookmanager->resPrint; if (! $sall) { - $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.total, f.tva, f.total_ttc,'; - $sql.= ' f.localtax1, f.localtax2,'; - $sql.= ' f.datef, f.date_lim_reglement,'; - $sql.= ' f.paye, f.fk_statut,'; - $sql.= ' f.datec, f.tms,'; - $sql.= ' s.rowid, s.nom, s.town, s.zip, s.fk_pays, s.code_client, s.client, typent.code,'; - $sql.= ' state.code_departement, state.nom'; + $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.total, f.tva, f.total_ttc,'; + $sql.= ' f.localtax1, f.localtax2,'; + $sql.= ' f.datef, f.date_lim_reglement,'; + $sql.= ' f.paye, f.fk_statut,'; + $sql.= ' f.datec, f.tms,'; + $sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.code_client, s.client, typent.code,'; + $sql.= ' state.code_departement, state.nom'; - foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by - { - $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); - } + foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by + { + $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); + } } else { - $sql .= natural_search(array_keys($fieldstosearchall), $sall); + $sql .= natural_search(array_keys($fieldstosearchall), $sall); } $sql.= ' ORDER BY '; @@ -525,55 +527,56 @@ $sql.= $db->plimit($limit+1,$offset); $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); + $num = $db->num_rows($resql); $arrayofselected=is_array($toselect)?$toselect:array(); - if ($socid) - { - $soc = new Societe($db); - $soc->fetch($socid); + if ($socid) + { + $soc = new Societe($db); + $soc->fetch($socid); if (empty($search_societe)) $search_societe = $soc->name; - } + } - $param='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + $param='&socid='.$socid; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $param.='&sall='.urlencode($sall); - if ($day) $param.='&day='.urlencode($day); - if ($month) $param.='&month='.urlencode($month); - if ($year) $param.='&year=' .urlencode($year); - if ($day_lim) $param.='&day_lim='.urlencode($day_lim); - if ($month_lim) $param.='&month_lim='.urlencode($month_lim); - if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); - if ($search_ref) $param.='&search_ref=' .urlencode($search_ref); - if ($search_refcustomer) $param.='&search_refcustomer=' .urlencode($search_refcustomer); - if ($search_type != '') $param.='&search_type='.urlencode($search_type); - if ($search_societe) $param.='&search_societe=' .urlencode($search_societe); - if ($search_sale > 0) $param.='&search_sale=' .urlencode($search_sale); - if ($search_user > 0) $param.='&search_user=' .urlencode($search_user); - if ($search_product_category > 0) $param.='$search_product_category=' .urlencode($search_product_category); - if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); - if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); - if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); - if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); + if ($day) $param.='&day='.urlencode($day); + if ($month) $param.='&month='.urlencode($month); + if ($year) $param.='&year=' .urlencode($year); + if ($day_lim) $param.='&day_lim='.urlencode($day_lim); + if ($month_lim) $param.='&month_lim='.urlencode($month_lim); + if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); + if ($search_ref) $param.='&search_ref=' .urlencode($search_ref); + if ($search_refcustomer) $param.='&search_refcustomer=' .urlencode($search_refcustomer); + if ($search_type != '') $param.='&search_type='.urlencode($search_type); + if ($search_societe) $param.='&search_societe=' .urlencode($search_societe); + if ($search_sale > 0) $param.='&search_sale=' .urlencode($search_sale); + if ($search_user > 0) $param.='&search_user=' .urlencode($search_user); + if ($search_product_category > 0) $param.='$search_product_category=' .urlencode($search_product_category); + if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); + if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); + if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); + if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); + if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); if ($search_status != '') $param.='&search_status='.urlencode($search_status); if ($search_paymentmode > 0) $param.='search_paymentmode='.urlencode($search_paymentmode); - if ($show_files) $param.='&show_files=' .$show_files; + if ($show_files) $param.='&show_files=' .$show_files; if ($option) $param.="&option=".$option; if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } $arrayofmassactions=array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'validate'=>$langs->trans("Validate"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if ($conf->prelevement->enabled) { @@ -582,140 +585,52 @@ if ($resql) } if ($user->rights->facture->supprimer) { - //if (! empty($conf->global->STOCK_CALCULATE_ON_BILL) || empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) - if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) - { - // mass deletion never possible on invoices on such situation - } - else - { - $arrayofmassactions['delete']=$langs->trans("Delete"); - } + //if (! empty($conf->global->STOCK_CALCULATE_ON_BILL) || empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) + if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) + { + // mass deletion never possible on invoices on such situation + } + else + { + $arrayofmassactions['delete']=$langs->trans("Delete"); + } } if ($massaction == 'presend') $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - $i = 0; - print '
    '."\n"; + $i = 0; + print ''."\n"; - if ($optioncss != '') print ''; - print ''; + if ($optioncss != '') print ''; + print ''; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit); if ($massaction == 'presend') { - $langs->load("mails"); - - if (! GETPOST('cancel')) - { - $objecttmp=new Facture($db); - $listofselectedid=array(); - $listofselectedthirdparties=array(); - $listofselectedref=array(); - foreach($arrayofselected as $toselectid) - { - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofselectedid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - $listofselectedthirdparties[$thirdpartyid]=$thirdpartyid; - $listofselectedref[$thirdpartyid][$toselectid]=$objecttmp->ref; - } - } - } - - print ''; - - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - - dol_fiche_head(null, '', ''); - $topicmail="SendBillRef"; $modelmail="facture_send"; + $objecttmp=new Facture($db); + $trackid='inv'.$object->id; - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->withform=-1; - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 1)) // If bit 1 is set - { - $formmail->trackid='inv'.$object->id; - } - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'inv'.$object->id); - } - $formmail->withfrom=1; - $liste=$langs->trans("AllRecipientSelected"); - if (count($listofselectedthirdparties) == 1) - { - $liste=array(); - $thirdpartyid=array_shift($listofselectedthirdparties); - $soc=new Societe($db); - $soc->fetch($thirdpartyid); - foreach ($soc->thirdparty_and_contact_email_array(1) as $key=>$value) - { - $liste[$key]=$value; - } - $formmail->withtoreadonly=0; - } - else - { - $formmail->withtoreadonly=1; - } - $formmail->withto=$liste; - $formmail->withtofree=0; - $formmail->withtocc=1; - $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic=$langs->transnoentities($topicmail, '__REF__', '__REFCLIENT__'); - $formmail->withfile=$langs->trans("OnlyPDFattachmentSupported"); - $formmail->withbody=1; - $formmail->withdeliveryreceipt=1; - $formmail->withcancel=1; - // Tableau des substitutions - $formmail->substit['__REF__']='__REF__'; // We want to keep the tag - $formmail->substit['__SIGNATURE__']=$user->signature; - $formmail->substit['__REFCLIENT__']='__REFCLIENT__'; // We want to keep the tag - $formmail->substit['__PERSONALIZED__']=''; - $formmail->substit['__CONTACTCIVNAME__']=''; - - // Tableau des parametres complementaires du post - $formmail->param['action']=$action; - $formmail->param['models']=$modelmail; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['facid']=join(',',$arrayofselected); - // TODO We should use $formmail->param['id']=join(',',$arrayofselected); - //$formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id; - - print $formmail->get_form(); - - dol_fiche_end(); + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; } - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + if ($sall) + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } // If the user can view prospects other than his' - $moreforfilter=''; + $moreforfilter=''; if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); @@ -724,14 +639,14 @@ if ($resql) $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); $moreforfilter.='
    '; } - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) + { $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='
    '; - } + } // If the user can view prospects other than his' if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { @@ -742,51 +657,51 @@ if ($resql) $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter.='
    '; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; else $moreforfilter = $hookmanager->resPrint; - if ($moreforfilter) - { + if ($moreforfilter) + { print '
    '; - print $moreforfilter; - print '
    '; - } + print $moreforfilter; + print '
    '; + } - $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); + $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"; + print '
    '; + print '
    '."\n"; - // Filters lines - print ''; + // Filters lines + print ''; // Ref if (! empty($arrayfields['f.facnumber']['checked'])) { - print ''; + print ''; } // Ref customer if (! empty($arrayfields['f.ref_client']['checked'])) { - print ''; + print ''; } // Type if (! empty($arrayfields['f.type']['checked'])) { print ''; @@ -794,26 +709,26 @@ if ($resql) // Date invoice if (! empty($arrayfields['f.date']['checked'])) { - print ''; + print ''; } // Date due if (! empty($arrayfields['f.date_lim_reglement']['checked'])) { - print ''; + print ''; } // Project if (! empty($arrayfields['p.ref']['checked'])) { - print ''; + print ''; } // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) @@ -827,98 +742,98 @@ if ($resql) // State if (! empty($arrayfields['state.nom']['checked'])) { - print ''; + print ''; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; + print ''; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print ''; + print ''; } // Payment mode if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['f.total_ht']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_vat']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_localtax1']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_localtax2']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_ttc']['checked'])) { - // Amount - print ''; + // Amount + print ''; } - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print ''; - } - if (! empty($arrayfields['rtp']['checked'])) - { - print ''; - } - // Extra fields + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print ''; + } + if (! empty($arrayfields['rtp']['checked'])) + { + print ''; + } + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -927,360 +842,360 @@ if ($resql) // Date creation if (! empty($arrayfields['f.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['f.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['f.fk_statut']['checked'])) { - print ''; + print ''; } // Action column print ''; - print "\n"; + print ''; + print "\n"; - print ''; - if (! empty($arrayfields['f.facnumber']['checked'])) print_liste_field_titre($arrayfields['f.facnumber']['label'],$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'],$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'],$_SERVER["PHP_SELF"],'f.type','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'],$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'],$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'],$_SERVER["PHP_SELF"],"f.fk_mode_reglement","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'],$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'],$_SERVER['PHP_SELF'],'f.tva','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'],$_SERVER['PHP_SELF'],'f.localtax1','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'],$_SERVER['PHP_SELF'],'f.localtax2','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; + print ''; + if (! empty($arrayfields['f.facnumber']['checked'])) print_liste_field_titre($arrayfields['f.facnumber']['label'],$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'],$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'],$_SERVER["PHP_SELF"],'f.type','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'],$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'],$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'],$_SERVER["PHP_SELF"],"f.fk_mode_reglement","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'],$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'],$_SERVER['PHP_SELF'],'f.tva','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'],$_SERVER['PHP_SELF'],'f.localtax1','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'],$_SERVER['PHP_SELF'],'f.localtax2','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } + } + // Hook fields + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); + print "\n"; - if ($num > 0) - { - $i=0; - $totalarray=array(); - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); + if ($num > 0) + { + $i=0; + $totalarray=array(); + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); - $datelimit=$db->jdate($obj->datelimite); - $facturestatic->id=$obj->id; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - $facturestatic->statut=$obj->fk_statut; - $facturestatic->date_lim_reglement=$db->jdate($obj->datelimite); - $facturestatic->note_public=$obj->note_public; - $facturestatic->note_private=$obj->note_private; + $datelimit=$db->jdate($obj->datelimite); + $facturestatic->id=$obj->id; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + $facturestatic->statut=$obj->fk_statut; + $facturestatic->date_lim_reglement=$db->jdate($obj->datelimite); + $facturestatic->note_public=$obj->note_public; + $facturestatic->note_private=$obj->note_private; - $paiement = $facturestatic->getSommePaiement(); - $totalcreditnotes = $facturestatic->getSumCreditNotesUsed(); - $totaldeposits = $facturestatic->getSumDepositsUsed(); - $totalpay = $paiement + $totalcreditnotes + $totaldeposits; - $remaintopay = $obj->total_ttc - $totalpay; + $paiement = $facturestatic->getSommePaiement(); + $totalcreditnotes = $facturestatic->getSumCreditNotesUsed(); + $totaldeposits = $facturestatic->getSumDepositsUsed(); + $totalpay = $paiement + $totalcreditnotes + $totaldeposits; + $remaintopay = $obj->total_ttc - $totalpay; - print ''; - if (! empty($arrayfields['f.facnumber']['checked'])) - { - print ''; + if (! empty($arrayfields['f.facnumber']['checked'])) + { + print ''; + print ''; + print '
    '; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; $listtype=array( - Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), - Facture::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), - Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), - Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), - ); + Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), + Facture::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), + Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), + Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), + ); //$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma"); // A proformat invoice is not an invoice but must be an order. print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth100'); print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); - print '
    '.$langs->trans("Late"); - print '
    '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); + print '
    '.$langs->trans("Late"); + print '
    '; - print ''; - print ''; + print ''; + print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100'); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100'); + print ''; - $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); - print ''; + $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + 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 ''; + 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 ''; - print ''; + print ''; - $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); - print $form->selectarray('search_status', $liststatus, $search_status, 1); - print ''; + $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); + print $form->selectarray('search_status', $liststatus, $search_status, 1); + print ''; $searchpicto=$form->showFilterButtons(); print $searchpicto; - print '
    '; + print '
    '; - print ''; + print '
    '; - print ''; + print ''; - print ''; - print ''; - print '
    '; - print $facturestatic->getNomUrl(1,'',200,0,'',0,1); - print empty($obj->increment)?'':' ('.$obj->increment.')'; - print ''; + print $facturestatic->getNomUrl(1,'',200,0,'',0,1); + print empty($obj->increment)?'':' ('.$obj->increment.')'; + print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->id; - print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); - print '
    '; + print '
    '; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->id; + print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); + print '
    '; - print "\n"; - if (! $i) $totalarray['nbfield']++; - } + print "\n"; + if (! $i) $totalarray['nbfield']++; + } // Customer ref - if (! empty($arrayfields['f.ref_client']['checked'])) - { - print ''; - print $obj->ref_client; - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.ref_client']['checked'])) + { + print ''; + print $obj->ref_client; + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Type - if (! empty($arrayfields['f.type']['checked'])) - { - print ''; - print $facturestatic->getLibType(); - print ""; - if (! $i) $totalarray['nbfield']++; - } + // Type + if (! empty($arrayfields['f.type']['checked'])) + { + print ''; + print $facturestatic->getLibType(); + print ""; + if (! $i) $totalarray['nbfield']++; + } // Date - if (! empty($arrayfields['f.date']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->df),'day'); - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.date']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->df),'day'); + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Date limit - if (! empty($arrayfields['f.date_lim_reglement']['checked'])) - { - print ''.dol_print_date($datelimit,'day'); - if ($facturestatic->hasDelay()) - { - print img_warning($langs->trans('Late')); - } - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Date limit + if (! empty($arrayfields['f.date_lim_reglement']['checked'])) + { + print ''.dol_print_date($datelimit,'day'); + if ($facturestatic->hasDelay()) + { + print img_warning($langs->trans('Late')); + } + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Project - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - if ($obj->project_id > 0) - { - $projectstatic->id=$obj->project_id; - $projectstatic->ref=$obj->project_ref; - print $projectstatic->getNomUrl(1); - } - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Project + if (! empty($arrayfields['p.ref']['checked'])) + { + print ''; + if ($obj->project_id > 0) + { + $projectstatic->id=$obj->project_id; + $projectstatic->ref=$obj->project_ref; + print $projectstatic->getNomUrl(1); + } + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - $thirdparty=new Societe($db); - $thirdparty->id=$obj->socid; - $thirdparty->name=$obj->name; - $thirdparty->client=$obj->client; - $thirdparty->code_client=$obj->code_client; - print $thirdparty->getNomUrl(1,'customer'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - print $obj->town; - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print ''; - print $obj->zip; - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "".$obj->state_name."\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Third party + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + $thirdpartystatic->id=$obj->socid; + $thirdpartystatic->name=$obj->name; + $thirdpartystatic->client=$obj->client; + $thirdpartystatic->code_client=$obj->code_client; + $thirdpartystatic->email=$obj->email; + print $thirdpartystatic->getNomUrl(1,'customer'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + print $obj->town; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print ''; + print $obj->zip; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "".$obj->state_name."\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Payment mode - if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) - { - print ''; - $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Payment mode + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) + { + print ''; + $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Amount HT - if (! empty($arrayfields['f.total_ht']['checked'])) - { - print ''.price($obj->total_ht)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['f.total_vat']['checked'])) - { - print ''.price($obj->total_vat)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount LocalTax1 - if (! empty($arrayfields['f.total_localtax1']['checked'])) - { - print ''.price($obj->total_localtax1)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; - $totalarray['totallocaltax1'] += $obj->total_localtax1; - } - // Amount LocalTax2 - if (! empty($arrayfields['f.total_localtax2']['checked'])) - { - print ''.price($obj->total_localtax2)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; - $totalarray['totallocaltax2'] += $obj->total_localtax2; - } - // Amount TTC - if (! empty($arrayfields['f.total_ttc']['checked'])) - { - print ''.price($obj->total_ttc)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } + // Amount HT + if (! empty($arrayfields['f.total_ht']['checked'])) + { + print ''.price($obj->total_ht)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['f.total_vat']['checked'])) + { + print ''.price($obj->total_vat)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount LocalTax1 + if (! empty($arrayfields['f.total_localtax1']['checked'])) + { + print ''.price($obj->total_localtax1)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; + $totalarray['totallocaltax1'] += $obj->total_localtax1; + } + // Amount LocalTax2 + if (! empty($arrayfields['f.total_localtax2']['checked'])) + { + print ''.price($obj->total_localtax2)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; + $totalarray['totallocaltax2'] += $obj->total_localtax2; + } + // Amount TTC + if (! empty($arrayfields['f.total_ttc']['checked'])) + { + print ''.price($obj->total_ttc)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print ''.(! empty($totalpay)?price($totalpay,0,$langs):' ').''; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; - $totalarray['totalam'] += $totalpay; - } + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print ''.(! empty($totalpay)?price($totalpay,0,$langs):' ').''; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; + $totalarray['totalam'] += $totalpay; + } - if (! empty($arrayfields['rtp']['checked'])) - { - print ''.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').''; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; - $totalarray['totalrtp'] += $remaintopay; - } + if (! empty($arrayfields['rtp']['checked'])) + { + print ''.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').''; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; + $totalarray['totalrtp'] += $remaintopay; + } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['f.datec']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['f.tms']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['f.fk_statut']['checked'])) - { - print ''; - print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); - print ""; - if (! $i) $totalarray['nbfield']++; - } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['f.datec']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['f.tms']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['f.fk_statut']['checked'])) + { + print ''; + print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); + print ""; + if (! $i) $totalarray['nbfield']++; + } - // Action column - 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->id, $arrayofselected)) $selected=1; - print ''; - } - print '' ; - if (! $i) $totalarray['nbfield']++; + // Action column + 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->id, $arrayofselected)) $selected=1; + print ''; + } + print '' ; + if (! $i) $totalarray['nbfield']++; - print "\n"; + print "\n"; - $i++; - } + $i++; + } - // Show total line - if (isset($totalarray['totalhtfield']) + // Show total line + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totallocaltax1field']) || isset($totalarray['totallocaltax2field']) @@ -1288,62 +1203,62 @@ if ($resql) || isset($totalarray['totalamfield']) || isset($totalarray['totalrtpfield']) ) - { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; - else print ''.$langs->trans("Totalforthispage").''; - } - elseif ($totalarray['totalhtfield'] == $i) print ''.price($totalarray['totalht']).''; - elseif ($totalarray['totalvatfield'] == $i) print ''.price($totalarray['totalvat']).''; - elseif ($totalarray['totallocaltax1field'] == $i) print ''.price($totalarray['totallocaltax1']).''; - elseif ($totalarray['totallocaltax2field'] == $i) print ''.price($totalarray['totallocaltax2']).''; - elseif ($totalarray['totalttcfield'] == $i) print ''.price($totalarray['totalttc']).''; - elseif ($totalarray['totalamfield'] == $i) print ''.price($totalarray['totalam']).''; - elseif ($totalarray['totalrtpfield'] == $i) print ''.price($totalarray['totalrtp']).''; - else print ''; - } - print ''; + { + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; + else print ''.$langs->trans("Totalforthispage").''; + } + elseif ($totalarray['totalhtfield'] == $i) print ''.price($totalarray['totalht']).''; + elseif ($totalarray['totalvatfield'] == $i) print ''.price($totalarray['totalvat']).''; + elseif ($totalarray['totallocaltax1field'] == $i) print ''.price($totalarray['totallocaltax1']).''; + elseif ($totalarray['totallocaltax2field'] == $i) print ''.price($totalarray['totallocaltax2']).''; + elseif ($totalarray['totalttcfield'] == $i) print ''.price($totalarray['totalttc']).''; + elseif ($totalarray['totalamfield'] == $i) print ''.price($totalarray['totalam']).''; + elseif ($totalarray['totalrtpfield'] == $i) print ''.price($totalarray['totalrtp']).''; + else print ''; + } + print ''; - } - } + } + } - $db->free($resql); + $db->free($resql); $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 "\n"; - print '
    '; + print '
    '; - print "\n"; + print "\n"; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) - { - // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->facture->lire; - $delallowed=$user->rights->facture->creer; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->facture->lire; + $delallowed=$user->rights->facture->creer; - print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
    '.$langs->trans("ShowTempMassFilesArea").''; - } + print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '
    '.$langs->trans("ShowTempMassFilesArea").''; + } } else { - dol_print_error($db); + dol_print_error($db); } llxFooter(); diff --git a/htdocs/compta/facture/note.php b/htdocs/compta/facture/note.php index 223480e4ba8..3428ccddd4b 100644 --- a/htdocs/compta/facture/note.php +++ b/htdocs/compta/facture/note.php @@ -74,14 +74,14 @@ if ($id > 0 || ! empty($ref)) $object->fetch_thirdparty(); $head = facture_prepare_head($object); - + $totalpaye = $object->getSommePaiement(); - + dol_fiche_head($head, 'note', $langs->trans("InvoiceCustomer"), -1, 'bill'); // Invoice content - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; // Ref customer @@ -130,8 +130,8 @@ if ($id > 0 || ! empty($ref)) print '
    '; print '
    '; - - + + $cssclass="titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index e9b1694808b..9f2245d38a5 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -151,7 +151,7 @@ if ($object->id > 0) // Invoice content - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; // Ref customer @@ -425,28 +425,28 @@ if ($object->id > 0) print ''.$langs->trans("RIB").''; print $object->thirdparty->display_rib(); print ''; - + print ''; print '
    '; print '
    '; print '
    '; print '
    '; - + print ''; - + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT print ''; print ''; print ''; - + // Multicurrency Amount VAT print ''; print ''; print ''; - + // Multicurrency Amount TTC print ''; print ''; @@ -507,16 +507,16 @@ if ($object->id > 0) // TODO Replace this by an include with same code to show already done payment visible in invoice card print ''; - + print '
    ' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    '.$langs->trans('RemainderToPay').''.price($resteapayer, 1, '', 1, - 1, - 1, $conf->currency).'
    '; - + print '
    '; print '
    '; print '
    '; print '
    '; - - + + dol_fiche_end(); @@ -612,7 +612,7 @@ if ($object->id > 0) while ($i < $num) { $obj = $db->fetch_object($result_sql); - + print ''; print ''.dol_print_date($db->jdate($obj->date_demande),'day')."\n"; @@ -640,7 +640,7 @@ if ($object->id > 0) } // Closed requests - + $sql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande,"; $sql.= " pfd.date_traite, pfd.fk_prelevement_bons, pfd.amount,"; $sql.= " pb.ref,"; @@ -663,7 +663,7 @@ if ($object->id > 0) while ($i < $num) { $obj = $db->fetch_object($result); - + print ''; diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index 5f3076f9b37..d85255fbf4e 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -74,7 +74,7 @@ if ($mode == 'customer') if ($mode == 'supplier') { $title=$langs->trans("BillsStatisticsSuppliers"); - $dir=$conf->fournisseur->dir_output.'/facture/temp'; + $dir=$conf->fournisseur->facture->dir_temp; } print load_fiche_titre($title, $mesg, 'title_accountancy.png'); diff --git a/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php b/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php index 2e7858fdb08..44d5ec2ced5 100644 --- a/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php +++ b/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php @@ -36,7 +36,7 @@ $var=true; foreach($linkedObjectBlock as $key => $objectlink) { $ilink++; - + $trclass=($var?'pair':'impair'); if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total'; ?> @@ -44,13 +44,17 @@ foreach($linkedObjectBlock as $key => $objectlink) trans("RepeatableInvoice"); ?> getNomUrl(1); ?> - date,'day'); ?> + date_when,'day'); ?> rights->facture->lire) { $total = $total + $objectlink->total_ht; echo price($objectlink->total_ht); } ?> - + + getLibStatut(3); + ?> + ">transnoentitiesnoconv("RemoveLink")); ?> global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele if (! empty($conf->facture->enabled) && $user->rights->facture->lire) { $sql = "SELECT f.facnumber"; - $sql.= ", f.rowid, f.total as total_ht, f.tva as total_tva, f.total_ttc"; + $sql.= ", f.rowid, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.ref_client"; $sql.= ", f.type"; $sql.= ", s.nom as name"; $sql.= ", s.rowid as socid"; @@ -178,6 +178,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $facturestatic->total_ht=$obj->total_ht; $facturestatic->total_tva=$obj->total_tva; $facturestatic->total_ttc=$obj->total_ttc; + $facturestatic->ref_client=$obj->ref_client; $facturestatic->type=$obj->type; print $facturestatic->getNomUrl(1,''); print ''; @@ -218,7 +219,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) */ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) { - $sql = "SELECT f.ref, f.rowid, f.total_ht, f.total_tva, f.total_ttc, f.type"; + $sql = "SELECT f.ref, f.rowid, f.total_ht, f.total_tva, f.total_ttc, f.type, f.ref_supplier"; $sql.= ", s.nom as name"; $sql.= ", s.rowid as socid"; $sql.= ", s.code_fournisseur"; @@ -253,6 +254,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- $facturesupplierstatic->total_ht=$obj->total_ht; $facturesupplierstatic->total_tva=$obj->total_tva; $facturesupplierstatic->total_ttc=$obj->total_ttc; + $facturesupplierstatic->ref_supplier=$obj->ref_supplier; $facturesupplierstatic->type=$obj->type; print $facturesupplierstatic->getNomUrl(1,'',16); print ''; diff --git a/htdocs/compta/journal/purchasesjournal.php b/htdocs/compta/journal/purchasesjournal.php index fbd391ffe2a..5934ca71afb 100644 --- a/htdocs/compta/journal/purchasesjournal.php +++ b/htdocs/compta/journal/purchasesjournal.php @@ -84,16 +84,16 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end $date_start=dol_get_first_day($pastmonthyear,$pastmonth,false); $date_end=dol_get_last_day($pastmonthyear,$pastmonth,false); } -$nom=$langs->trans("PurchasesJournal"); -$nomlink=''; +$name=$langs->trans("PurchasesJournal"); $periodlink=''; $exportlink=''; -$builddate=time(); +$builddate=dol_now(); $description=$langs->trans("DescPurchasesJournal").'
    '; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink); + +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink); $p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); $idpays = $p[0]; diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php index fd0c45be7cd..f4b027b5016 100644 --- a/htdocs/compta/journal/sellsjournal.php +++ b/htdocs/compta/journal/sellsjournal.php @@ -89,15 +89,14 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end } $nom=$langs->trans("SellsJournal"); -$nomlink=''; $periodlink=''; $exportlink=''; -$builddate=time(); +$builddate=dol_now(); $description=$langs->trans("DescSellsJournal").'
    '; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink); +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink); $p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); $idpays = $p[0]; @@ -170,7 +169,7 @@ if ($result) $prev_progress = 0; if ($obj->type==Facture::TYPE_SITUATION) { // Avoid divide by 0 - if ($obj->situation_percent == 0) { + if ($obj->situation_percent == 0) { $situation_ratio = 0; } else { $prev_progress = $line->get_prev_progress($obj->rowid); // id on invoice diff --git a/htdocs/compta/localtax/class/localtax.class.php b/htdocs/compta/localtax/class/localtax.class.php index 870c123b468..570942590c2 100644 --- a/htdocs/compta/localtax/class/localtax.class.php +++ b/htdocs/compta/localtax/class/localtax.class.php @@ -87,12 +87,12 @@ class Localtax extends CommonObject $sql.= " '".$this->db->idate($this->tms)."',"; $sql.= " '".$this->db->idate($this->datep)."',"; $sql.= " '".$this->db->idate($this->datev)."',"; - $sql.= " '".$this->amount."',"; - $sql.= " '".$this->label."',"; - $sql.= " '".$this->note."',"; - $sql.= " ".($this->fk_bank <= 0 ? "NULL" : "'".$this->fk_bank."'").","; - $sql.= " '".$this->fk_user_creat."',"; - $sql.= " '".$this->fk_user_modif."'"; + $sql.= " '".$this->db->escape($this->amount)."',"; + $sql.= " '".$this->db->escape($this->label)."',"; + $sql.= " '".$this->db->escape($this->note)."',"; + $sql.= " ".($this->fk_bank <= 0 ? "NULL" : "'".$this->db->escape($this->fk_bank)."'").","; + $sql.= " '".$this->db->escape($this->fk_user_creat)."',"; + $sql.= " '".$this->db->escape($this->fk_user_modif)."'"; $sql.= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); diff --git a/htdocs/compta/localtax/clients.php b/htdocs/compta/localtax/clients.php index 40a5805f2b3..70d52c3d9d3 100644 --- a/htdocs/compta/localtax/clients.php +++ b/htdocs/compta/localtax/clients.php @@ -115,7 +115,7 @@ if ($calc==0 || $calc==1) // Calculate on invoice for goods and services if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
    '.$langs->trans("WarningDepositsNotIncluded"); $description.=$fsearch; $description.='
    ('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; - $builddate=time(); + $builddate=dol_now(); $elementcust=$langs->trans("CustomersInvoices"); $productcust=$langs->trans("Description"); @@ -133,7 +133,7 @@ if ($calc==2) // Invoice for goods, payment for services if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
    '.$langs->trans("WarningDepositsNotIncluded"); $description.=$fsearch; $description.='
    ('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; - $builddate=time(); + $builddate=dol_now(); $elementcust=$langs->trans("CustomersInvoices"); $productcust=$langs->trans("Description"); @@ -142,7 +142,7 @@ if ($calc==2) // Invoice for goods, payment for services $productsup=$langs->trans("Description"); $amountsup=$langs->trans("AmountHT"); } -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); $vatcust=$langs->transcountry($local==1?"LT1":"LT2",$mysoc->country_code); @@ -169,7 +169,7 @@ if($calc ==0 || $calc == 2) $parameters["end"] = $date_end; $parameters["direction"] = 'sell'; $parameters["type"] = 'localtax'.$local; - + // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('externalbalance')); $reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -183,7 +183,7 @@ if($calc ==0 || $calc == 2) { if(($min == 0 or ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) !=0) { - + $intra = str_replace($find,$replace,$coll->tva_intra); if(empty($intra)) { @@ -247,7 +247,7 @@ if($calc ==0 || $calc == 1){ $coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'buy'); $parameters["direction"] = 'buy'; $parameters["type"] = 'localtax'.$local; - + $reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if (is_array($coll_list)) { @@ -258,7 +258,7 @@ if($calc ==0 || $calc == 1){ { if(($min == 0 or ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) != 0) { - + $intra = str_replace($find,$replace,$coll->tva_intra); if(empty($intra)) { diff --git a/htdocs/compta/localtax/quadri_detail.php b/htdocs/compta/localtax/quadri_detail.php index a70066bdb5d..5e18c786c18 100644 --- a/htdocs/compta/localtax/quadri_detail.php +++ b/htdocs/compta/localtax/quadri_detail.php @@ -136,7 +136,7 @@ if ($conf->global->$calc==0 || $conf->global->$calc==1) // Calculate on invoice if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.='
    '.$langs->trans("DepositsAreNotIncluded"); else $description.='
    '.$langs->trans("DepositsAreIncluded"); $description.=$fsearch; - $builddate=time(); + $builddate=dol_now(); $elementcust=$langs->trans("CustomersInvoices"); $productcust=$langs->trans("ProductOrService"); @@ -164,7 +164,7 @@ if ($conf->global->$calc==2) // Invoice for goods, payment for services if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.=' '.$langs->trans("DepositsAreNotIncluded"); else $description.=' '.$langs->trans("DepositsAreIncluded"); $description.=$fsearch; - $builddate=time(); + $builddate=dol_now(); $elementcust=$langs->trans("CustomersInvoices"); $productcust=$langs->trans("ProductOrService"); @@ -177,7 +177,7 @@ if ($conf->global->$calc==2) // Invoice for goods, payment for services $vatsup=$langs->trans("VATPaid"); if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')'; } -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); if($local==1){ @@ -336,7 +336,7 @@ else if (! empty($fields['ddate_start'])) $type=1; if (! empty($fields['ddate_end'])) $type=1; - + print ''; // Ref @@ -499,7 +499,7 @@ else if (! empty($fields['ddate_start'])) $type=1; if (! empty($fields['ddate_end'])) $type=1; - + print ''; // Ref diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index 7a494113090..866529fd5dd 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -251,7 +251,7 @@ if (empty($reshook)) $paiement->datepaye = $datepaye; $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching - $paiement->paiementid = dol_getIdFromCode($db,GETPOST('paiementcode'),'c_paiement'); + $paiement->paiementid = dol_getIdFromCode($db,GETPOST('paiementcode'),'c_paiement','code','id',1); $paiement->num_paiement = GETPOST('num_paiement'); $paiement->note = GETPOST('comment'); @@ -526,21 +526,19 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie * List of unpaid invoices */ - $sql = 'SELECT f.rowid as facid, f.facnumber, f.total_ttc, f.multicurrency_code, f.multicurrency_total_ttc, f.type, '; + $sql = 'SELECT f.rowid as facid, f.facnumber, f.total_ttc, f.multicurrency_code, f.multicurrency_total_ttc, f.type,'; $sql.= ' f.datef as df, f.fk_soc as socid'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f'; - - if(!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS)) { - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON (f.fk_soc = s.rowid)'; - } - - $sql.= ' WHERE f.entity = '.$conf->entity; + $sql.= ' WHERE f.entity IN ('.getEntity('facture', $conf->entity).')'; $sql.= ' AND (f.fk_soc = '.$facture->socid; - + // Can pay invoices of all child of parent company if(!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS) && !empty($facture->thirdparty->parent)) { $sql.= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->parent.')'; } - + // Can pay invoices of all child of myself + if(!empty($conf->global->FACTURE_PAYMENTS_ON_SUBSIDIARY_COMPANIES)){ + $sql.= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->id.')'; + } $sql.= ') AND f.paye = 0'; $sql.= ' AND f.fk_statut = 1'; // Statut=0 => not validated, Statut=2 => canceled if ($facture->type != 2) @@ -831,7 +829,8 @@ if (! GETPOST('action','aZ09')) $sql.=', f.rowid as facid, c.libelle as paiement_type, p.num_paiement'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p, '.MAIN_DB_PREFIX.'facture as f, '.MAIN_DB_PREFIX.'c_paiement as c'; $sql.= ' WHERE p.fk_facture = f.rowid AND p.fk_paiement = c.id'; - $sql.= ' AND f.entity = '.$conf->entity; + $sql.= ' AND f.entity IN (' . getEntity('facture').')'; + $sql.= ' AND c.entity IN (' . getEntity('c_paiement').')'; if ($socid) { $sql.= ' AND f.fk_soc = '.$socid; diff --git a/htdocs/compta/paiement/avalider.php b/htdocs/compta/paiement/avalider.php index 370fbdfdd05..4c7fafe4429 100644 --- a/htdocs/compta/paiement/avalider.php +++ b/htdocs/compta/paiement/avalider.php @@ -71,7 +71,8 @@ if ($socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON pf.fk_facture = f.rowid"; } $sql.= " WHERE p.fk_paiement = c.id"; -$sql.= " AND p.entity = ".$conf->entity; +$sql.= " AND p.entity = " . $conf->entity; +$sql.= " AND c.entity = " . getEntity('c_paiement'); if ($socid) { $sql.= " AND f.fk_soc = ".$socid; diff --git a/htdocs/compta/paiement/card.php b/htdocs/compta/paiement/card.php index 523d5256816..da38e9fb47a 100644 --- a/htdocs/compta/paiement/card.php +++ b/htdocs/compta/paiement/card.php @@ -60,7 +60,7 @@ if ($action == 'setnote' && $user->rights->facture->paiement) $db->begin(); $object->fetch($id); - $result = $object->update_note(GETPOST('note')); + $result = $object->update_note(GETPOST('note','none')); if ($result > 0) { $db->commit(); diff --git a/htdocs/compta/paiement/cheque/class/remisecheque.class.php b/htdocs/compta/paiement/cheque/class/remisecheque.class.php index 808d2cbb00b..3458e6bc82a 100644 --- a/htdocs/compta/paiement/cheque/class/remisecheque.class.php +++ b/htdocs/compta/paiement/cheque/class/remisecheque.class.php @@ -36,7 +36,7 @@ class RemiseCheque extends CommonObject public $element='chequereceipt'; public $table_element='bordereau_cheque'; public $picto = 'payment'; - + var $num; var $intitule; //! Numero d'erreur Plage 1024-1279 @@ -345,7 +345,7 @@ class RemiseCheque extends CommonObject $this->errno = 0; $this->db->begin(); - + $numref = $this->getNextNumRef(); if ($this->errno == 0 && $numref) @@ -481,10 +481,10 @@ class RemiseCheque extends CommonObject /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ function load_board($user) { @@ -533,6 +533,45 @@ class RemiseCheque extends CommonObject } + /** + * Charge indicateurs this->nb de tableau de bord + * + * @return int <0 if ko, >0 if ok + */ + function load_state_board() + { + global $user; + + if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe + + $sql = "SELECT count(b.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql.= " AND b.fk_type = 'CHQ'"; + $sql.= " AND b.amount > 0"; + + $resql=$this->db->query($sql); + if ($resql) + { + + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["cheques"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } + + /** * Build document * @@ -716,7 +755,7 @@ class RemiseCheque extends CommonObject * * @param int $bank_id Id of bank transaction line concerned * @param date $rejection_date Date to use on the negative payment - * @return int Id of negative payment line created + * @return int Id of negative payment line created */ function rejectCheck($bank_id, $rejection_date) { @@ -727,19 +766,19 @@ class RemiseCheque extends CommonObject $bankline = new AccountLine($db); $bankline->fetch($bank_id); - + /* Conciliation is allowed because when check is returned, a new line is created onto bank transaction log. if ($bankline->rappro) { $this->error='ActionRefusedLineAlreadyConciliated'; return -1; }*/ - + $this->db->begin(); - + // Not conciliated, we can delete it - //$bankline->delete($user); // We delete - + //$bankline->delete($user); // We delete + $bankaccount = $payment->fk_account; // Get invoices list to reopen them @@ -753,7 +792,7 @@ class RemiseCheque extends CommonObject $rejectedPayment = new Paiement($db); $rejectedPayment->amounts = array(); $rejectedPayment->datepaye = $rejection_date; - $rejectedPayment->paiementid = dol_getIdFromCode($this->db, 'CHQ', 'c_paiement'); + $rejectedPayment->paiementid = dol_getIdFromCode($this->db, 'CHQ', 'c_paiement','code','id',1); $rejectedPayment->num_paiement = $payment->numero; while($obj = $db->fetch_object($resql)) diff --git a/htdocs/compta/paiement/cheque/list.php b/htdocs/compta/paiement/cheque/list.php index d08b6c734cc..76c52215281 100644 --- a/htdocs/compta/paiement/cheque/list.php +++ b/htdocs/compta/paiement/cheque/list.php @@ -203,7 +203,7 @@ if ($resql) // Bank print ''; - if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.$objp->label.''; + if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.$objp->label.''; else print ' '; print ''; diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php index 7c5b99e2945..10d1f0fa884 100644 --- a/htdocs/compta/paiement/class/paiement.class.php +++ b/htdocs/compta/paiement/class/paiement.class.php @@ -93,6 +93,7 @@ class Paiement extends CommonObject $sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement as p'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid '; $sql.= ' WHERE p.fk_paiement = c.id'; + $sql.= ' AND c.entity IN (' . getEntity('c_paiement').')'; if ($id > 0) $sql.= ' AND p.rowid = '.$id; else if ($ref) @@ -337,6 +338,24 @@ class Paiement extends CommonObject $error++; } } + } + + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $invoice->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $ret = $invoice->fetch($id); // Reload to get new records + + $result = $invoice->generateDocument($invoice->modelpdf, $outputlangs); + if ($result < 0) { + setEventMessages($invoice->error, $invoice->errors, 'errors'); + $error++; + } + } } } diff --git a/htdocs/compta/paiement/list.php b/htdocs/compta/paiement/list.php index 2d73c2b1c6f..b7b0b0489e2 100644 --- a/htdocs/compta/paiement/list.php +++ b/htdocs/compta/paiement/list.php @@ -119,7 +119,8 @@ if (GETPOST("orphelins")) $sql.= " ".MAIN_DB_PREFIX."c_paiement as c)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; $sql.= " WHERE p.fk_paiement = c.id"; - $sql.= " AND p.entity = ".$conf->entity; + $sql.= " AND p.entity = " . $conf->entity; + $sql.= " AND c.entity = " . getEntity('c_paiement'); $sql.= " AND pf.fk_facture IS NULL"; // Add where from hooks $parameters=array(); @@ -150,7 +151,8 @@ else $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; } $sql.= " WHERE p.fk_paiement = c.id"; - $sql.= " AND p.entity = ".$conf->entity; + $sql.= " AND p.entity = " . $conf->entity; + $sql.= " AND c.entity = " . getEntity('c_paiement'); if (! $user->rights->societe->client->voir && ! $socid) { $sql.= " AND sc.fk_user = " .$user->id; @@ -331,7 +333,7 @@ if ($resql) $accountstatic->label=$objp->blabel; $accountstatic->number=$objp->number; $accountstatic->account_number=$objp->account_number; - + $accountingjournal = new AccountingJournal($db); $accountingjournal->fetch($objp->accountancy_journal); $accountstatic->accountancy_journal = $accountingjournal->code; diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php index bd262eaa675..e966eba4a47 100644 --- a/htdocs/compta/paiement_charge.php +++ b/htdocs/compta/paiement_charge.php @@ -60,18 +60,21 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes if (! $_POST["paiementtype"] > 0) { - $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("PaymentMode")); + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("PaymentMode")), null, 'errors'); $error++; + $action = 'create'; } if ($datepaye == '') { - $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("Date")); + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("Date")), null, 'errors'); $error++; + $action = 'create'; } if (! empty($conf->banque->enabled) && ! $_POST["accountid"] > 0) { - $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("AccountToCredit")); + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("AccountToCredit")), null, 'errors'); $error++; + $action = 'create'; } if (! $error) @@ -91,7 +94,8 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes if (count($amounts) <= 0) { $error++; - $errmsg='ErrorNoPaymentDefined'; + setEventMessages($langs->trans("ErrorNoPaymentDefined"), null, 'errors'); + $action='create'; } if (! $error) @@ -112,18 +116,20 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes $paymentid = $paiement->create($user, (GETPOST('closepaidcontrib')=='on'?1:0)); if ($paymentid < 0) { - $errmsg=$paiement->error; - $error++; + $error++; + setEventMessages($paiement->error, null, 'errors'); + $action='create'; } } if (! $error) { - $result=$paiement->addPaymentToBank($user,'payment_sc','(SocialContributionPayment)',$_POST['accountid'],'',''); - if (! $result > 0) + $result=$paiement->addPaymentToBank($user,'payment_sc','(SocialContributionPayment)', GETPOST('accountid','int'),'',''); + if (! ($result > 0)) { - $errmsg=$paiement->error; - $error++; + $error++; + setEventMessages($paiement->error, null, 'errors'); + $action='create'; } } @@ -141,7 +147,6 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes } } - $_GET["action"]='create'; } @@ -164,6 +169,20 @@ if ($action == 'create') $charge->paiementtype=$charge->mode_reglement_id?$charge->mode_reglement_id:$charge->paiementtype; $total = $charge->amount; + if (! empty($conf->use_javascript_ajax)) + { + print "\n".''."\n"; + } print load_fiche_titre($langs->trans("DoPayment")); print "
    \n"; @@ -183,14 +202,12 @@ if ($action == 'create') print ''; - print ""; - - print ''; + print ''; print '\n"; print '\n"; print '\n"; - print '\n"; - print ''; + /*print '\n"; + print '';*/ $sql = "SELECT sum(p.amount) as total"; $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as p"; @@ -202,12 +219,8 @@ if ($action == 'create') $sumpaid = $obj->total; $db->free(); } - print ''; - print ''; - - print ''; - print "'; - print ''; + /*print ''; + print '';*/ print ''; @@ -289,7 +302,12 @@ if ($action == 'create') if ($sumpaid < $objp->amount) { $namef = "amount_".$objp->id; - print ''; + $nameRemain = "remain_".$objp->id; + if (!empty($conf->use_javascript_ajax)) + print img_picto("Auto fill",'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->amount - $sumpaid)."'"); + $remaintopay=$objp->amount - $sumpaid; + print ''; + print ''; } else { diff --git a/htdocs/compta/payment_sc/card.php b/htdocs/compta/payment_sc/card.php index 45762ed95bb..ea9bc5af42a 100644 --- a/htdocs/compta/payment_sc/card.php +++ b/htdocs/compta/payment_sc/card.php @@ -44,10 +44,10 @@ if ($user->societe_id) $socid=$user->societe_id; // TODO ajouter regle pour restreindre acces paiement //$result = restrictedArea($user, 'facture', $id,''); -$paiement = new PaymentSocialContribution($db); -if ($id > 0) +$object = new PaymentSocialContribution($db); +if ($id > 0) { - $result=$paiement->fetch($id); + $result=$object->fetch($id); if (! $result) dol_print_error($db,'Failed to get payment id '.$id); } @@ -61,7 +61,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->tax->char { $db->begin(); - $result = $paiement->delete($user); + $result = $object->delete($user); if ($result > 0) { $db->commit(); @@ -70,7 +70,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->tax->char } else { - setEventMessages($paiement->error, $paiement->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); } } @@ -80,8 +80,8 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->tax->char { $db->begin(); - $result=$paiement->valide(); - + $result=$object->valide(); + if ($result > 0) { $db->commit(); @@ -103,12 +103,12 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->tax->char } } - header('Location: card.php?id='.$paiement->id); + header('Location: card.php?id='.$object->id); exit; } else { - setEventMessages($paiement->error, $paiement->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); } } @@ -137,15 +137,15 @@ $h++; */ -dol_fiche_head($head, $hselected, $langs->trans("PaymentSocialContribution"), 0, 'payment'); +dol_fiche_head($head, $hselected, $langs->trans("PaymentSocialContribution"), -1, 'payment'); /* * Deletion confirmation of payment */ if ($action == 'delete') { - print $form->formconfirm('card.php?id='.$paiement->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete','',0,2); - + print $form->formconfirm('card.php?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete','',0,2); + } /* @@ -154,41 +154,49 @@ if ($action == 'delete') if ($action == 'valide') { $facid = $_GET['facid']; - print $form->formconfirm('card.php?id='.$paiement->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide','',0,2); - + print $form->formconfirm('card.php?id='.$object->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide','',0,2); + } +$linkback = '' . $langs->trans("BackToList") . ''; + +dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'id', ''); + + +print '
    '; +print '
    '; + print '
    ".$langs->trans("SocialContribution")."
    '.$langs->trans("Ref").''.$chid.'
    '.$langs->trans("Ref").''.$chid.'
    '.$langs->trans("Type")."".$charge->type_libelle."
    '.$langs->trans("Period")."".dol_print_date($charge->periode,'day')."
    '.$langs->trans("Label").''.$charge->lib."
    '.$langs->trans("DateDue")."".dol_print_date($charge->date_ech,'day')."
    '.$langs->trans("Amount")."".price($charge->amount,0,$outputlangs,1,-1,-1,$conf->currency).'
    '.$langs->trans("DateDue")."".dol_print_date($charge->date_ech,'day')."
    '.$langs->trans("Amount")."".price($charge->amount,0,$outputlangs,1,-1,-1,$conf->currency).'
    '.$langs->trans("AlreadyPaid").''.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
    '.$langs->trans("RemainderToPay").''.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
    ".$langs->trans("Payment").'
    '.$langs->trans("AlreadyPaid").''.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
    '.$langs->trans("RemainderToPay").''.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
    '.$langs->trans("Date").''; $datepaye = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); @@ -266,7 +279,7 @@ if ($action == 'create') { $objp = $charge; - + print '
    '; // Ref -print ''; +/*print ''; print ''; +print $form->showrefnav($object,'id','',1,'rowid','id'); +print '';*/ // Date -print ''; +print ''; // Mode -print ''; +print ''; // Numero -print ''; +print ''; // Montant -print ''; +print ''; // Note -print ''; +print ''; // Bank account if (! empty($conf->banque->enabled)) { - if ($paiement->bank_account) + if ($object->bank_account) { $bankline=new AccountLine($db); - $bankline->fetch($paiement->bank_line); + $bankline->fetch($object->bank_line); print ''; print ''; @@ -201,6 +209,10 @@ if (! empty($conf->banque->enabled)) print '
    '.$langs->trans('Ref').'
    '.$langs->trans('Ref').''; -print $form->showrefnav($paiement,'id','',1,'rowid','id'); -print '
    '.$langs->trans('Date').''.dol_print_date($paiement->datep,'day').'
    '.$langs->trans('Date').''.dol_print_date($object->datep,'day').'
    '.$langs->trans('Mode').''.$langs->trans("PaymentType".$paiement->type_code).'
    '.$langs->trans('Mode').''.$langs->trans("PaymentType".$object->type_code).'
    '.$langs->trans('Numero').''.$paiement->num_paiement.'
    '.$langs->trans('Numero').''.$object->num_paiement.'
    '.$langs->trans('Amount').''.price($paiement->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).'
    '.$langs->trans('Amount').''.price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).'
    '.$langs->trans('Note').''.nl2br($paiement->note).'
    '.$langs->trans('Note').''.nl2br($object->note).'
    '.$langs->trans('BankTransactionLine').'
    '; +print '
    '; + +dol_fiche_end(); + /* * List of social contributions payed @@ -211,7 +223,7 @@ $sql = 'SELECT f.rowid as scid, f.libelle, f.paye, f.amount as sc_amount, pf.amo $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementcharge as pf,'.MAIN_DB_PREFIX.'chargesociales as f, '.MAIN_DB_PREFIX.'c_chargesociales as pc'; $sql.= ' WHERE pf.fk_charge = f.rowid AND f.fk_type = pc.id'; $sql.= ' AND f.entity = '.$conf->entity; -$sql.= ' AND pf.rowid = '.$paiement->id; +$sql.= ' AND pf.rowid = '.$object->id; dol_syslog("compta/payment_sc/card.php", LOG_DEBUG); $resql=$db->query($sql); @@ -239,7 +251,7 @@ if ($resql) { $objp = $db->fetch_object($resql); - + print ''; // Ref print ''; @@ -268,7 +280,7 @@ if ($resql) $i++; } } - + print "\n"; $db->free($resql); @@ -278,7 +290,6 @@ else dol_print_error($db); } -dol_fiche_end(); /* @@ -289,7 +300,7 @@ print '
    '; /* if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) { - if ($user->societe_id == 0 && $paiement->statut == 0 && $_GET['action'] == '') + if ($user->societe_id == 0 && $object->statut == 0 && $_GET['action'] == '') { if ($user->rights->facture->paiement) { @@ -299,7 +310,7 @@ if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) } */ -if ($_GET['action'] == '') +if ($action == '') { if ($user->rights->tax->charges->supprimer) { diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index a3d50d58143..188b0236e5f 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -42,417 +42,418 @@ class BonPrelevement extends CommonObject public $table_element='prelevement_bons'; public $picto = 'payment'; - var $date_echeance; - var $raison_sociale; - var $reference_remise; - var $emetteur_code_guichet; - var $emetteur_numero_compte; - var $emetteur_code_banque; - var $emetteur_number_key; + var $date_echeance; + var $raison_sociale; + var $reference_remise; + var $emetteur_code_guichet; + var $emetteur_numero_compte; + var $emetteur_code_banque; + var $emetteur_number_key; - var $emetteur_iban; - var $emetteur_bic; - var $emetteur_ics; + var $emetteur_iban; + var $emetteur_bic; + var $emetteur_ics; - var $total; - var $_fetched; - var $statut; // 0-Wait, 1-Trans, 2-Done - var $labelstatut=array(); + var $total; + var $_fetched; + var $statut; // 0-Wait, 1-Trans, 2-Done + var $labelstatut=array(); - var $invoice_in_error=array(); + var $invoice_in_error=array(); + var $thirdparty_in_error=array(); - /** - * Constructor - * - * @param DoliDB $db Database handler - * @param string $filename Filename of withdraw receipt - */ - function __construct($db, $filename='') - { - global $conf,$langs; + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $filename Filename of withdraw receipt + */ + function __construct($db, $filename='') + { + global $conf,$langs; - $error = 0; - $this->db = $db; + $error = 0; + $this->db = $db; - $this->filename=$filename; + $this->filename=$filename; - $this->date_echeance = time(); - $this->raison_sociale = ""; - $this->reference_remise = ""; + $this->date_echeance = time(); + $this->raison_sociale = ""; + $this->reference_remise = ""; - $this->emetteur_code_guichet = ""; - $this->emetteur_numero_compte = ""; - $this->emetteur_code_banque = ""; - $this->emetteur_number_key = ""; + $this->emetteur_code_guichet = ""; + $this->emetteur_numero_compte = ""; + $this->emetteur_code_banque = ""; + $this->emetteur_number_key = ""; - $this->emetteur_iban = ""; - $this->emetteur_bic = ""; - $this->emetteur_ics = ""; + $this->emetteur_iban = ""; + $this->emetteur_bic = ""; + $this->emetteur_ics = ""; - $this->factures = array(); + $this->factures = array(); - $this->methodes_trans = array(); + $this->methodes_trans = array(); - $this->methodes_trans[0] = "Internet"; + $this->methodes_trans[0] = "Internet"; - $this->_fetched = 0; + $this->_fetched = 0; - $langs->load("withdrawals"); - $this->labelstatut[0]=$langs->trans("StatusWaiting"); - $this->labelstatut[1]=$langs->trans("StatusTrans"); - $this->labelstatut[2]=$langs->trans("StatusCredited"); + $langs->load("withdrawals"); + $this->labelstatut[0]=$langs->trans("StatusWaiting"); + $this->labelstatut[1]=$langs->trans("StatusTrans"); + $this->labelstatut[2]=$langs->trans("StatusCredited"); - return 1; - } + return 1; + } - /** - * Add invoice to withdrawal - * - * @param int $facture_id id invoice to add - * @param int $client_id id invoice customer - * @param string $client_nom customer name - * @param int $amount amount of invoice - * @param string $code_banque code of bank withdrawal - * @param string $code_guichet code of bank's office - * @param string $number bank account number - * @param string $number_key number key of account number - * @return int >0 if OK, <0 if KO - */ - function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) - { - $result = 0; - $line_id = 0; + /** + * Add invoice to withdrawal + * + * @param int $facture_id id invoice to add + * @param int $client_id id invoice customer + * @param string $client_nom customer name + * @param int $amount amount of invoice + * @param string $code_banque code of bank withdrawal + * @param string $code_guichet code of bank's office + * @param string $number bank account number + * @param string $number_key number key of account number + * @return int >0 if OK, <0 if KO + */ + function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) + { + $result = 0; + $line_id = 0; - $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key); + $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key); - if ($result == 0) - { - if ($line_id > 0) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture ("; - $sql.= "fk_facture"; - $sql.= ",fk_prelevement_lignes"; - $sql.= ") VALUES ("; - $sql.= $facture_id; - $sql.= ", ".$line_id; - $sql.= ")"; + if ($result == 0) + { + if ($line_id > 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture ("; + $sql.= "fk_facture"; + $sql.= ",fk_prelevement_lignes"; + $sql.= ") VALUES ("; + $sql.= $facture_id; + $sql.= ", ".$line_id; + $sql.= ")"; - if ($this->db->query($sql)) - { - $result = 0; - } - else - { - $result = -1; - dol_syslog(get_class($this)."::AddFacture Erreur $result"); - } - } - else - { - $result = -2; - dol_syslog(get_class($this)."::AddFacture Erreur $result"); - } - } - else - { - $result = -3; - dol_syslog(get_class($this)."::AddFacture Erreur $result"); - } + if ($this->db->query($sql)) + { + $result = 0; + } + else + { + $result = -1; + dol_syslog(get_class($this)."::AddFacture Erreur $result"); + } + } + else + { + $result = -2; + dol_syslog(get_class($this)."::AddFacture Erreur $result"); + } + } + else + { + $result = -3; + dol_syslog(get_class($this)."::AddFacture Erreur $result"); + } - return $result; + return $result; - } + } - /** - * Add line to withdrawal - * - * @param int $line_id id line to add - * @param int $client_id id invoice customer - * @param string $client_nom customer name - * @param int $amount amount of invoice - * @param string $code_banque code of bank withdrawal - * @param string $code_guichet code of bank's office - * @param string $number bank account number - * @param string $number_key number key of account number - * @return int >0 if OK, <0 if KO - */ - function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) - { - $result = -1; - $concat = 0; + /** + * Add line to withdrawal + * + * @param int $line_id id line to add + * @param int $client_id id invoice customer + * @param string $client_nom customer name + * @param int $amount amount of invoice + * @param string $code_banque code of bank withdrawal + * @param string $code_guichet code of bank's office + * @param string $number bank account number + * @param string $number_key number key of account number + * @return int >0 if OK, <0 if KO + */ + function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) + { + $result = -1; + $concat = 0; - if ($concat == 1) - { - /* + if ($concat == 1) + { + /* * We aggregate the lines */ - $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_lignes"; - $sql.= " WHERE fk_prelevement_bons = ".$this->id; - $sql.= " AND fk_soc =".$client_id; - $sql.= " AND code_banque ='".$code_banque."'"; - $sql.= " AND code_guichet ='".$code_guichet."'"; - $sql.= " AND number ='".$number."'"; + $sql = "SELECT rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_lignes"; + $sql.= " WHERE fk_prelevement_bons = ".$this->id; + $sql.= " AND fk_soc =".$client_id; + $sql.= " AND code_banque ='".$code_banque."'"; + $sql.= " AND code_guichet ='".$code_guichet."'"; + $sql.= " AND number ='".$number."'"; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - } - else - { - $result = -1; - } - } - else - { - /* + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + } + else + { + $result = -1; + } + } + else + { + /* * No aggregate */ - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes ("; - $sql.= "fk_prelevement_bons"; - $sql.= ", fk_soc"; - $sql.= ", client_nom"; - $sql.= ", amount"; - $sql.= ", code_banque"; - $sql.= ", code_guichet"; - $sql.= ", number"; - $sql.= ", cle_rib"; - $sql.= ") VALUES ("; - $sql.= $this->id; - $sql.= ", ".$client_id; - $sql.= ", '".$this->db->escape($client_nom)."'"; - $sql.= ", '".price2num($amount)."'"; - $sql.= ", '".$code_banque."'"; - $sql.= ", '".$code_guichet."'"; - $sql.= ", '".$number."'"; - $sql.= ", '".$number_key."'"; - $sql.= ")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes ("; + $sql.= "fk_prelevement_bons"; + $sql.= ", fk_soc"; + $sql.= ", client_nom"; + $sql.= ", amount"; + $sql.= ", code_banque"; + $sql.= ", code_guichet"; + $sql.= ", number"; + $sql.= ", cle_rib"; + $sql.= ") VALUES ("; + $sql.= $this->id; + $sql.= ", ".$client_id; + $sql.= ", '".$this->db->escape($client_nom)."'"; + $sql.= ", '".price2num($amount)."'"; + $sql.= ", '".$code_banque."'"; + $sql.= ", '".$code_guichet."'"; + $sql.= ", '".$number."'"; + $sql.= ", '".$number_key."'"; + $sql.= ")"; - if ($this->db->query($sql)) - { - $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes"); - $result = 0; - } - else - { - dol_syslog(get_class($this)."::addline Error -2"); - $result = -2; - } + if ($this->db->query($sql)) + { + $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes"); + $result = 0; + } + else + { + dol_syslog(get_class($this)."::addline Error -2"); + $result = -2; + } - } + } - return $result; - } + return $result; + } - /** - * Return error string - * - * @param int $error Id of error - * @return string Error string - */ - function getErrorString($error) - { - global $langs; + /** + * Return error string + * + * @param int $error Id of error + * @return string Error string + */ + function getErrorString($error) + { + global $langs; - $errors = array(); + $errors = array(); - $errors[1027] = $langs->trans("DateInvalid"); + $errors[1027] = $langs->trans("DateInvalid"); - return $errors[abs($error)]; - } + return $errors[abs($error)]; + } - /** - * Get object and lines from database - * - * @param int $rowid Id of object to load - * @param string $ref Ref of direct debit - * @return int >0 if OK, <0 if KO - */ - function fetch($rowid, $ref='') - { - global $conf; + /** + * Get object and lines from database + * + * @param int $rowid Id of object to load + * @param string $ref Ref of direct debit + * @return int >0 if OK, <0 if KO + */ + function fetch($rowid, $ref='') + { + global $conf; - $sql = "SELECT p.rowid, p.ref, p.amount, p.note"; - $sql.= ", p.datec as dc"; - $sql.= ", p.date_trans as date_trans"; - $sql.= ", p.method_trans, p.fk_user_trans"; - $sql.= ", p.date_credit as date_credit"; - $sql.= ", p.fk_user_credit"; - $sql.= ", p.statut"; - $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; - $sql.= " WHERE p.entity = ".$conf->entity; - if ($rowid > 0) $sql.= " AND p.rowid = ".$rowid; - else $sql.= " AND p.ref = '".$this->db->escape($ref)."'"; + $sql = "SELECT p.rowid, p.ref, p.amount, p.note"; + $sql.= ", p.datec as dc"; + $sql.= ", p.date_trans as date_trans"; + $sql.= ", p.method_trans, p.fk_user_trans"; + $sql.= ", p.date_credit as date_credit"; + $sql.= ", p.fk_user_credit"; + $sql.= ", p.statut"; + $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; + $sql.= " WHERE p.entity = ".$conf->entity; + if ($rowid > 0) $sql.= " AND p.rowid = ".$rowid; + else $sql.= " AND p.ref = '".$this->db->escape($ref)."'"; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; - $this->ref = $obj->ref; - $this->amount = $obj->amount; - $this->note = $obj->note; - $this->datec = $this->db->jdate($obj->dc); + $this->id = $obj->rowid; + $this->ref = $obj->ref; + $this->amount = $obj->amount; + $this->note = $obj->note; + $this->datec = $this->db->jdate($obj->dc); - $this->date_trans = $this->db->jdate($obj->date_trans); - $this->method_trans = $obj->method_trans; - $this->user_trans = $obj->fk_user_trans; + $this->date_trans = $this->db->jdate($obj->date_trans); + $this->method_trans = $obj->method_trans; + $this->user_trans = $obj->fk_user_trans; - $this->date_credit = $this->db->jdate($obj->date_credit); - $this->user_credit = $obj->fk_user_credit; + $this->date_credit = $this->db->jdate($obj->date_credit); + $this->user_credit = $obj->fk_user_credit; - $this->statut = $obj->statut; + $this->statut = $obj->statut; - $this->_fetched = 1; + $this->_fetched = 1; - return 0; - } - else - { - dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee"); - return -1; - } - } - else - { - return -2; - } - } + return 0; + } + else + { + dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee"); + return -1; + } + } + else + { + return -2; + } + } - /** - * Set credite and set status of linked invoices. Still used ?? - * - * @return int <0 if KO, >=0 if OK - */ - function set_credite() - { - global $user,$conf; + /** + * Set credite and set status of linked invoices. Still used ?? + * + * @return int <0 if KO, >=0 if OK + */ + function set_credite() + { + global $user,$conf; - $error = 0; + $error = 0; - if ($this->db->begin()) - { - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; - $sql.= " SET statut = 1"; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; + if ($this->db->begin()) + { + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; + $sql.= " SET statut = 1"; + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; - $result=$this->db->query($sql); - if (! $result) - { - dol_syslog(get_class($this)."::set_credite Erreur 1"); - $error++; - } + $result=$this->db->query($sql); + if (! $result) + { + dol_syslog(get_class($this)."::set_credite Erreur 1"); + $error++; + } - if (! $error) - { - $facs = array(); - $facs = $this->getListInvoices(); + if (! $error) + { + $facs = array(); + $facs = $this->getListInvoices(); - $num=count($facs); - for ($i = 0; $i < $num; $i++) - { - /* Tag invoice as payed */ - dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]); - $fac = new Facture($this->db); - $fac->fetch($facs[$i]); - $result = $fac->set_paid($user); - } - } + $num=count($facs); + for ($i = 0; $i < $num; $i++) + { + /* Tag invoice as payed */ + dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]); + $fac = new Facture($this->db); + $fac->fetch($facs[$i]); + $result = $fac->set_paid($user); + } + } - if (! $error) - { - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; - $sql.= " SET statut = 2"; - $sql.= " WHERE fk_prelevement_bons = ".$this->id; + if (! $error) + { + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; + $sql.= " SET statut = 2"; + $sql.= " WHERE fk_prelevement_bons = ".$this->id; - if (! $this->db->query($sql)) - { - dol_syslog(get_class($this)."::set_credite Erreur 1"); - $error++; - } - } + if (! $this->db->query($sql)) + { + dol_syslog(get_class($this)."::set_credite Erreur 1"); + $error++; + } + } - /* + /* * End of procedure */ - if (! $error) - { - $this->db->commit(); - return 0; - } - else - { - $this->db->rollback(); - dol_syslog(get_class($this)."::set_credite ROLLBACK "); + if (! $error) + { + $this->db->commit(); + return 0; + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::set_credite ROLLBACK "); - return -1; - } - } - else - { - dol_syslog(get_class($this)."::set_credite Ouverture transaction SQL impossible "); - return -2; - } - } + return -1; + } + } + else + { + dol_syslog(get_class($this)."::set_credite Ouverture transaction SQL impossible "); + return -2; + } + } - /** - * Set direct debit order to "credited" status. - * - * @param User $user Id of user - * @param int $date date of action - * @return int >0 if OK, <0 if KO - */ - function set_infocredit($user, $date) - { - global $conf,$langs; + /** + * Set direct debit order to "credited" status. + * + * @param User $user Id of user + * @param int $date date of action + * @return int >0 if OK, <0 if KO + */ + function set_infocredit($user, $date) + { + global $conf,$langs; - $error = 0; + $error = 0; - if ($this->_fetched == 1) - { - if ($date >= $this->date_trans) - { - if ($this->db->begin()) - { - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; - $sql.= " SET fk_user_credit = ".$user->id; - $sql.= ", statut = 2"; - $sql.= ", date_credit = '".$this->db->idate($date)."'"; - $sql.= " WHERE rowid=".$this->id; - $sql.= " AND entity = ".$conf->entity; - $sql.= " AND statut = 1"; + if ($this->_fetched == 1) + { + if ($date >= $this->date_trans) + { + if ($this->db->begin()) + { + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; + $sql.= " SET fk_user_credit = ".$user->id; + $sql.= ", statut = 2"; + $sql.= ", date_credit = '".$this->db->idate($date)."'"; + $sql.= " WHERE rowid=".$this->id; + $sql.= " AND entity = ".$conf->entity; + $sql.= " AND statut = 1"; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) + { - $langs->load('withdrawals'); - $subject = $langs->trans("InfoCreditSubject", $this->ref); - $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date,'dayhour')); + $langs->load('withdrawals'); + $subject = $langs->trans("InfoCreditSubject", $this->ref); + $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date,'dayhour')); - //Add payment of withdrawal into bank - $bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT; - $facs = array(); - $amounts = array(); - $amountsperthirdparty = array(); + //Add payment of withdrawal into bank + $bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT; + $facs = array(); + $amounts = array(); + $amountsperthirdparty = array(); - $facs = $this->getListInvoices(1); + $facs = $this->getListInvoices(1); - // Loop on each invoice. $facs=array(0=>id, 1=>amount requested) - $num=count($facs); - for ($i = 0; $i < $num; $i++) - { - $fac = new Facture($this->db); - $fac->fetch($facs[$i][0]); - $amounts[$fac->id] = $facs[$i][1]; - $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1]; + // Loop on each invoice. $facs=array(0=>id, 1=>amount requested) + $num=count($facs); + for ($i = 0; $i < $num; $i++) + { + $fac = new Facture($this->db); + $fac->fetch($facs[$i][0]); + $amounts[$fac->id] = $facs[$i][1]; + $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1]; $totalpaye = $fac->getSommePaiement(); $totalcreditnotes = $fac->getSumCreditNotesUsed(); @@ -462,462 +463,477 @@ class BonPrelevement extends CommonObject if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) { $result = $fac->set_paid($user); } - } + } - // Make one payment per customer - foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts) - { - $paiement = new Paiement($this->db); - $paiement->datepaye = $date; - $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice - $paiement->paiementid = 3; // - $paiement->num_paiement = $this->ref; // Set ref of direct debit note + // Make one payment per customer + foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts) + { + $paiement = new Paiement($this->db); + $paiement->datepaye = $date; + $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice + $paiement->paiementid = 3; // + $paiement->num_paiement = $this->ref; // Set ref of direct debit note $paiement->id_prelevement = $this->id; - $paiement_id = $paiement->create($user); - if ($paiement_id < 0) - { - dol_syslog(get_class($this)."::set_infocredit AddPayment Error"); - $error++; - } - else - { - $result=$paiement->addPaymentToBank($user,'payment','(WithdrawalPayment)',$bankaccount,'',''); - if ($result < 0) - { - dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error"); - $error++; - } - } - //var_dump($paiement->amounts); - //var_dump($thirdpartyid); - //var_dump($cursoramounts); - } + $paiement_id = $paiement->create($user); + if ($paiement_id < 0) + { + dol_syslog(get_class($this)."::set_infocredit AddPayment Error"); + $error++; + } + else + { + $result=$paiement->addPaymentToBank($user,'payment','(WithdrawalPayment)',$bankaccount,'',''); + if ($result < 0) + { + dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error"); + $error++; + } + } + //var_dump($paiement->amounts); + //var_dump($thirdpartyid); + //var_dump($cursoramounts); + } // Update withdrawal line - // TODO: Translate to ligneprelevement.class.php - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; - $sql.= " SET statut = 2"; - $sql.= " WHERE fk_prelevement_bons = ".$this->id; + // TODO: Translate to ligneprelevement.class.php + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; + $sql.= " SET statut = 2"; + $sql.= " WHERE fk_prelevement_bons = ".$this->id; - if (! $this->db->query($sql)) - { - dol_syslog(get_class($this)."::set_infocredit Update lines Error"); - $error++; - } + if (! $this->db->query($sql)) + { + dol_syslog(get_class($this)."::set_infocredit Update lines Error"); + $error++; + } - } - else - { - dol_syslog(get_class($this)."::set_infocredit Update Bons Error"); - $error++; - } + } + else + { + dol_syslog(get_class($this)."::set_infocredit Update Bons Error"); + $error++; + } - /* + /* * End of procedure */ - if ($error == 0) - { - $this->db->commit(); - return 0; - } - else - { - $this->db->rollback(); - dol_syslog("bon-prelevment::set_infocredit ROLLBACK "); - return -1; - } - } - else - { - dol_syslog(get_class($this)."::set_infocredit 1025 Open SQL transaction impossible "); - return -1025; - } - } - else - { - dol_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans "); - return -1027; - } - } - else - { - return -1026; - } - } + if ($error == 0) + { + $this->db->commit(); + return 0; + } + else + { + $this->db->rollback(); + dol_syslog("bon-prelevment::set_infocredit ROLLBACK "); + return -1; + } + } + else + { + dol_syslog(get_class($this)."::set_infocredit 1025 Open SQL transaction impossible "); + return -1025; + } + } + else + { + dol_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans "); + return -1027; + } + } + else + { + return -1026; + } + } - /** - * Set withdrawal to transmited status - * - * @param User $user id of user - * @param int $date date of action - * @param string $method method of transmision to bank - * @return int >0 if OK, <0 if KO - */ - function set_infotrans($user, $date, $method) - { - global $conf,$langs; + /** + * Set withdrawal to transmited status + * + * @param User $user id of user + * @param int $date date of action + * @param string $method method of transmision to bank + * @return int >0 if OK, <0 if KO + */ + function set_infotrans($user, $date, $method) + { + global $conf,$langs; - $error = 0; + $error = 0; - dol_syslog(get_class($this)."::set_infotrans Start",LOG_INFO); - if ($this->db->begin()) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; - $sql.= " SET fk_user_trans = ".$user->id; - $sql.= " , date_trans = '".$this->db->idate($date)."'"; - $sql.= " , method_trans = ".$method; - $sql.= " , statut = 1"; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; - $sql.= " AND statut = 0"; + dol_syslog(get_class($this)."::set_infotrans Start",LOG_INFO); + if ($this->db->begin()) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; + $sql.= " SET fk_user_trans = ".$user->id; + $sql.= " , date_trans = '".$this->db->idate($date)."'"; + $sql.= " , method_trans = ".$method; + $sql.= " , statut = 1"; + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; + $sql.= " AND statut = 0"; - if ($this->db->query($sql)) - { - $this->method_trans = $method; - $langs->load('withdrawals'); - $subject = $langs->trans("InfoTransSubject", $this->ref); - $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname)); - $message .=$langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date,'day')); + if ($this->db->query($sql)) + { + $this->method_trans = $method; + $langs->load('withdrawals'); + $subject = $langs->trans("InfoTransSubject", $this->ref); + $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname)); + $message .=$langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date,'day')); - // TODO Call trigger to create a notification using notification module - } - else - { - $error++; - } + // TODO Call trigger to create a notification using notification module + } + else + { + $error++; + } - if ($error == 0) - { - $this->db->commit(); - return 0; - } - else - { - $this->db->rollback(); - dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR); + if ($error == 0) + { + $this->db->commit(); + return 0; + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR); - return -1; - } - } - else - { + return -1; + } + } + else + { - dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT); - return -2; - } - } + dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT); + return -2; + } + } - /** - * Get invoice list - * - * @param int $amounts If you want to get the amount of the order for each invoice - * @return array Id of invoices - */ - private function getListInvoices($amounts=0) - { - global $conf; + /** + * Get invoice list + * + * @param int $amounts If you want to get the amount of the order for each invoice + * @return array Id of invoices + */ + private function getListInvoices($amounts=0) + { + global $conf; - $arr = array(); + $arr = array(); - /* + /* * Returns all invoices presented * within a withdrawal receipt */ - $sql = "SELECT fk_facture"; - if ($amounts) $sql .= ", SUM(pl.amount)"; - $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; - $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; - $sql.= " , ".MAIN_DB_PREFIX."prelevement_facture as pf"; - $sql.= " WHERE pf.fk_prelevement_lignes = pl.rowid"; - $sql.= " AND pl.fk_prelevement_bons = p.rowid"; - $sql.= " AND p.rowid = ".$this->id; - $sql.= " AND p.entity = ".$conf->entity; - if ($amounts) $sql.= " GROUP BY fk_facture"; + $sql = "SELECT fk_facture"; + if ($amounts) $sql .= ", SUM(pl.amount)"; + $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; + $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; + $sql.= " , ".MAIN_DB_PREFIX."prelevement_facture as pf"; + $sql.= " WHERE pf.fk_prelevement_lignes = pl.rowid"; + $sql.= " AND pl.fk_prelevement_bons = p.rowid"; + $sql.= " AND p.rowid = ".$this->id; + $sql.= " AND p.entity = ".$conf->entity; + if ($amounts) $sql.= " GROUP BY fk_facture"; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); - if ($num) - { - $i = 0; - while ($i < $num) - { - $row = $this->db->fetch_row($resql); - if (!$amounts) $arr[$i] = $row[0]; - else - { - $arr[$i] = array( - $row[0], - $row[1] - ); - } - $i++; - } - } - $this->db->free($resql); - } - else - { - dol_syslog(get_class($this)."::getListInvoices Erreur"); - } - - return $arr; - } - - /** - * Returns amount of withdrawal - * - * @return double Total amount - */ - function SommeAPrelever() - { - global $conf; - - $sql = "SELECT sum(pfd.amount) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //$sql.= " ,".MAIN_DB_PREFIX."c_paiement as cp"; - $sql.= " WHERE f.fk_statut = 1"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND f.rowid = pfd.fk_facture"; - $sql.= " AND f.paye = 0"; - $sql.= " AND pfd.traite = 0"; - $sql.= " AND f.total_ttc > 0"; - - $resql = $this->db->query($sql); - if ( $resql ) - { - $obj = $this->db->fetch_object($resql); - - $this->db->free($resql); - - return $obj->nb; - } - else - { - $error = 1; - dol_syslog(get_class($this)."::SommeAPrelever Erreur -1"); - dol_syslog($this->db->error()); - } - } - - /** - * Get number of invoices to withdrawal - * TODO delete params banque and agence when not necesary - * - * @param int $banque dolibarr mysoc bank - * @param int $agence dolibarr mysoc agence - * @return int entity; - $sql.= " AND f.rowid = pfd.fk_facture"; - $sql.= " AND f.paye = 0"; - $sql.= " AND pfd.traite = 0"; - $sql.= " AND f.total_ttc > 0"; - //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid"; - //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; - //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; - - dol_syslog(get_class($this)."::SommeAPrelever"); - $resql = $this->db->query($sql); - - if ( $resql ) - { - $obj = $this->db->fetch_object($resql); - - $this->db->free($resql); - - return $obj->nb; - } - else - { - $this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error(); - return -1; - } - } - - - /** - * Create a withdraw - * TODO delete params banque and agence when not necesary - * - * @param int $banque dolibarr mysoc bank - * @param int $agence dolibarr mysoc bank office (guichet) - * @param string $mode real=do action, simu=test only - * @return int <0 if KO, nbre of invoice withdrawed if OK - */ - function Create($banque=0, $agence=0, $mode='real') - { - global $conf,$langs; - - dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence, LOG_DEBUG); - - require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"); - require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); - - $error = 0; - - $datetimeprev = time(); - - $month = strftime("%m", $datetimeprev); - $year = strftime("%Y", $datetimeprev); - - $puser = new User($this->db, $conf->global->PRELEVEMENT_USER); - - /* - * Read invoices - */ - $factures = array(); - $factures_prev = array(); - $factures_result = array(); - $factures_prev_id=array(); - $factures_errors=array(); - - if (! $error) - { - $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc"; - $sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib"; - $sql.= ", pfd.amount"; - $sql.= ", s.nom as name"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; - $sql.= " WHERE f.rowid = pfd.fk_facture"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND s.rowid = f.fk_soc"; - //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; - $sql.= " AND f.fk_statut = 1"; - $sql.= " AND f.paye = 0"; - $sql.= " AND pfd.traite = 0"; - $sql.= " AND f.total_ttc > 0"; - //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; - //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; - - dol_syslog(__METHOD__."::Read invoices, sql=".$sql, LOG_DEBUG); - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - - while ($i < $num) - { - $row = $this->db->fetch_row($resql); - $factures[$i] = $row; // All fields - $i++; - } - $this->db->free($resql); - dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG); - } - else - { - $error++; - dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR); - } - } - - if (! $error) - { - require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; - $soc = new Societe($this->db); - - // Check RIB - $i = 0; - dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG); - - if (count($factures) > 0) - { - foreach ($factures as $key => $fac) - { - $fact = new Facture($this->db); - if ($fact->fetch($fac[0]) >= 0) // Field 0 of $fac is rowid of invoice - { - if ($soc->fetch($fact->socid) >= 0) - { - $bac = new CompanyBankAccount($this->db); - $bac->fetch(0,$soc->id); - - if ($bac->verif() >= 1) - //if (true) - { - $factures_prev[$i] = $fac; - /* second tableau necessaire pour BonPrelevement */ - $factures_prev_id[$i] = $fac[0]; - $i++; - } - else - { - dol_syslog(__METHOD__."::Check RIB Error on default bank number RIB/IBAN for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_ERR); - $this->invoice_in_error[$fac[0]]="Error on default bank number RIB/IBAN for invoice ".$fact->getNomUrl(0)." for thirdparty (reported by function verif) ".$soc->getNomUrl(0); - } - } - else - { - dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_ERR); - } - } - else - { - dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_ERR); - } - } - } - else + if ($num) { - dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_ERR); - } - } + $i = 0; + while ($i < $num) + { + $row = $this->db->fetch_row($resql); + if (!$amounts) $arr[$i] = $row[0]; + else + { + $arr[$i] = array( + $row[0], + $row[1] + ); + } + $i++; + } + } + $this->db->free($resql); + } + else + { + dol_syslog(get_class($this)."::getListInvoices Erreur"); + } - $ok=0; + return $arr; + } - // Withdraw invoices in factures_prev array - $out=count($factures_prev)." invoices will be withdrawn."; - //print $out."\n"; - dol_syslog($out); + /** + * Returns amount of withdrawal + * + * @return double Total amount + */ + function SommeAPrelever() + { + global $conf; + + $sql = "SELECT sum(pfd.amount) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,"; + $sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + //$sql.= " ,".MAIN_DB_PREFIX."c_paiement as cp"; + $sql.= " WHERE f.fk_statut = 1"; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND f.rowid = pfd.fk_facture"; + $sql.= " AND f.paye = 0"; + $sql.= " AND pfd.traite = 0"; + $sql.= " AND f.total_ttc > 0"; + + $resql = $this->db->query($sql); + if ( $resql ) + { + $obj = $this->db->fetch_object($resql); + + $this->db->free($resql); + + return $obj->nb; + } + else + { + $error = 1; + dol_syslog(get_class($this)."::SommeAPrelever Erreur -1"); + dol_syslog($this->db->error()); + } + } + + /** + * Get number of invoices to withdrawal + * TODO delete params banque and agence when not necesary + * + * @param int $banque dolibarr mysoc bank + * @param int $agence dolibarr mysoc agence + * @return int entity; + $sql.= " AND f.rowid = pfd.fk_facture"; + $sql.= " AND f.paye = 0"; + $sql.= " AND pfd.traite = 0"; + $sql.= " AND f.total_ttc > 0"; + //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid"; + //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; + //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; + + dol_syslog(get_class($this)."::SommeAPrelever"); + $resql = $this->db->query($sql); + + if ( $resql ) + { + $obj = $this->db->fetch_object($resql); + + $this->db->free($resql); + + return $obj->nb; + } + else + { + $this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error(); + return -1; + } + } - if (count($factures_prev) > 0) + /** + * Create a withdraw + * TODO delete params banque and agence when not necesary + * + * @param int $banque dolibarr mysoc bank + * @param int $agence dolibarr mysoc bank office (guichet) + * @param string $mode real=do action, simu=test only + * @param string $format FRST, RCUR or ALL + * @return int <0 if KO, nbre of invoice withdrawed if OK + */ + function Create($banque=0, $agence=0, $mode='real', $format='ALL') + { + global $conf,$langs; + + dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence." mode=".$mode." format=".$format, LOG_DEBUG); + + require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"); + require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); + + if (empty($format)) return 'ErrorBadParametersForDirectDebitFileCreate'; + + $error = 0; + + $datetimeprev = time(); + + $month = strftime("%m", $datetimeprev); + $year = strftime("%Y", $datetimeprev); + + $puser = new User($this->db, $conf->global->PRELEVEMENT_USER); + + $this->invoice_in_error = array(); + $this->thirdparty_in_error = array(); + + // Read invoices + $factures = array(); + $factures_prev = array(); + $factures_result = array(); + $factures_prev_id=array(); + $factures_errors=array(); + + if (! $error) + { + $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc"; + $sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib"; + $sql.= ", pfd.amount"; + $sql.= ", s.nom as name"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= ", ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; + $sql.= " WHERE f.rowid = pfd.fk_facture"; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND s.rowid = f.fk_soc"; + //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; + $sql.= " AND f.fk_statut = 1"; + $sql.= " AND f.paye = 0"; + $sql.= " AND pfd.traite = 0"; + $sql.= " AND f.total_ttc > 0"; + //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; + //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; + + dol_syslog(__METHOD__."::Read invoices, sql=".$sql, LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + + while ($i < $num) + { + $row = $this->db->fetch_row($resql); + $factures[$i] = $row; // All fields + $i++; + } + $this->db->free($resql); + dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG); + } + else + { + $error++; + dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR); + } + } + + if (! $error) + { + require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + $soc = new Societe($this->db); + + // Check RIB + $i = 0; + dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG); + + if (count($factures) > 0) + { + foreach ($factures as $key => $fac) + { + $fact = new Facture($this->db); + if ($fact->fetch($fac[0]) >= 0) // Field 0 of $fac is rowid of invoice + { + if ($soc->fetch($fact->socid) >= 0) + { + $bac = new CompanyBankAccount($this->db); + $bac->fetch(0, $soc->id); + + if ($format == 'FRST' && $bac->frstrecur != 'FRST') continue; + if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR')) continue; + + if ($bac->verif() >= 1) + { + $factures_prev[$i] = $fac; + /* second tableau necessaire pour BonPrelevement */ + $factures_prev_id[$i] = $fac[0]; + $i++; + } + else + { + dol_syslog(__METHOD__."::Check RIB Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_ERR); + $this->invoice_in_error[$fac[0]]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0); + $this->thirdparty_in_error[$soc->id]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0); + } + } + else + { + dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_ERR); + } + } + else + { + dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_ERR); + } + } + } + else + { + dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_ERR); + } + } + + $ok=0; + + // Withdraw invoices in factures_prev array + $out=count($factures_prev)." invoices will be withdrawn."; + //print $out."\n"; + dol_syslog($out); + + // Return warning + /*$i=0; + foreach ($this->thirdparty_in_error as $key => $val) { - if ($mode=='real') - { - $ok=1; - } - else - { - print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n"; - } - } + if ($i < 10) setEventMessages($val, null, 'warnings'); + else setEventMessages('More error were discarded...', null, 'warnings'); + $i++; + }*/ + + if (count($factures_prev) > 0) + { + if ($mode=='real') + { + $ok=1; + } + else + { + print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n"; + } + } - if ($ok) - { - /* + if ($ok) + { + /* * We are in real mode. * We create withdraw receipt and build withdraw into disk */ - $this->db->begin(); + $this->db->begin(); - $now=dol_now(); + $now=dol_now(); - /* + /* * Traitements */ - if (!$error) - { + if (!$error) + { $ref = substr($year,-2).$month; $sql = "SELECT substring(ref from char_length(ref) - 1)"; @@ -939,48 +955,48 @@ class BonPrelevement extends CommonObject $this->filename = $dir.'/'.$ref.'.xml'; - // Create withdraw receipt in database - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons ("; - $sql.= " ref, entity, datec"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->escape($ref)."'"; - $sql.= ", ".$conf->entity; - $sql.= ", '".$this->db->idate($now)."'"; - $sql.= ")"; + // Create withdraw receipt in database + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons ("; + $sql.= " ref, entity, datec"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->escape($ref)."'"; + $sql.= ", ".$conf->entity; + $sql.= ", '".$this->db->idate($now)."'"; + $sql.= ")"; - $resql = $this->db->query($sql); - if ($resql) - { - $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons"); + $resql = $this->db->query($sql); + if ($resql) + { + $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons"); $this->id = $prev_id; $this->ref = $ref; - } - else + } + else { - $error++; - dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR); - } + $error++; + dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR); + } } else { $error++; dol_syslog(__METHOD__."::Get last withdraw receipt ".$this->db->lasterror(), LOG_ERR); } - } + } - if (!$error) - { - /* + if (!$error) + { + /* * Create withdrawal receipt in database */ - if (count($factures_prev) > 0) - { - foreach ($factures_prev as $fac) // Add a link in database for each invoice - { - // Fetch invoice - $fact = new Facture($this->db); - $fact->fetch($fac[0]); - /* + if (count($factures_prev) > 0) + { + foreach ($factures_prev as $fac) // Add a link in database for each invoice + { + // Fetch invoice + $fact = new Facture($this->db); + $fact->fetch($fac[0]); + /* * Add standing order * * @@ -992,128 +1008,128 @@ class BonPrelevement extends CommonObject * $fac[8] : client nom * $fac[2] : client id */ - $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]); - if ($ri <> 0) - { - $error++; - } + $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]); + if ($ri <> 0) + { + $error++; + } - // Update invoice requests as done - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande"; - $sql.= " SET traite = 1"; - $sql.= ", date_traite = '".$this->db->idate($now)."'"; - $sql.= ", fk_prelevement_bons = ".$this->id; - $sql.= " WHERE rowid = ".$fac[1]; + // Update invoice requests as done + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande"; + $sql.= " SET traite = 1"; + $sql.= ", date_traite = '".$this->db->idate($now)."'"; + $sql.= ", fk_prelevement_bons = ".$this->id; + $sql.= " WHERE rowid = ".$fac[1]; - dol_syslog(__METHOD__."::Update Orders::Sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); + dol_syslog(__METHOD__."::Update Orders::Sql=".$sql, LOG_DEBUG); + $resql=$this->db->query($sql); - if (! $resql) - { - $error++; - dol_syslog(__METHOD__."::Update Orders::Error=".$this->db->error(), LOG_ERR); - } + if (! $resql) + { + $error++; + dol_syslog(__METHOD__."::Update Orders::Error=".$this->db->error(), LOG_ERR); + } - } - } + } + } - } + } - if (!$error) - { - /* + if (!$error) + { + /* * Create direct debit order in a XML file */ - dol_syslog(__METHOD__."::Init withdraw receipt for ".count($factures_prev)." invoices", LOG_DEBUG); + dol_syslog(__METHOD__."::Init withdraw receipt for ".count($factures_prev)." invoices", LOG_DEBUG); - if (count($factures_prev) > 0) - { - $this->date_echeance = $datetimeprev; - $this->reference_remise = $ref; + if (count($factures_prev) > 0) + { + $this->date_echeance = $datetimeprev; + $this->reference_remise = $ref; - $id=$conf->global->PRELEVEMENT_ID_BANKACCOUNT; - $account = new Account($this->db); - if ($account->fetch($id)>0) - { - $this->emetteur_code_banque = $account->code_banque; - $this->emetteur_code_guichet = $account->code_guichet; - $this->emetteur_numero_compte = $account->number; - $this->emetteur_number_key = $account->cle_rib; - $this->emetteur_iban = $account->iban; - $this->emetteur_bic = $account->bic; + $id=$conf->global->PRELEVEMENT_ID_BANKACCOUNT; + $account = new Account($this->db); + if ($account->fetch($id)>0) + { + $this->emetteur_code_banque = $account->code_banque; + $this->emetteur_code_guichet = $account->code_guichet; + $this->emetteur_numero_compte = $account->number; + $this->emetteur_number_key = $account->cle_rib; + $this->emetteur_iban = $account->iban; + $this->emetteur_bic = $account->bic; - $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; + $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; - $this->raison_sociale = $account->proprio; - } + $this->raison_sociale = $account->proprio; + } - $this->factures = $factures_prev_id; + $this->factures = $factures_prev_id; - // Generation of SEPA file $this->filename - $this->generate(); - } - dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG); - } + // Generation of SEPA file $this->filename + $this->generate($format); + } + dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG); + } //var_dump($factures_prev);exit; - /* + /* * Update total */ - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; - $sql.= " SET amount = ".price2num($this->total); - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; + $sql.= " SET amount = ".price2num($this->total); + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; - $resql=$this->db->query($sql); - if (! $resql) - { - $error++; - dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR); - } + $resql=$this->db->query($sql); + if (! $resql) + { + $error++; + dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR); + } - if (!$error) - { - $this->db->commit(); - } - else - { - $this->db->rollback(); - } + if (!$error) + { + $this->db->commit(); + } + else + { + $this->db->rollback(); + } - return count($factures_prev); - } - else - { - return 0; - } - } + return count($factures_prev); + } + else + { + return 0; + } + } - /** - * Get object and lines from database - * - * @return int >0 if OK, <0 if KO - */ - function delete() - { - $this->db->begin(); + /** + * Get object and lines from database + * + * @return int >0 if OK, <0 if KO + */ + function delete() + { + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_facture WHERE fk_prelevement_lignes IN (SELECT rowid FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id.")"; - $resql1=$this->db->query($sql); - if (! $resql1) dol_print_error($this->db); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_facture WHERE fk_prelevement_lignes IN (SELECT rowid FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id.")"; + $resql1=$this->db->query($sql); + if (! $resql1) dol_print_error($this->db); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id; - $resql2=$this->db->query($sql); - if (! $resql2) dol_print_error($this->db); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id; + $resql2=$this->db->query($sql); + if (! $resql2) dol_print_error($this->db); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".$this->id; - $resql3=$this->db->query($sql); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".$this->id; + $resql3=$this->db->query($sql); if (! $resql3) dol_print_error($this->db); - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".$this->id; - $resql4=$this->db->query($sql); + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".$this->id; + $resql4=$this->db->query($sql); if (! $resql4) dol_print_error($this->db); if ($resql1 && $resql2 && $resql3) @@ -1126,151 +1142,153 @@ class BonPrelevement extends CommonObject $this->db->rollback(); return -1; } - } + } - /** - * Returns clickable name (with picto) - * - * @param int $withpicto link with picto - * @param string $option link target - * @return string URL of target - */ - function getNomUrl($withpicto=0,$option='') - { - global $langs; + /** + * Returns clickable name (with picto) + * + * @param int $withpicto link with picto + * @param string $option link target + * @return string URL of target + */ + function getNomUrl($withpicto=0,$option='') + { + global $langs; - $result=''; - $label = $langs->trans("ShowWithdraw").': '.$this->ref; + $result=''; + $label = $langs->trans("ShowWithdraw").': '.$this->ref; - $link = ''; - $linkend=''; + $link = ''; + $linkend=''; - if ($option == 'xxx') - { - $link = ''; - $linkend=''; - } + if ($option == 'xxx') + { + $link = ''; + $linkend=''; + } - if ($withpicto) $result.=($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); - $result.=$link.$this->ref.$linkend; - return $result; - } + if ($withpicto) $result.=($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + $result.=$link.$this->ref.$linkend; + return $result; + } - /** - * Delete a notification def by id - * - * @param int $rowid id of notification - * @return int 0 if OK, <0 if KO - */ - function DeleteNotificationById($rowid) - { - $result = 0; + /** + * Delete a notification def by id + * + * @param int $rowid id of notification + * @return int 0 if OK, <0 if KO + */ + function DeleteNotificationById($rowid) + { + $result = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; - $sql.= " WHERE rowid = '".$rowid."'"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; + $sql.= " WHERE rowid = '".$rowid."'"; - if ($this->db->query($sql)) - { - return 0; - } - else - { - return -1; - } - } + if ($this->db->query($sql)) + { + return 0; + } + else + { + return -1; + } + } - /** - * Delete a notification - * - * @param int $user notification user - * @param string $action notification action - * @return int >0 if OK, <0 if KO - */ - function DeleteNotification($user, $action) - { - $result = 0; + /** + * Delete a notification + * + * @param int $user notification user + * @param string $action notification action + * @return int >0 if OK, <0 if KO + */ + function DeleteNotification($user, $action) + { + $result = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; - $sql .= " WHERE fk_user=".$user." AND fk_action='".$action."'"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; + $sql .= " WHERE fk_user=".$user." AND fk_action='".$action."'"; - if ($this->db->query($sql)) - { - return 0; - } - else - { - return -1; - } - } + if ($this->db->query($sql)) + { + return 0; + } + else + { + return -1; + } + } - /** - * Add a notification - * - * @param DoliDB $db database handler - * @param int $user notification user - * @param string $action notification action - * @return int 0 if OK, <0 if KO - */ - function AddNotification($db, $user, $action) - { - $result = 0; + /** + * Add a notification + * + * @param DoliDB $db database handler + * @param int $user notification user + * @param string $action notification action + * @return int 0 if OK, <0 if KO + */ + function AddNotification($db, $user, $action) + { + $result = 0; - if ($this->DeleteNotification($user, $action) == 0) - { - $now=dol_now(); + if ($this->DeleteNotification($user, $action) == 0) + { + $now=dol_now(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)"; - $sql .= " VALUES (".$db->idate($now).",".$user.", 'NULL', 'NULL', '".$action."')"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)"; + $sql .= " VALUES (".$db->idate($now).",".$user.", 'NULL', 'NULL', '".$action."')"; - dol_syslog("adnotiff: ".$sql); - if ($this->db->query($sql)) - { - $result = 0; - } - else - { - $result = -1; - dol_syslog(get_class($this)."::AddNotification Error $result"); - } - } + dol_syslog("adnotiff: ".$sql); + if ($this->db->query($sql)) + { + $result = 0; + } + else + { + $result = -1; + dol_syslog(get_class($this)."::AddNotification Error $result"); + } + } - return $result; - } + return $result; + } - /** - * Generate a withdrawal file. - * Generation Formats: - * - Europe: SEPA (France: CFONB no more supported, Spain: AEB19 if external module EsAEB is enabled) - * - Others countries: Warning message - * File is generated with name this->filename - * - * @return int 0 if OK, <0 if KO - */ - //TODO: Optimize code to read lines in a single function - function generate() - { - global $conf,$langs,$mysoc; + /** + * Generate a withdrawal file. + * Generation Formats: + * - Europe: SEPA (France: CFONB no more supported, Spain: AEB19 if external module EsAEB is enabled) + * - Others countries: Warning message + * File is generated with name this->filename + * + * @param string $format FRST, RCUR or ALL + * @return int 0 if OK, <0 if KO + */ + function generate($format='ALL') + { + global $conf,$langs,$mysoc; - $result = 0; + //TODO: Optimize code to read lines in a single function - dol_syslog(get_class($this)."::generate build file ".$this->filename); + $result = 0; - $this->file = fopen($this->filename,"w"); + dol_syslog(get_class($this)."::generate build file ".$this->filename); + + $this->file = fopen($this->filename,"w"); if (empty($this->file)) { $this->error=$langs->trans('ErrorFailedToOpenFile', $this->filename); return -1; } - $found=0; + $found=0; - // Build file for European countries - if ($mysoc->isInEEC()) - { - $found++; + // Build file for European countries + if ($mysoc->isInEEC()) + { + $found++; /** * SECTION CREATION FICHIER SEPA @@ -1332,7 +1350,7 @@ class BonPrelevement extends CommonObject // Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all DrctDbtTxInf if ($result != -2) { - $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf); + $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format); } else { @@ -1373,163 +1391,163 @@ class BonPrelevement extends CommonObject fputs($this->file, ' '.$CrLf); fputs($this->file, ' '.$CrLf); fputs($this->file, ''.$CrLf); - } + } - // Build file for Other Countries with unknow format - if (! $found) + // Build file for Other Countries with unknow format + if (! $found) { - $this->total = 0; - $sql = "SELECT pl.amount"; - $sql.= " FROM"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; - $sql.= " ".MAIN_DB_PREFIX."facture as f,"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf"; - $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id; - $sql.= " AND pl.rowid = pf.fk_prelevement_lignes"; - $sql.= " AND pf.fk_facture = f.rowid"; + $this->total = 0; + $sql = "SELECT pl.amount"; + $sql.= " FROM"; + $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; + $sql.= " ".MAIN_DB_PREFIX."facture as f,"; + $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf"; + $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id; + $sql.= " AND pl.rowid = pf.fk_prelevement_lignes"; + $sql.= " AND pf.fk_facture = f.rowid"; - //Lines - $i = 0; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $this->total = $this->total + $obj->amount; - $i++; - } - } - else + //Lines + $i = 0; + $resql=$this->db->query($sql); + if ($resql) { - $result = -2; - } + $num = $this->db->num_rows($resql); - $langs->load('withdrawals'); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $this->total = $this->total + $obj->amount; + $i++; + } + } + else + { + $result = -2; + } - // TODO Add here code to generate a generic file - fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code)); - } + $langs->load('withdrawals'); - fclose($this->file); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($this->file, octdec($conf->global->MAIN_UMASK)); - return $result; + // TODO Add here code to generate a generic file + fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code)); + } - } + fclose($this->file); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($this->file, octdec($conf->global->MAIN_UMASK)); + return $result; + + } - /** - * Write recipient of request (customer) - * - * @param int $rowid id of line - * @param string $client_nom name of customer - * @param string $rib_banque code of bank - * @param string $rib_guichet code of bank office - * @param string $rib_number bank account - * @param float $amount amount - * @param string $facnumber ref of invoice - * @param int $facid id of invoice + /** + * Write recipient of request (customer) + * + * @param int $rowid id of line + * @param string $client_nom name of customer + * @param string $rib_banque code of bank + * @param string $rib_guichet code of bank office + * @param string $rib_number bank account + * @param float $amount amount + * @param string $facnumber ref of invoice + * @param int $facid id of invoice * @param string $rib_dom rib domiciliation - * @return void - */ - function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $facnumber, $facid, $rib_dom='') - { - fputs($this->file, "06"); - fputs($this->file, "08"); // Prelevement ordinaire + * @return void + */ + function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $facnumber, $facid, $rib_dom='') + { + fputs($this->file, "06"); + fputs($this->file, "08"); // Prelevement ordinaire - fputs($this->file, " "); // Zone Reservee B2 + fputs($this->file, " "); // Zone Reservee B2 - fputs($this->file, $this->emetteur_ics); // ICS + fputs($this->file, $this->emetteur_ics); // ICS - // Date d'echeance C1 + // Date d'echeance C1 - fputs($this->file, " "); - fputs($this->file, strftime("%d%m", $this->date_echeance)); - fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); + fputs($this->file, " "); + fputs($this->file, strftime("%d%m", $this->date_echeance)); + fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); - // Raison Sociale Destinataire C2 + // Raison Sociale Destinataire C2 - fputs($this->file, substr(strtoupper($client_nom)." ",0,24)); + fputs($this->file, substr(strtoupper($client_nom)." ",0,24)); - // Domiciliation facultative D1 - $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => "")); - fputs($this->file, substr($domiciliation." ",0,24)); + // Domiciliation facultative D1 + $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => "")); + fputs($this->file, substr($domiciliation." ",0,24)); - // Zone Reservee D2 + // Zone Reservee D2 - fputs($this->file, substr(" ",0,8)); + fputs($this->file, substr(" ",0,8)); - // Code Guichet D3 + // Code Guichet D3 - fputs($this->file, $rib_guichet); + fputs($this->file, $rib_guichet); - // Numero de compte D4 + // Numero de compte D4 - fputs($this->file, substr("000000000000000".$rib_number, -11)); + fputs($this->file, substr("000000000000000".$rib_number, -11)); - // Zone E Montant + // Zone E Montant - $montant = (round($amount,2) * 100); + $montant = (round($amount,2) * 100); - fputs($this->file, substr("000000000000000".$montant, -16)); + fputs($this->file, substr("000000000000000".$montant, -16)); - // Libelle F + // Libelle F - fputs($this->file, substr("*_".$facnumber."_RDVnet".$rowid." ", 0, 31)); + fputs($this->file, substr("*_".$facnumber."_RDVnet".$rowid." ", 0, 31)); - // Code etablissement G1 + // Code etablissement G1 - fputs($this->file, $rib_banque); + fputs($this->file, $rib_banque); - // Zone Reservee G2 + // Zone Reservee G2 - fputs($this->file, substr(" ", 0, 5)); + fputs($this->file, substr(" ", 0, 5)); - fputs($this->file, "\n"); - } + fputs($this->file, "\n"); + } - /** - * Build RUM number for a customer bank account - * - * @param string $row_code_client Customer code (soc.code_client) - * @param int $row_datec Creation date of bank account (rib.datec) - * @param string $row_drum Id of customer bank account (rib.rowid) - * @return string RUM number - */ - static function buildRumNumber($row_code_client, $row_datec, $row_drum) - { - global $langs; - $pre = ($row_datec > 1359673200) ? $langs->trans('RUM').'-' : '++R'; + /** + * Build RUM number for a customer bank account + * + * @param string $row_code_client Customer code (soc.code_client) + * @param int $row_datec Creation date of bank account (rib.datec) + * @param string $row_drum Id of customer bank account (rib.rowid) + * @return string RUM number + */ + static function buildRumNumber($row_code_client, $row_datec, $row_drum) + { + global $langs; + $pre = $langs->trans('RUM').'-'; return $pre.$row_code_client.'-'.$row_drum.'-'.date('U', $row_datec); - } + } - /** - * Write recipient of request (customer) - * - * @param string $row_code_client soc.code_client as code, - * @param string $row_nom pl.client_nom AS name, - * @param string $row_address soc.address AS adr, - * @param string $row_zip soc.zip - * @param string $row_town soc.town - * @param string $row_country_code c.code AS country, - * @param string $row_cb pl.code_banque AS cb, - * @param string $row_cg pl.code_guichet AS cg, - * @param string $row_cc pl.number AS cc, - * @param string $row_somme pl.amount AS somme, - * @param string $row_facnumber f.facnumber - * @param string $row_idfac pf.fk_facture AS idfac, - * @param string $row_iban rib.iban_prefix AS iban, - * @param string $row_bic rib.bic AS bic, - * @param string $row_datec rib.datec, - * @param string $row_drum rib.rowid used to generate rum - * @return string Return string with SEPA part DrctDbtTxInf - */ - function EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_facnumber, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum) - { + /** + * Write recipient of request (customer) + * + * @param string $row_code_client soc.code_client as code, + * @param string $row_nom pl.client_nom AS name, + * @param string $row_address soc.address AS adr, + * @param string $row_zip soc.zip + * @param string $row_town soc.town + * @param string $row_country_code c.code AS country, + * @param string $row_cb pl.code_banque AS cb, Not used for SEPA + * @param string $row_cg pl.code_guichet AS cg, Not used for SEPA + * @param string $row_cc pl.number AS cc, Not used for SEPA + * @param string $row_somme pl.amount AS somme, + * @param string $row_facnumber f.facnumber + * @param string $row_idfac pf.fk_facture AS idfac, + * @param string $row_iban rib.iban_prefix AS iban, + * @param string $row_bic rib.bic AS bic, + * @param string $row_datec rib.datec, + * @param string $row_drum rib.rowid used to generate rum + * @return string Return string with SEPA part DrctDbtTxInf + */ + function EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_facnumber, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum) + { $CrLf = "\n"; $Rowing = sprintf("%06d", $row_idfac); @@ -1562,8 +1580,10 @@ class BonPrelevement extends CommonObject $XML_DEBITOR .=' '.dolEscapeXML(strtoupper(dol_string_unaccent($row_nom))).''.$CrLf; $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.$row_country_code.''.$CrLf; - $XML_DEBITOR .=' '.dolEscapeXML(dol_trunc(dol_string_unaccent(strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""))),70,'right','UTF-8',true)).''.$CrLf; - $XML_DEBITOR .=' '.dolEscapeXML(dol_string_unaccent($row_zip.' '.$row_town)).''.$CrLf; + $addressline1 = dol_string_unaccent(strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""))); + $addressline2 = dol_string_unaccent(strtr($row_zip.(($row_zip && $row_town)?' ':''.$row_town), array(CHR(13) => ", ", CHR(10) => ""))); + if (trim($addressline1)) $XML_DEBITOR .=' '.dolEscapeXML(dol_trunc($addressline1,70,'right','UTF-8',true)).''.$CrLf; + if (trim($addressline2)) $XML_DEBITOR .=' '.dolEscapeXML(dol_trunc($addressline2,70,'right','UTF-8',true)).''.$CrLf; $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.$CrLf; @@ -1577,89 +1597,90 @@ class BonPrelevement extends CommonObject $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.$CrLf; return $XML_DEBITOR; - } + } - /** - * Write sender of request (me) - * - * @return void - */ - function EnregEmetteur() - { - fputs($this->file, "03"); - fputs($this->file, "08"); // Prelevement ordinaire + /** + * Write sender of request (me) + * + * @return void + */ + function EnregEmetteur() + { + fputs($this->file, "03"); + fputs($this->file, "08"); // Prelevement ordinaire - fputs($this->file, " "); // Zone Reservee B2 + fputs($this->file, " "); // Zone Reservee B2 - fputs($this->file, $this->emetteur_ics); // ICS + fputs($this->file, $this->emetteur_ics); // ICS - // Date d'echeance C1 + // Date d'echeance C1 - fputs($this->file, " "); - fputs($this->file, strftime("%d%m", $this->date_echeance)); - fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); + fputs($this->file, " "); + fputs($this->file, strftime("%d%m", $this->date_echeance)); + fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); - // Raison Sociale C2 + // Raison Sociale C2 - fputs($this->file, substr($this->raison_sociale. " ",0,24)); + fputs($this->file, substr($this->raison_sociale. " ",0,24)); - // Reference de la remise creancier D1 sur 7 caracteres + // Reference de la remise creancier D1 sur 7 caracteres - fputs($this->file, substr($this->reference_remise. " ",0,7)); + fputs($this->file, substr($this->reference_remise. " ",0,7)); - // Zone Reservee D1-2 + // Zone Reservee D1-2 - fputs($this->file, substr(" ",0,17)); + fputs($this->file, substr(" ",0,17)); - // Zone Reservee D2 + // Zone Reservee D2 - fputs($this->file, substr(" ",0,2)); - fputs($this->file, "E"); - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,2)); + fputs($this->file, "E"); + fputs($this->file, substr(" ",0,5)); - // Code Guichet D3 + // Code Guichet D3 - fputs($this->file, $this->emetteur_code_guichet); + fputs($this->file, $this->emetteur_code_guichet); - // Numero de compte D4 + // Numero de compte D4 - fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11)); + fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11)); - // Zone Reservee E + // Zone Reservee E - fputs($this->file, substr(" ",0,16)); + fputs($this->file, substr(" ",0,16)); - // Zone Reservee F + // Zone Reservee F - fputs($this->file, substr(" ",0,31)); + fputs($this->file, substr(" ",0,31)); - // Code etablissement + // Code etablissement - fputs($this->file, $this->emetteur_code_banque); + fputs($this->file, $this->emetteur_code_banque); - // Zone Reservee G + // Zone Reservee G - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - fputs($this->file, "\n"); + fputs($this->file, "\n"); - } + } - /** - * Write sender of request (me). - * Note: The tag PmtInf is opened here but closed into caller - * - * @param string $configuration conf - * @param int $ladate Date - * @param int $nombre 0 or 1 - * @param float $total Total - * @param string $CrLf End of line character - * @return string String with SEPA Sender - */ - function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n') - { - // SEPA INITIALISATION + /** + * Write sender of request (me). + * Note: The tag PmtInf is opened here but closed into caller + * + * @param string $configuration conf + * @param int $ladate Date + * @param int $nombre 0 or 1 + * @param float $total Total + * @param string $CrLf End of line character + * @param string $format FRST or RCUR or ALL + * @return string String with SEPA Sender + */ + function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n', $format='FRST') + { + // SEPA INITIALISATION global $conf; $dateTime_YMD = dol_print_date($ladate, '%Y%m%d'); @@ -1671,16 +1692,16 @@ class BonPrelevement extends CommonObject $account = new Account($this->db); if ($account->fetch($id)>0) { - $this->emetteur_code_banque = $account->code_banque; - $this->emetteur_code_guichet = $account->code_guichet; - $this->emetteur_numero_compte = $account->number; - $this->emetteur_number_key = $account->cle_rib; - $this->emetteur_iban = $account->iban; - $this->emetteur_bic = $account->bic; + $this->emetteur_code_banque = $account->code_banque; + $this->emetteur_code_guichet = $account->code_guichet; + $this->emetteur_numero_compte = $account->number; + $this->emetteur_number_key = $account->cle_rib; + $this->emetteur_iban = $account->iban; + $this->emetteur_bic = $account->bic; - $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; + $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; - $this->raison_sociale = $account->proprio; + $this->raison_sociale = $account->proprio; } // Récupération info demandeur @@ -1698,7 +1719,7 @@ class BonPrelevement extends CommonObject $country = explode(':', $configuration->global->MAIN_INFO_SOCIETE_COUNTRY); $IdBon = sprintf("%05d", $obj->rowid); $RefBon = $obj->ref; - $type = ($nombre == 1) ? 'FRST' : 'RCUR' ; + // SEPA Paiement Information $XML_SEPA_INFO = ''; $XML_SEPA_INFO .= ' '.$CrLf; @@ -1713,15 +1734,17 @@ class BonPrelevement extends CommonObject $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' CORE'.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; - $XML_SEPA_INFO .= ' '.$type.''.$CrLf; + $XML_SEPA_INFO .= ' '.$format.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$dateTime_ETAD.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.strtoupper(dol_string_unaccent($this->raison_sociale)).''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$country[1].''.$CrLf; - $XML_SEPA_INFO .= ' '.strtoupper(dol_string_unaccent($configuration->global->MAIN_INFO_SOCIETE_ADDRESS)).''.$CrLf; - $XML_SEPA_INFO .= ' '.strtoupper(dol_string_unaccent($configuration->global->MAIN_INFO_SOCIETE_ZIP.' '.$configuration->global->MAIN_INFO_SOCIETE_TOWN)).''.$CrLf; + $addressline1 = dol_string_unaccent(strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => ""))); + $addressline2 = dol_string_unaccent(strtr($configuration->global->MAIN_INFO_SOCIETE_ZIP.(($configuration->global->MAIN_INFO_SOCIETE_ZIP || ' '.$configuration->global->MAIN_INFO_SOCIETE_TOWN)?' ':'').$configuration->global->MAIN_INFO_SOCIETE_TOWN, array(CHR(13) => ", ", CHR(10) => ""))); + if ($addressline1) $XML_SEPA_INFO .= ' '.$addressline1.''.$CrLf; + if ($addressline2) $XML_SEPA_INFO .= ' '.$addressline2.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; @@ -1764,131 +1787,131 @@ class BonPrelevement extends CommonObject return $XML_SEPA_INFO; } - /** - * Write end - * - * @param int $total total amount - * @return void - */ - function EnregTotal($total) - { - fputs($this->file, "08"); - fputs($this->file, "08"); // Prelevement ordinaire + /** + * Write end + * + * @param int $total total amount + * @return void + */ + function EnregTotal($total) + { + fputs($this->file, "08"); + fputs($this->file, "08"); // Prelevement ordinaire - fputs($this->file, " "); // Zone Reservee B2 + fputs($this->file, " "); // Zone Reservee B2 - fputs($this->file, $this->emetteur_ics); // ICS + fputs($this->file, $this->emetteur_ics); // ICS - // Reserve C1 + // Reserve C1 - fputs($this->file, substr(" ",0,12)); + fputs($this->file, substr(" ",0,12)); - // Raison Sociale C2 + // Raison Sociale C2 - fputs($this->file, substr(" ",0,24)); + fputs($this->file, substr(" ",0,24)); - // D1 + // D1 - fputs($this->file, substr(" ",0,24)); + fputs($this->file, substr(" ",0,24)); - // Zone Reservee D2 + // Zone Reservee D2 - fputs($this->file, substr(" ",0,8)); + fputs($this->file, substr(" ",0,8)); - // Code Guichet D3 + // Code Guichet D3 - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - // Numero de compte D4 + // Numero de compte D4 - fputs($this->file, substr(" ",0,11)); + fputs($this->file, substr(" ",0,11)); - // Zone E Montant + // Zone E Montant - $montant = ($total * 100); + $montant = ($total * 100); - fputs($this->file, substr("000000000000000".$montant, -16)); + fputs($this->file, substr("000000000000000".$montant, -16)); - // Zone Reservee F + // Zone Reservee F - fputs($this->file, substr(" ",0,31)); + fputs($this->file, substr(" ",0,31)); - // Code etablissement + // Code etablissement - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - // Zone Reservee F + // Zone Reservee F - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - fputs($this->file, "\n"); - } + fputs($this->file, "\n"); + } - /** - * Return status label of object - * - * @param int $mode 0=Label, 1=Picto + label, 2=Picto, 3=Label + Picto - * @return string Label - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->statut,$mode); - } + /** + * Return status label of object + * + * @param int $mode 0=Label, 1=Picto + label, 2=Picto, 3=Label + Picto + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut,$mode); + } - /** - * Return status label for a status - * - * @param int $statut id statut + /** + * Return status label for a status + * + * @param int $statut id statut * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto - * @return string Label - */ - function LibStatut($statut,$mode=0) - { - global $langs; + * @return string Label + */ + function LibStatut($statut,$mode=0) + { + global $langs; - if ($mode == 0) - { - return $langs->trans($this->labelstatut[$statut]); - } + if ($mode == 0) + { + return $langs->trans($this->labelstatut[$statut]); + } - if ($mode == 1) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); - } - if ($mode == 2) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - if ($mode == 3) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - if ($mode == 4) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); - } - if ($mode == 5) - { - if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - if ($mode == 6) - { - if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - } + if ($mode == 1) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); + } + if ($mode == 2) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + if ($mode == 3) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + if ($mode == 4) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); + } + if ($mode == 5) + { + if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + if ($mode == 6) + { + if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + } } diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index 09102ec1309..d9775250853 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -28,6 +28,7 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/prelevement.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -44,6 +45,8 @@ $result = restrictedArea($user, 'prelevement', '', '', 'bons'); // Get supervariables $action = GETPOST('action','alpha'); +$mode = GETPOST('mode','alpha')?GETPOST('mode','alpha'):'real'; +$format = GETPOST('format','aZ09'); /* @@ -53,35 +56,35 @@ $action = GETPOST('action','alpha'); // Change customer bank information to withdraw if ($action == 'modify') { - for ($i = 1 ; $i < 9 ; $i++) - { - dolibarr_set_const($db, GETPOST("nom$i"), GETPOST("value$i"),'chaine',0,'',$conf->entity); - } + for ($i = 1 ; $i < 9 ; $i++) + { + dolibarr_set_const($db, GETPOST("nom$i"), GETPOST("value$i"),'chaine',0,'',$conf->entity); + } } if ($action == 'create') { // $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty - $bprev = new BonPrelevement($db); - $result=$bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET); - if ($result < 0) - { - setEventMessages($bprev->error, $bprev->errors, 'errors'); - } - elseif ($result == 0) - { - $mesg=''; - $mesg=$langs->trans("NoInvoiceCouldBeWithdrawed"); - setEventMessages($mesg, null, 'errors'); - $mesg.='
    '."\n"; - foreach($bprev->invoice_in_error as $key => $val) - { - $mesg.=$val."
    \n"; - } - } - else - { - setEventMessages($langs->trans("DirectDebitOrderCreated", $bprev->getNomUrl(1)), null); - } + $bprev = new BonPrelevement($db); + $result=$bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format); + if ($result < 0) + { + setEventMessages($bprev->error, $bprev->errors, 'errors'); + } + elseif ($result == 0) + { + $mesg=''; + $mesg=$langs->trans("NoInvoiceCouldBeWithdrawed"); + setEventMessages($mesg, null, 'errors'); + $mesg.='
    '."\n"; + foreach($bprev->invoice_in_error as $key => $val) + { + $mesg.=''.$val."
    \n"; + } + } + else + { + setEventMessages($langs->trans("DirectDebitOrderCreated", $bprev->getNomUrl(1)), null); + } } @@ -121,7 +124,7 @@ $nb11=$bprev->NbFactureAPrelever(1,1); $pricetowithdraw=$bprev->SommeAPrelever(); if ($nb < 0 || $nb1 < 0 || $nb11 < 0) { - dol_print_error($bprev->error); + dol_print_error($bprev->error); } print ''; @@ -145,12 +148,34 @@ print "
    \n"; if ($nb) { - if ($pricetowithdraw) print ''.$langs->trans("CreateAll")."\n"; - else print ''.$langs->trans("CreateAll")."\n"; + if ($pricetowithdraw) + { + if ($mysoc->isInEEC()) + { + print ''.$langs->trans("CreateForSepaFRST")."\n"; + print ''.$langs->trans("CreateForSepaRCUR")."\n"; + } + else + { + print ''.$langs->trans("CreateAll")."\n"; + } + } + else + { + if ($mysoc->isInEEC()) + { + print ''.$langs->trans("CreateForSepaFRST")."\n"; + print ''.$langs->trans("CreateForSepaRCUR")."\n"; + } + else + { + print ''.$langs->trans("CreateAll")."\n"; + } + } } else { - print 'transnoentitiesnoconv("StandingOrders"))).'">'.$langs->trans("CreateAll")."\n"; + print 'transnoentitiesnoconv("StandingOrders"))).'">'.$langs->trans("CreateAll")."\n"; } print "
    \n"; @@ -175,66 +200,72 @@ if ($socid) $sql.= " AND f.fk_soc = ".$socid; $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; + $num = $db->num_rows($resql); + $i = 0; - print load_fiche_titre($langs->trans("InvoiceWaitingWithdraw").($num > 0?' ('.$num.')':''),'',''); + print load_fiche_titre($langs->trans("InvoiceWaitingWithdraw").($num > 0?' ('.$num.')':''),'',''); - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print '
    '.$langs->trans("Invoice").''.$langs->trans("ThirdParty").''.$langs->trans("RIB").''.$langs->trans("RUM").''.$langs->trans("AmountTTC").''.$langs->trans("DateRequest").'
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - if ($num) - { - $var = True; - while ($i < $num && $i < 20) - { - $obj = $db->fetch_object($resql); + if ($num) + { + require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + $bac = new CompanyBankAccount($db); - print ''; - print ''; - // Thirdparty - print ''; - // RIB - print ''; - // RUM - print ''; - // Amount - print ''; - // Date - print ''; - print ''; - $i++; - } - } - else print ''; - print "
    '.$langs->trans("Invoice").''.$langs->trans("ThirdParty").''.$langs->trans("RIB").''.$langs->trans("RUM").''.$langs->trans("AmountTTC").''.$langs->trans("DateRequest").'
    '; - $invoicestatic->id=$obj->rowid; - $invoicestatic->ref=$obj->facnumber; - print $invoicestatic->getNomUrl(1,'withdraw'); - print ''; - $thirdpartystatic->fetch($obj->socid); - print $thirdpartystatic->getNomUrl(1,'card'); - print ''; - print $thirdpartystatic->display_rib(); - print ''; - print $thirdpartystatic->display_rib('rum'); - print ''; - print price($obj->amount,0,$langs,0,0,-1,$conf->currency); - print ''; - print dol_print_date($db->jdate($obj->date_demande),'day'); - print '
    '.$langs->trans("None").'
    "; - print "
    \n"; + while ($i < $num && $i < 20) + { + $obj = $db->fetch_object($resql); + + print ''; + print ''; + $invoicestatic->id=$obj->rowid; + $invoicestatic->ref=$obj->facnumber; + print $invoicestatic->getNomUrl(1,'withdraw'); + print ''; + // Thirdparty + print ''; + $thirdpartystatic->fetch($obj->socid); + print $thirdpartystatic->getNomUrl(1,'ban'); + print ''; + // RIB + print ''; + print $thirdpartystatic->display_rib(); + $bac->fetch(0, $obj->socid); + if ($bac->verif() <= 0) print img_warning('Error on default bank number for IBAN : '.$bac->error_message); + print ''; + // RUM + print ''; + print $thirdpartystatic->display_rib('rum'); + $format = $thirdpartystatic->display_rib('format'); + if ($format) print ' ('.$format.')'; + print ''; + // Amount + print ''; + print price($obj->amount,0,$langs,0,0,-1,$conf->currency); + print ''; + // Date + print ''; + print dol_print_date($db->jdate($obj->date_demande),'day'); + print ''; + print ''; + $i++; + } + } + else print ''.$langs->trans("None").''; + print ""; + print "
    \n"; } else { - dol_print_error($db); + dol_print_error($db); } diff --git a/htdocs/compta/recap-compta.php b/htdocs/compta/recap-compta.php index c3231ecccdd..4b5351324a3 100644 --- a/htdocs/compta/recap-compta.php +++ b/htdocs/compta/recap-compta.php @@ -1,6 +1,7 @@ * Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2017 Pierre-Henry Favre * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -39,6 +40,9 @@ $result = restrictedArea($user, 'societe', $id, '&societe'); $object = new Societe($db); if ($id > 0) $object->fetch($id); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('recapcomptacard','globalcard')); + // Load variable for pagination $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST('sortfield','alpha'); @@ -60,6 +64,9 @@ $arrayfields=array( /* * Actions */ +$parameters = array('socid' => $id); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object); // Note that $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); // None @@ -139,13 +146,20 @@ if ($id > 0) $userstatic->id=$objf->userid; $userstatic->login=$objf->login; - $TData[] = array( + $values = array( + 'fk_facture' => $objf->facid, 'date' => $fac->date, 'link' => $fac->getNomUrl(1), 'status' => $fac->getLibStatut(2,$totalpaye), 'amount' => $fac->total_ttc, 'author' => $userstatic->getLoginUrl(1) ); + + $parameters = array('socid' => $id, 'values' => &$values, 'fac' => $fac, 'userstatic' => $userstatic); + $reshook = $hookmanager->executeHooks('facdao', $parameters, $object); // Note that $parameters['values'] and $object may have been modified by some hooks + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + $TData[] = $values; $TDataSort[] = $fac->date; // Paiements @@ -175,13 +189,20 @@ if ($id > 0) $userstatic->id=$objp->userid; $userstatic->login=$objp->login; - $TData[] = array( + $values = array( + 'fk_paiement' => $objp->rowid, 'date' => $db->jdate($objp->dp), 'link' => $langs->trans("Payment") .' '. $paymentstatic->getNomUrl(1), 'status' => '', 'amount' => -$objp->amount, 'author' => $userstatic->getLoginUrl(1) ); + + $parameters = array('socid' => $id, 'values' => &$values, 'fac' => $fac, 'userstatic' => $userstatic, 'paymentstatic' => $paymentstatic); + $reshook = $hookmanager->executeHooks('paydao', $parameters, $object); // Note that $parameters['values'] and $object may have been modified by some hooks + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + $TData[] = $values; $TDataSort[] = $db->jdate($objp->dp); $j++; @@ -224,7 +245,11 @@ if ($id > 0) // Display array foreach($TData as $data) { - print ''; + $html_class = ''; + if (!empty($data['fk_facture'])) $html_class = 'facid-'.$data['fk_facture']; + elseif (!empty($data['fk_paiement'])) $html_class = 'payid-'.$data['fk_paiement']; + + print ''; print "".dol_print_date($data['date'],'day')."\n"; print ''.$data['link']."\n"; diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index a7cf8769711..485b9a9b47a 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2011 Laurent Destailleur + * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2012 Cédric Salvador * Copyright (C) 2012-2014 Raphaël Dourseanud @@ -23,8 +23,9 @@ */ /** - * \file htdocs/compta/resultat/clientfourn.php - * \brief Page reporting + * \file htdocs/compta/resultat/clientfourn.php + * \ingroup compta, accountancy + * \brief Page reporting */ require '../../main.inc.php'; @@ -33,18 +34,17 @@ require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php' require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php'; +$langs->loadLangs(array('compta','bills','donation','salaries','accountancy')); -$langs->load("bills"); -$langs->load("donation"); -$langs->load("salaries"); - -$date_startmonth=GETPOST('date_startmonth'); -$date_startday=GETPOST('date_startday'); -$date_startyear=GETPOST('date_startyear'); -$date_endmonth=GETPOST('date_endmonth'); -$date_endday=GETPOST('date_endday'); -$date_endyear=GETPOST('date_endyear'); +$date_startmonth=GETPOST('date_startmonth','int'); +$date_startday=GETPOST('date_startday','int'); +$date_startyear=GETPOST('date_startyear','int'); +$date_endmonth=GETPOST('date_endmonth','int'); +$date_endday=GETPOST('date_endday','int'); +$date_endyear=GETPOST('date_endyear','int'); +$showaccountdetail = GETPOST('showaccountdetail','aZ09')?GETPOST('showaccountdetail','aZ09'):'no'; // Security check $socid = GETPOST('socid','int'); @@ -60,11 +60,11 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield='s.nom, s.rowid'; +//if (! $sortfield) $sortfield='s.nom, s.rowid'; if (! $sortorder) $sortorder='ASC'; // Date range -$year=GETPOST("year"); +$year=GETPOST('year','int'); if (empty($year)) { $year_current = strftime("%Y",dol_now()); @@ -77,7 +77,8 @@ if (empty($year)) } $date_start=dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); $date_end=dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); -// Quarter + +// We define date_start and date_end if (empty($date_start) || empty($date_end)) // We define date_start and date_end { $q=GETPOST("q")?GETPOST("q"):0; @@ -105,25 +106,47 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } } -else -{ - // TODO We define q -} +// $date_start and $date_end are defined. We force $start_year and $nbofyear +$tmps=dol_getdate($date_start); +$start_year = $tmps['year']; +$tmpe=dol_getdate($date_end); +$year_end = $tmpe['year']; +$nbofyear = ($year_end - $start_year) + 1; +//var_dump($start_year." ".$end_year." ".$nbofyear); + +// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES' or 'BOOKKEEPING') +$modecompta = $conf->global->ACCOUNTING_MODE; +if (! empty($conf->accounting->enabled)) $modecompta='BOOKKEEPING'; +if (GETPOST("modecompta",'alpha')) $modecompta=GETPOST("modecompta",'alpha'); + +$AccCat = new AccountancyCategory($db); -// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') -$modecompta=(GETPOST("modecompta")?GETPOST("modecompta"):$conf->global->ACCOUNTING_MODE); /* * View */ +$months = array( + $langs->trans("JanuaryMin"), + $langs->trans("FebruaryMin"), + $langs->trans("MarchMin"), + $langs->trans("AprilMin"), + $langs->trans("MayMin"), + $langs->trans("JuneMin"), + $langs->trans("JulyMin"), + $langs->trans("AugustMin"), + $langs->trans("SeptemberMin"), + $langs->trans("OctoberMin"), + $langs->trans("NovemberMin"), + $langs->trans("DecemberMin"), +); + llxHeader(); $form=new Form($db); -$nomlink=''; $periodlink=''; $exportlink=''; @@ -133,34 +156,53 @@ $total_ttc=0; // Affiche en-tete de rapport if ($modecompta=="CREANCES-DETTES") { - $name=$langs->trans("AnnualByCompaniesDueDebtMode"); + $name = $langs->trans("ReportInOut").', '.$langs->trans("ByPredefinedAccountGroups"); $calcmode=$langs->trans("CalcModeDebt"); - $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + $calcmode.='
    ('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); - //$periodlink=''.img_previous().' '.img_next().''; + $periodlink=($year_start?"".img_previous()." ".img_next()."":""); $description=$langs->trans("RulesResultDue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } -else { - $name=$langs->trans("AnnualByCompaniesInputOutputMode"); +elseif ($modecompta=="RECETTES-DEPENSES") +{ + $name = $langs->trans("ReportInOut").', '.$langs->trans("ByPredefinedAccountGroups"); $calcmode=$langs->trans("CalcModeEngagement"); - $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; + $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; + $calcmode.='
    ('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; //$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',1,1,0,'',1,0,1); $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); - //$periodlink=''.img_previous().' '.img_next().''; + $periodlink=($year_start?"".img_previous()." ".img_next()."":""); $description=$langs->trans("RulesResultInOut"); - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } +elseif ($modecompta=="BOOKKEEPING") +{ + $name = $langs->trans("ReportInOut").', '.$langs->trans("ByPredefinedAccountGroups"); + $calcmode=$langs->trans("CalcModeBookkeeping"); + $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; + //$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',1,1,0,'',1,0,1); + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + $arraylist=array('no'=>$langs->trans("No"), 'yes'=>$langs->trans("AccountWithNonZeroValues"), 'all'=>$langs->trans("All")); + $period.='     '.$langs->trans("DetailByAccount").' '. $form->selectarray('showaccountdetail', $arraylist, $showaccountdetail, 0); + $periodlink=($year_start?"".img_previous()." ".img_next()."":""); + $description=$langs->trans("RulesResultBookkeepingPredefined"); + $description.=' ('.$langs->trans("SeePageForSetup", DOL_URL_ROOT.'/accountancy/admin/account.php?mainmenu=accountancy&leftmenu=accountancy_admin', $langs->transnoentitiesnoconv("Accountancy").' / '.$langs->transnoentitiesnoconv("Setup").' / '.$langs->trans("Chartofaccounts")).')'; + $builddate=dol_now(); + //$exportlink=$langs->trans("NotYetAvailable"); +} $hselected = 'report'; -report_header($name,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array('modecompta'=>$modecompta),$calcmode); +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array('modecompta'=>$modecompta),$calcmode); -if (! empty($conf->accounting->enabled)) +if (! empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') { print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); } @@ -176,452 +218,316 @@ if ($date_endyear) $param.='&date_endyear='.$date_startyear; print ''; print ''; +print_liste_field_titre("PredefinedGroups", $_SERVER["PHP_SELF"], 's.nom, s.rowid','',$param,'',$sortfield,$sortorder,'width200 '); print_liste_field_titre(''); -print_liste_field_titre("Name", $_SERVER["PHP_SELF"],'s.nom, s.rowid','',$param,'',$sortfield,$sortorder); -if ($modecompta == 'CREANCES-DETTES') +if ($modecompta == 'BOOKKEEPING') { - print_liste_field_titre("AmountHT", $_SERVER["PHP_SELF"],'amount_ht','',$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre("Amount", $_SERVER["PHP_SELF"],'amount','',$param,'align="right"',$sortfield,$sortorder); +} +else +{ + if ($modecompta == 'CREANCES-DETTES') + { + print_liste_field_titre("AmountHT", $_SERVER["PHP_SELF"],'amount_ht','',$param,'align="right"',$sortfield,$sortorder); + } + print_liste_field_titre("AmountTTC", $_SERVER["PHP_SELF"],'amount_ttc','',$param,'align="right"',$sortfield,$sortorder); } -print_liste_field_titre("AmountTTC", $_SERVER["PHP_SELF"],'amount_ttc','',$param,'align="right"',$sortfield,$sortorder); print "\n"; -/* - * Factures clients - */ -print ''; -if ($modecompta == 'CREANCES-DETTES') + +if ($modecompta == 'BOOKKEEPING') { - $sql = "SELECT s.nom as name, s.rowid as socid, sum(f.total) as amount_ht, sum(f.total_ttc) as amount_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."facture as f"; - $sql.= " WHERE f.fk_soc = s.rowid"; - $sql.= " AND f.fk_statut IN (1,2)"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) - $sql.= " AND f.type IN (0,1,2,5)"; - else - $sql.= " AND f.type IN (0,1,2,3,5)"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; -} -else -{ - /* - * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les - * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin) - */ - $sql = "SELECT s.nom as name, s.rowid as socid, sum(pf.amount) as amount_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."facture as f"; - $sql.= ", ".MAIN_DB_PREFIX."paiement_facture as pf"; - $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; - $sql.= " WHERE p.rowid = pf.fk_paiement"; - $sql.= " AND pf.fk_facture = f.rowid"; - $sql.= " AND f.fk_soc = s.rowid"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; -} -$sql.= " AND f.entity = ".$conf->entity; -if ($socid) $sql.= " AND f.fk_soc = ".$socid; -$sql.= " GROUP BY s.nom, s.rowid"; -$sql.= $db->order($sortfield, $sortorder); + $predefinedgroupwhere = "("; + //$predefinedgroupwhere.= " (pcg_type = 'EXPENSE' and pcg_subtype in ('PRODUCT','SERVICE'))"; + $predefinedgroupwhere.= " (pcg_type = 'EXPENSE')"; + $predefinedgroupwhere.= " OR "; + //$predefinedgroupwhere.= " (pcg_type = 'INCOME' and pcg_subtype in ('PRODUCT','SERVICE'))"; + $predefinedgroupwhere.= " (pcg_type = 'INCOME')"; + $predefinedgroupwhere.= ")"; -dol_syslog("get customer invoices", LOG_DEBUG); -$result = $db->query($sql); -if ($result) { - $num = $db->num_rows($result); - $i = 0; - while ($i < $num) - { - $objp = $db->fetch_object($result); + $charofaccountstring = $conf->global->CHARTOFACCOUNTS; + $charofaccountstring=dol_getIdFromCode($db, $conf->global->CHARTOFACCOUNTS, 'accounting_system', 'rowid', 'pcg_version'); - print ''; - print "\n"; - - if ($modecompta == 'CREANCES-DETTES') - print "\n"; - print "\n"; - - $total_ht += (isset($objp->amount_ht)?$objp->amount_ht:0); - $total_ttc += $objp->amount_ttc; - print "\n"; - $i++; - } - $db->free($result); -} else { - dol_print_error($db); -} - -// On ajoute les paiements clients anciennes version, non lie par paiement_facture -if ($modecompta != 'CREANCES-DETTES') -{ - $sql = "SELECT 'Autres' as name, '0' as idp, sum(p.amount) as amount_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; - $sql.= " WHERE pf.rowid IS NULL"; - $sql.= " AND p.fk_bank = b.rowid"; - $sql.= " AND b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; - $sql.= " GROUP BY name, idp"; - $sql.= " ORDER BY name"; - - dol_syslog("get old customer payments not linked to invoices", LOG_DEBUG); - $result = $db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $i = 0; - if ($num) { - while ($i < $num) - { - $objp = $db->fetch_object($result); - - - print ''; - print "\n"; - print "\n"; - - $total_ht += (isset($objp->amount_ht)?$objp->amount_ht:0); - $total_ttc += $objp->amount_ttc; - - print "\n"; - $i++; - } - } - $db->free($result); - } else { - dol_print_error($db); - } -} - -if ($total_ttc == 0) -{ - print ''; - print ''; - print ''; -} - -print ''; -if ($modecompta == 'CREANCES-DETTES') - print ''; -print ''; -print ''; - - -/* - * Suppliers invoices - */ -if ($modecompta == 'CREANCES-DETTES') -{ - $sql = "SELECT s.nom as name, s.rowid as socid, sum(f.total_ht) as amount_ht, sum(f.total_ttc) as amount_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= " WHERE f.fk_soc = s.rowid"; - $sql.= " AND f.fk_statut IN (1,2)"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) - $sql.= " AND f.type IN (0,1,2)"; - else - $sql.= " AND f.type IN (0,1,2,3)"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; -} -else -{ - $sql = "SELECT s.nom as name, s.rowid as socid, sum(pf.amount) as amount_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p"; - $sql.= ", ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= " ON pf.fk_facturefourn = f.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s"; - $sql.= " ON f.fk_soc = s.rowid"; - $sql.= " WHERE p.rowid = pf.fk_paiementfourn "; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; -} -$sql.= " AND f.entity = ".$conf->entity; -if ($socid) $sql.= " AND f.fk_soc = ".$socid; -$sql .= " GROUP BY s.nom, s.rowid"; -$sql.= $db->order($sortfield, $sortorder); - -print ''; - -$subtotal_ht = 0; -$subtotal_ttc = 0; -dol_syslog("get suppliers invoices", LOG_DEBUG); -$result = $db->query($sql); -if ($result) { - $num = $db->num_rows($result); - $i = 0; - if ($num > 0) - { - while ($i < $num) - { - $objp = $db->fetch_object($result); - - print ''; - print "\n"; - - if ($modecompta == 'CREANCES-DETTES') - print "\n"; - print "\n"; - - $total_ht -= (isset($objp->amount_ht)?$objp->amount_ht:0); - $total_ttc -= $objp->amount_ttc; - $subtotal_ht += (isset($objp->amount_ht)?$objp->amount_ht:0); - $subtotal_ttc += $objp->amount_ttc; - - print "\n"; - $i++; - } - } - else - { - print ''; - print ''; - print ''; - } - - $db->free($result); -} else { - dol_print_error($db); -} -print ''; -if ($modecompta == 'CREANCES-DETTES') - print ''; -print ''; -print ''; - - - -/* - * Charges sociales non deductibles - */ - -print ''; - -if ($modecompta == 'CREANCES-DETTES') -{ - $sql = "SELECT c.id, c.libelle as label, sum(cs.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; - $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= " WHERE cs.fk_type = c.id"; - $sql.= " AND c.deductible = 0"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND cs.date_ech >= '".$db->idate($date_start)."' AND cs.date_ech <= '".$db->idate($date_end)."'"; -} -else -{ - $sql = "SELECT c.id, c.libelle as label, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; - $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; - $sql.= " WHERE p.fk_charge = cs.rowid"; - $sql.= " AND cs.fk_type = c.id"; - $sql.= " AND c.deductible = 0"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; -} -$sql.= " AND cs.entity = ".$conf->entity; -$sql.= " GROUP BY c.libelle, c.id"; -$newsortfield = $sortfield; -if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'c.libelle, c.id'; -if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; -if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; -$sql.= $db->order($newsortfield, $sortorder); - -dol_syslog("get social contributions deductible=0", LOG_DEBUG); -$result=$db->query($sql); -$subtotal_ht = 0; -$subtotal_ttc = 0; -if ($result) { - $num = $db->num_rows($result); - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); - - $total_ht -= $obj->amount; - $total_ttc -= $obj->amount; - $subtotal_ht += $obj->amount; - $subtotal_ttc += $obj->amount; - - print ''; - print ''; - if ($modecompta == 'CREANCES-DETTES') print ''; - print ''; - print ''; - $i++; - } - } - else { - print ''; - print ''; - print ''; - } -} else { - dol_print_error($db); -} -print ''; -if ($modecompta == 'CREANCES-DETTES') - print ''; -print ''; -print ''; - - -/* - * Charges sociales deductibles - */ - -print ''; - -if ($modecompta == 'CREANCES-DETTES') -{ - $sql = "SELECT c.id, c.libelle as label, sum(cs.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; - $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= " WHERE cs.fk_type = c.id"; - $sql.= " AND c.deductible = 1"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND cs.date_ech >= '".$db->idate($date_start)."' AND cs.date_ech <= '".$db->idate($date_end)."'"; - $sql.= " AND cs.entity = ".$conf->entity; -} -else -{ - $sql = "SELECT c.id, c.libelle as label, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; - $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; - $sql.= " WHERE p.fk_charge = cs.rowid"; - $sql.= " AND cs.fk_type = c.id"; - $sql.= " AND c.deductible = 1"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; - $sql.= " AND cs.entity = ".$conf->entity; -} -$sql.= " GROUP BY c.libelle, c.id"; -$newsortfield = $sortfield; -if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'c.libelle, c.id'; -if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; -if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; -$sql.= $db->order($newsortfield, $sortorder); - -dol_syslog("get social contributions deductible=1", LOG_DEBUG); -$result=$db->query($sql); -$subtotal_ht = 0; -$subtotal_ttc = 0; -if ($result) { - $num = $db->num_rows($result); - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); - - $total_ht -= $obj->amount; - $total_ttc -= $obj->amount; - $subtotal_ht += $obj->amount; - $subtotal_ttc += $obj->amount; - - print ''; - print ''; - if ($modecompta == 'CREANCES-DETTES') - print ''; - print ''; - print ''; - $i++; - } - } - else { - print ''; - print ''; - print ''; - } -} else { - dol_print_error($db); -} -print ''; -if ($modecompta == 'CREANCES-DETTES') - print ''; -print ''; -print ''; - -if ($mysoc->tva_assuj == 'franchise') // Non assujetti -{ - // Total - print ''; - print ''; - print ''; - - print ''; - if ($modecompta == 'CREANCES-DETTES') - print ''; - print ''; - print ''; - - print ''; - print ''; - print ''; -} - - -/* - * Salaries - */ - -if (! empty($conf->salaries->enabled)) -{ - if ($modecompta == 'CREANCES-DETTES') { - $column = 'p.datev'; - } else { - $column = 'p.datep'; - } - - print ''; - $sql = "SELECT u.rowid, u.firstname, u.lastname, p.fk_user, p.label as label, date_format($column,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as p"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user"; - $sql.= " WHERE p.entity = ".$conf->entity; + $sql = "SELECT f.thirdparty_code as name, -1 as socid, aa.pcg_type, aa.pcg_subtype, sum(f.credit - f.debit) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as f"; + $sql.= ", ".MAIN_DB_PREFIX."accounting_account as aa"; + $sql.= " WHERE f.numero_compte = aa.account_number"; + //$sql.= " AND fk_statut in (1,2)"; + $sql.= " AND ".$predefinedgroupwhere; + $sql.= " AND aa.fk_pcg_version = '".$charofaccountstring."'"; if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND $column >= '".$db->idate($date_start)."' AND $column <= '".$db->idate($date_end)."'"; + $sql.= " AND f.doc_date >= '".$db->idate($date_start)."' AND f.doc_date <= '".$db->idate($date_end)."'"; + $sql.= " GROUP BY pcg_type, pcg_subtype, name, socid"; + $sql.= $db->order($sortfield, $sortorder); - $sql.= " GROUP BY u.rowid, u.firstname, u.lastname, p.fk_user, p.label, dm"; - $newsortfield = $sortfield; - if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'u.firstname, u.lastname'; - if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; - if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; - $sql.= $db->order($newsortfield, $sortorder); + $oldpcgtype = ''; + $oldpcgsubtype = ''; - dol_syslog("get payment salaries"); - $result=$db->query($sql); - $subtotal_ht = 0; - $subtotal_ttc = 0; - if ($result) + dol_syslog("get bookkeeping entries", LOG_DEBUG); + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; + if ($num > 0) + { + while ($i < $num) + { + $objp = $db->fetch_object($result); + + if ($objp->pcg_type != $oldpcgtype) + { + print ''; + $oldpcgtype = $objp->pcg_type; + } + + print ''; + print ''; + print '\n"; + print '\n"; + print "\n"; + + $total_ht += (isset($objp->amount)?$objp->amount:0); + $total_ttc += (isset($objp->amount)?$objp->amount:0); + + // Loop on detail of all accounts + // This make 14 calls for each detail of account (NP, N and month m) + if ($showaccountdetail != 'no') + { + $tmppredefinedgroupwhere="pcg_type = '".$db->escape($objp->pcg_type)."' AND pcg_subtype = '".$db->escape($objp->pcg_subtype)."'"; + $tmppredefinedgroupwhere.= " AND fk_pcg_version = '".$charofaccountstring."'"; + //$tmppredefinedgroupwhere.= " AND thirdparty_code = '".$db->escape($objp->name)."'"; + + // Get cpts of category/group + $cpts = $AccCat->getCptsCat(0, $tmppredefinedgroupwhere); + + foreach($cpts as $i => $cpt) + { + $return = $AccCat->getResult($cpt['account_number'], 0, $date_start, $date_end, $cpt['dc']); + if ($return < 0) { + setEventMessages(null, $AccCat->errors, 'errors'); + $resultN=0; + } else { + $resultN=$AccCat->sdc; + } + + + if ($showaccountdetail == 'all' || $resultN > 0) + { + print ''; + print ''; + print ''; + print ''; + print "\n"; + } + } + } + + $i++; + } + } + else + { + print ''; + } + } + else dol_print_error($db); +} +else +{ + /* + * Factures clients + */ + print ''; + + if ($modecompta == 'CREANCES-DETTES') { + $sql = "SELECT s.nom as name, s.rowid as socid, sum(f.total) as amount_ht, sum(f.total_ttc) as amount_ttc"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", ".MAIN_DB_PREFIX."facture as f"; + $sql.= " WHERE f.fk_soc = s.rowid"; + $sql.= " AND f.fk_statut IN (1,2)"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + $sql.= " AND f.type IN (0,1,2,5)"; + else + $sql.= " AND f.type IN (0,1,2,3,5)"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } + elseif ($modecompta == 'RECETTES-DEPENSES') + { + /* + * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les + * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin) + */ + $sql = "SELECT s.nom as name, s.rowid as socid, sum(pf.amount) as amount_ttc"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", ".MAIN_DB_PREFIX."facture as f"; + $sql.= ", ".MAIN_DB_PREFIX."paiement_facture as pf"; + $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; + $sql.= " WHERE p.rowid = pf.fk_paiement"; + $sql.= " AND pf.fk_facture = f.rowid"; + $sql.= " AND f.fk_soc = s.rowid"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } + $sql.= " AND f.entity = ".$conf->entity; + if ($socid) $sql.= " AND f.fk_soc = ".$socid; + $sql.= " GROUP BY name, socid"; + $sql.= $db->order($sortfield, $sortorder); + + dol_syslog("get customer invoices", LOG_DEBUG); + $result = $db->query($sql); + if ($result) { $num = $db->num_rows($result); $i = 0; - if ($num) + while ($i < $num) + { + $objp = $db->fetch_object($result); + + print ''; + print "\n"; + + if ($modecompta == 'CREANCES-DETTES') + print "\n"; + print "\n"; + + $total_ht += (isset($objp->amount_ht)?$objp->amount_ht:0); + $total_ttc += $objp->amount_ttc; + print "\n"; + $i++; + } + $db->free($result); + } else { + dol_print_error($db); + } + + // On ajoute les paiements clients anciennes version, non lie par paiement_facture + if ($modecompta == 'RECETTES-DEPENSES') + { + $sql = "SELECT 'Autres' as name, '0' as idp, sum(p.amount) as amount_ttc"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; + $sql.= " WHERE pf.rowid IS NULL"; + $sql.= " AND p.fk_bank = b.rowid"; + $sql.= " AND b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + $sql.= " GROUP BY name, idp"; + $sql.= " ORDER BY name"; + + dol_syslog("get old customer payments not linked to invoices", LOG_DEBUG); + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; + if ($num) { + while ($i < $num) + { + $objp = $db->fetch_object($result); + + + print ''; + print "\n"; + print "\n"; + + $total_ht += (isset($objp->amount_ht)?$objp->amount_ht:0); + $total_ttc += $objp->amount_ttc; + + print "\n"; + $i++; + } + } + $db->free($result); + } else { + dol_print_error($db); + } + } + + if ($total_ttc == 0) + { + print ''; + print ''; + print ''; + } + + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''; + print ''; + print ''; + + + /* + * Suppliers invoices + */ + if ($modecompta == 'CREANCES-DETTES') + { + $sql = "SELECT s.nom as name, s.rowid as socid, sum(f.total_ht) as amount_ht, sum(f.total_ttc) as amount_ttc"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= " WHERE f.fk_soc = s.rowid"; + $sql.= " AND f.fk_statut IN (1,2)"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + $sql.= " AND f.type IN (0,1,2)"; + else + $sql.= " AND f.type IN (0,1,2,3)"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } + elseif ($modecompta == 'RECETTES-DEPENSES') + { + $sql = "SELECT s.nom as name, s.rowid as socid, sum(pf.amount) as amount_ttc"; + $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p"; + $sql.= ", ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= " ON pf.fk_facturefourn = f.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s"; + $sql.= " ON f.fk_soc = s.rowid"; + $sql.= " WHERE p.rowid = pf.fk_paiementfourn "; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } + + $sql.= " AND f.entity = ".$conf->entity; + if ($socid) $sql.= " AND f.fk_soc = ".$socid; + $sql .= " GROUP BY name, socid"; + $sql.= $db->order($sortfield, $sortorder); + + print ''; + + $subtotal_ht = 0; + $subtotal_ttc = 0; + dol_syslog("get suppliers invoices", LOG_DEBUG); + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; + if ($num > 0) { while ($i < $num) { - $obj = $db->fetch_object($result); - - $total_ht -= $obj->amount; - $total_ttc -= $obj->amount; - $subtotal_ht += $obj->amount; - $subtotal_ttc += $obj->amount; + $objp = $db->fetch_object($result); print ''; + print "\n"; - print "\n"; + if ($modecompta == 'CREANCES-DETTES') + print "\n"; + print "\n"; - if ($modecompta == 'CREANCES-DETTES') print ''; - print ''; - print ''; + $total_ht -= (isset($objp->amount_ht)?$objp->amount_ht:0); + $total_ttc -= $objp->amount_ttc; + $subtotal_ht += (isset($objp->amount_ht)?$objp->amount_ht:0); + $subtotal_ttc += $objp->amount_ttc; + + print "\n"; $i++; } } @@ -631,9 +537,9 @@ if (! empty($conf->salaries->enabled)) print ''; print ''; } - } - else - { + + $db->free($result); + } else { dol_print_error($db); } print ''; @@ -641,377 +547,638 @@ if (! empty($conf->salaries->enabled)) print ''; print ''; print ''; -} -/* - * Expense - */ -if (! empty($conf->expensereport->enabled)) -{ - $langs->load('trips'); - if ($modecompta == 'CREANCES-DETTES') { - $sql = "SELECT p.rowid, p.ref, u.rowid as userid, u.firstname, u.lastname, date_format(date_valid,'%Y-%m') as dm, sum(p.total_ht) as amount_ht,sum(p.total_ttc) as amount_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; - $sql.= " WHERE p.entity = ".getEntity('expensereport'); - $sql.= " AND p.fk_statut>=5"; - $column='p.date_valid'; - } else { - $sql = "SELECT p.rowid, p.ref, u.rowid as userid, u.firstname, u.lastname, date_format(pe.datep,'%Y-%m') as dm, sum(p.total_ht) as amount_ht, sum(p.total_ttc) as amount_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; - $sql.= " WHERE p.entity = ".getEntity('expensereport'); - $sql.= " AND p.fk_statut>=5"; + /* + * Charges sociales non deductibles + */ - $column='pe.datep'; - } + print ''; - print ''; - - if (! empty($date_start) && ! empty($date_end)) + if ($modecompta == 'CREANCES-DETTES') { - $sql.= " AND $column >= '".$db->idate($date_start)."' AND $column <= '".$db->idate($date_end)."'"; + $sql = "SELECT c.id, c.libelle as label, sum(cs.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; + $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql.= " WHERE cs.fk_type = c.id"; + $sql.= " AND c.deductible = 0"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND cs.date_ech >= '".$db->idate($date_start)."' AND cs.date_ech <= '".$db->idate($date_end)."'"; } + elseif ($modecompta == 'RECETTES-DEPENSES') + { + $sql = "SELECT c.id, c.libelle as label, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; + $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; + $sql.= " WHERE p.fk_charge = cs.rowid"; + $sql.= " AND cs.fk_type = c.id"; + $sql.= " AND c.deductible = 0"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } + $sql.= " AND cs.entity = ".$conf->entity; + $sql.= " GROUP BY c.libelle, c.id"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'c.libelle, c.id'; + if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; + if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; - $sql.= " GROUP BY u.rowid, p.rowid, p.ref, u.firstname, u.lastname, dm"; - $newsortfield = $sortfield; - if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'p.ref'; - $sql.= $db->order($newsortfield, $sortorder); + $sql.= $db->order($newsortfield, $sortorder); - dol_syslog("get expense report outcome"); + dol_syslog("get social contributions deductible=0", LOG_DEBUG); $result=$db->query($sql); $subtotal_ht = 0; $subtotal_ttc = 0; - if ($result) - { + if ($result) { $num = $db->num_rows($result); - if ($num) - { - while ($obj = $db->fetch_object($result)) - { - $total_ht -= $obj->amount_ht; - $total_ttc -= $obj->amount_ttc; - $subtotal_ht += $obj->amount_ht; - $subtotal_ttc += $obj->amount_ttc; + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); - print ''; + $total_ht -= $obj->amount; + $total_ttc -= $obj->amount; + $subtotal_ht += $obj->amount; + $subtotal_ttc += $obj->amount; - print "\n"; - - if ($modecompta == 'CREANCES-DETTES') print ''; - print ''; - print ''; - } - } - else - { - print ''; - print ''; - print ''; - } - } - else - { - dol_print_error($db); + print ''; + print ''; + if ($modecompta == 'CREANCES-DETTES') print ''; + print ''; + print ''; + $i++; + } + } + else { + print ''; + print ''; + print ''; + } + } else { + dol_print_error($db); } print ''; if ($modecompta == 'CREANCES-DETTES') print ''; - print ''; - print ''; -} + print ''; + print ''; -/* - * Donations - */ -if (! empty($conf->don->enabled)) -{ - print ''; + /* + * Charges sociales deductibles + */ + + print ''; + if ($modecompta == 'CREANCES-DETTES') { - $sql = "SELECT p.societe as name, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; - $sql.= " WHERE p.entity = ".$conf->entity; - $sql.= " AND fk_statut in (1,2)"; + $sql = "SELECT c.id, c.libelle as label, sum(cs.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; + $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql.= " WHERE cs.fk_type = c.id"; + $sql.= " AND c.deductible = 1"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND cs.date_ech >= '".$db->idate($date_start)."' AND cs.date_ech <= '".$db->idate($date_end)."'"; + $sql.= " AND cs.entity = ".$conf->entity; } - else + elseif ($modecompta == 'RECETTES-DEPENSES') { - $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; - $sql.= " WHERE p.entity = ".getEntity('donation'); - $sql.= " AND fk_statut >= 2"; + $sql = "SELECT c.id, c.libelle as label, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; + $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; + $sql.= " WHERE p.fk_charge = cs.rowid"; + $sql.= " AND cs.fk_type = c.id"; + $sql.= " AND c.deductible = 1"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + $sql.= " AND cs.entity = ".$conf->entity; } - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND p.datedon >= '".$db->idate($date_start)."' AND p.datedon <= '".$db->idate($date_end)."'"; - $sql.= " GROUP BY p.societe, p.firstname, p.lastname, dm"; - $newsortfield = $sortfield; - if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'p.societe, p.firstname, p.lastname, dm'; - if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; - if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; - $sql.= $db->order($newsortfield, $sortorder); + $sql.= " GROUP BY c.libelle, c.id"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'c.libelle, c.id'; + if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; + if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; + $sql.= $db->order($newsortfield, $sortorder); - dol_syslog("get dunning"); + dol_syslog("get social contributions deductible=1", LOG_DEBUG); $result=$db->query($sql); $subtotal_ht = 0; $subtotal_ttc = 0; - if ($result) + if ($result) { + $num = $db->num_rows($result); + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); + + $total_ht -= $obj->amount; + $total_ttc -= $obj->amount; + $subtotal_ht += $obj->amount; + $subtotal_ttc += $obj->amount; + + print ''; + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''; + print ''; + print ''; + $i++; + } + } + else { + print ''; + print ''; + print ''; + } + } else { + dol_print_error($db); + } + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''; + print ''; + print ''; + + if ($mysoc->tva_assuj == 'franchise') // Non assujetti { - $num = $db->num_rows($result); - $i = 0; - if ($num) + // Total + print ''; + print ''; + print ''; + + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''; + print ''; + print ''; + + print ''; + print ''; + print ''; + } + + + /* + * Salaries + */ + + if (! empty($conf->salaries->enabled)) + { + print ''; + + if ($modecompta == 'CREANCES-DETTES' || $modecompta == 'RECETTES-DEPENSES') { - while ($i < $num) + if ($modecompta == 'CREANCES-DETTES') { + $column = 'p.datev'; + } else { + $column = 'p.datep'; + } + + $sql = "SELECT u.rowid, u.firstname, u.lastname, p.fk_user, p.label as label, date_format($column,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as p"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user"; + $sql.= " WHERE p.entity = ".$conf->entity; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND $column >= '".$db->idate($date_start)."' AND $column <= '".$db->idate($date_end)."'"; + + $sql.= " GROUP BY u.rowid, u.firstname, u.lastname, p.fk_user, p.label, dm"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'u.firstname, u.lastname'; + if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; + if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; + $sql.= $db->order($newsortfield, $sortorder); + } + + dol_syslog("get payment salaries"); + $result=$db->query($sql); + $subtotal_ht = 0; + $subtotal_ttc = 0; + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($result); + + $total_ht -= $obj->amount; + $total_ttc -= $obj->amount; + $subtotal_ht += $obj->amount; + $subtotal_ttc += $obj->amount; + + print ''; + + print "\n"; + + if ($modecompta == 'CREANCES-DETTES') print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + print ''; + print ''; + } + } + else + { + dol_print_error($db); + } + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''; + print ''; + print ''; + } + + + /* + * Expense + */ + + if (! empty($conf->expensereport->enabled)) + { + if ($modecompta == 'CREANCES-DETTES' || $modecompta == 'RECETTES-DEPENSES') + { + $langs->load('trips'); + if ($modecompta == 'CREANCES-DETTES') { + $sql = "SELECT p.rowid, p.ref, u.rowid as userid, u.firstname, u.lastname, date_format(date_valid,'%Y-%m') as dm, sum(p.total_ht) as amount_ht,sum(p.total_ttc) as amount_ttc"; + $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; + $sql.= " WHERE p.entity = ".getEntity('expensereport'); + $sql.= " AND p.fk_statut>=5"; + + $column='p.date_valid'; + } else { + $sql = "SELECT p.rowid, p.ref, u.rowid as userid, u.firstname, u.lastname, date_format(pe.datep,'%Y-%m') as dm, sum(p.total_ht) as amount_ht, sum(p.total_ttc) as amount_ttc"; + $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity = " . getEntity('c_paiement'); + $sql.= " WHERE p.entity = ".getEntity('expensereport'); + $sql.= " AND p.fk_statut>=5"; + + $column='pe.datep'; + } + + if (! empty($date_start) && ! empty($date_end)) { - $obj = $db->fetch_object($result); + $sql.= " AND $column >= '".$db->idate($date_start)."' AND $column <= '".$db->idate($date_end)."'"; + } - $total_ht += $obj->amount; - $total_ttc += $obj->amount; - $subtotal_ht += $obj->amount; - $subtotal_ttc += $obj->amount; + $sql.= " GROUP BY u.rowid, p.rowid, p.ref, u.firstname, u.lastname, dm"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'p.ref'; + $sql.= $db->order($newsortfield, $sortorder); + } + print ''; + + dol_syslog("get expense report outcome"); + $result=$db->query($sql); + $subtotal_ht = 0; + $subtotal_ttc = 0; + if ($result) + { + $num = $db->num_rows($result); + if ($num) + { + while ($obj = $db->fetch_object($result)) + { + $total_ht -= $obj->amount_ht; + $total_ttc -= $obj->amount_ttc; + $subtotal_ht += $obj->amount_ht; + $subtotal_ttc += $obj->amount_ttc; + + print ''; + + print "\n"; + + if ($modecompta == 'CREANCES-DETTES') print ''; + print ''; + print ''; + } + } + else + { print ''; - - print "\n"; - - if ($modecompta == 'CREANCES-DETTES') print ''; - print ''; + print ''; print ''; - $i++; } } else { - print ''; - print ''; - print ''; + dol_print_error($db); + } + print ''; + if ($modecompta == 'CREANCES-DETTES') print ''; + print ''; + print ''; + } + + /* + * Donations + */ + + if (! empty($conf->don->enabled)) + { + print ''; + + if ($modecompta == 'CREANCES-DETTES' || $modecompta == 'RECETTES-DEPENSES') + { + if ($modecompta == 'CREANCES-DETTES') + { + $sql = "SELECT p.societe as name, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; + $sql.= " WHERE p.entity = ".$conf->entity; + $sql.= " AND fk_statut in (1,2)"; + } + else + { + $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity = " . getEntity('c_paiement'); + $sql.= " WHERE p.entity = ".getEntity('donation'); + $sql.= " AND fk_statut >= 2"; + } + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datedon >= '".$db->idate($date_start)."' AND p.datedon <= '".$db->idate($date_end)."'"; + } + $sql.= " GROUP BY p.societe, p.firstname, p.lastname, dm"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'p.societe, p.firstname, p.lastname, dm'; + if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; + if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; + $sql.= $db->order($newsortfield, $sortorder); + + dol_syslog("get dunning"); + $result=$db->query($sql); + $subtotal_ht = 0; + $subtotal_ttc = 0; + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($result); + + $total_ht += $obj->amount; + $total_ttc += $obj->amount; + $subtotal_ht += $obj->amount; + $subtotal_ttc += $obj->amount; + + print ''; + + print "\n"; + + if ($modecompta == 'CREANCES-DETTES') print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + print ''; + print ''; + } + } + else + { + dol_print_error($db); + } + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''; + print ''; + print ''; + } + + + /* + * VAT + */ + + print ''; + $subtotal_ht = 0; + $subtotal_ttc = 0; + + if ($conf->tax->enabled && ($modecompta == 'CREANCES-DETTES' || $modecompta == 'RECETTES-DEPENSES')) + { + if ($modecompta == 'CREANCES-DETTES') + { + // TVA a payer + $amount=0; + $sql = "SELECT date_format(f.datef,'%Y-%m') as dm, sum(f.tva) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= " WHERE f.fk_statut IN (1,2)"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + $sql.= " AND f.type IN (0,1,2,5)"; + else + $sql.= " AND f.type IN (0,1,2,3,5)"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " GROUP BY dm"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'dm'; + if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; + if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; + $sql.= $db->order($newsortfield, $sortorder); + + dol_syslog("get vat to pay", LOG_DEBUG); + $result=$db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($result); + + $amount -= $obj->amount; + //$total_ht -= $obj->amount; + $total_ttc -= $obj->amount; + //$subtotal_ht -= $obj->amount; + $subtotal_ttc -= $obj->amount; + $i++; + } + } + } else { + dol_print_error($db); + } + print ''; + print "\n"; + print "\n"; + print "\n"; + print "\n"; + + // TVA a recuperer + $amount=0; + $sql = "SELECT date_format(f.datef,'%Y-%m') as dm, sum(f.total_tva) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= " WHERE f.fk_statut IN (1,2)"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + $sql.= " AND f.type IN (0,1,2)"; + else + $sql.= " AND f.type IN (0,1,2,3)"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " GROUP BY dm"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'dm'; + if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; + if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; + $sql.= $db->order($newsortfield, $sortorder); + + dol_syslog("get vat received back", LOG_DEBUG); + $result=$db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($result); + + $amount += $obj->amount; + //$total_ht += $obj->amount; + $total_ttc += $obj->amount; + //$subtotal_ht += $obj->amount; + $subtotal_ttc += $obj->amount; + + $i++; + } + } + } else { + dol_print_error($db); + } + print ''; + print "\n"; + print "\n"; + print "\n"; + print "\n"; + } + else + { + // VAT really already paid + $amount=0; + $sql = "SELECT date_format(t.datev,'%Y-%m') as dm, sum(t.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; + $sql.= " WHERE amount > 0"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND t.datev >= '".$db->idate($date_start)."' AND t.datev <= '".$db->idate($date_end)."'"; + $sql.= " AND t.entity = ".$conf->entity; + $sql.= " GROUP BY dm"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'dm'; + if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; + if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; + $sql.= $db->order($newsortfield, $sortorder); + + dol_syslog("get vat really paid", LOG_DEBUG); + $result=$db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); + + $amount -= $obj->amount; + $total_ht -= $obj->amount; + $total_ttc -= $obj->amount; + $subtotal_ht -= $obj->amount; + $subtotal_ttc -= $obj->amount; + + $i++; + } + } + $db->free($result); + } else { + dol_print_error($db); + } + print ''; + print "\n"; + if ($modecompta == 'CREANCES-DETTES') + print "\n"; + print "\n"; + print "\n"; + + // VAT really received + $amount=0; + $sql = "SELECT date_format(t.datev,'%Y-%m') as dm, sum(t.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; + $sql.= " WHERE amount < 0"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND t.datev >= '".$db->idate($date_start)."' AND t.datev <= '".$db->idate($date_end)."'"; + $sql.= " AND t.entity = ".$conf->entity; + $sql.= " GROUP BY dm"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'dm'; + if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; + if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; + $sql.= $db->order($newsortfield, $sortorder); + + dol_syslog("get vat really received back", LOG_DEBUG); + $result=$db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); + + $amount += $obj->amount; + $total_ht += $obj->amount; + $total_ttc += $obj->amount; + $subtotal_ht += $obj->amount; + $subtotal_ttc += $obj->amount; + + $i++; + } + } + $db->free($result); + } + else + { + dol_print_error($db); + } + print ''; + print "\n"; + if ($modecompta == 'CREANCES-DETTES') + print "\n"; + print "\n"; + print "\n"; } } - else + + if ($mysoc->tva_assuj != 'franchise') // Assujetti { - dol_print_error($db); + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''; + print ''; + print ''; } - print ''; - if ($modecompta == 'CREANCES-DETTES') - print ''; - print ''; - print ''; -} - -/* - * VAT - */ - -print ''; -$subtotal_ht = 0; -$subtotal_ttc = 0; - -if ($modecompta == 'CREANCES-DETTES') -{ - // TVA a payer - $amount=0; - $sql = "SELECT date_format(f.datef,'%Y-%m') as dm, sum(f.tva) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= " WHERE f.fk_statut IN (1,2)"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) - $sql.= " AND f.type IN (0,1,2,5)"; - else - $sql.= " AND f.type IN (0,1,2,3,5)"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " GROUP BY dm"; - $newsortfield = $sortfield; - if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'dm'; - if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; - if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; - $sql.= $db->order($newsortfield, $sortorder); - - dol_syslog("get vat to pay", LOG_DEBUG); - $result=$db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $db->fetch_object($result); - - $amount -= $obj->amount; - //$total_ht -= $obj->amount; - $total_ttc -= $obj->amount; - //$subtotal_ht -= $obj->amount; - $subtotal_ttc -= $obj->amount; - $i++; - } - } - } else { - dol_print_error($db); - } - print ''; - print "\n"; - print "\n"; - print "\n"; - print "\n"; - - // TVA a recuperer - $amount=0; - $sql = "SELECT date_format(f.datef,'%Y-%m') as dm, sum(f.total_tva) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= " WHERE f.fk_statut IN (1,2)"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) - $sql.= " AND f.type IN (0,1,2)"; - else - $sql.= " AND f.type IN (0,1,2,3)"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " GROUP BY dm"; - $newsortfield = $sortfield; - if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'dm'; - if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; - if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; - $sql.= $db->order($newsortfield, $sortorder); - - dol_syslog("get vat received back", LOG_DEBUG); - $result=$db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $db->fetch_object($result); - - $amount += $obj->amount; - //$total_ht += $obj->amount; - $total_ttc += $obj->amount; - //$subtotal_ht += $obj->amount; - $subtotal_ttc += $obj->amount; - - $i++; - } - } - } else { - dol_print_error($db); - } - print ''; - print "\n"; - print "\n"; - print "\n"; - print "\n"; -} -else -{ - // VAT really already paid - $amount=0; - $sql = "SELECT date_format(t.datev,'%Y-%m') as dm, sum(t.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; - $sql.= " WHERE amount > 0"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND t.datev >= '".$db->idate($date_start)."' AND t.datev <= '".$db->idate($date_end)."'"; - $sql.= " AND t.entity = ".$conf->entity; - $sql.= " GROUP BY dm"; - $newsortfield = $sortfield; - if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'dm'; - if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; - if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; - $sql.= $db->order($newsortfield, $sortorder); - - dol_syslog("get vat really paid", LOG_DEBUG); - $result=$db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); - - $amount -= $obj->amount; - $total_ht -= $obj->amount; - $total_ttc -= $obj->amount; - $subtotal_ht -= $obj->amount; - $subtotal_ttc -= $obj->amount; - - $i++; - } - } - $db->free($result); - } else { - dol_print_error($db); - } - print ''; - print "\n"; - if ($modecompta == 'CREANCES-DETTES') - print "\n"; - print "\n"; - print "\n"; - - // VAT really received - $amount=0; - $sql = "SELECT date_format(t.datev,'%Y-%m') as dm, sum(t.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; - $sql.= " WHERE amount < 0"; - if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND t.datev >= '".$db->idate($date_start)."' AND t.datev <= '".$db->idate($date_end)."'"; - $sql.= " AND t.entity = ".$conf->entity; - $sql.= " GROUP BY dm"; - $newsortfield = $sortfield; - if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'dm'; - if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; - if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; - $sql.= $db->order($newsortfield, $sortorder); - - dol_syslog("get vat really received back", LOG_DEBUG); - $result=$db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); - - $amount += $obj->amount; - $total_ht += $obj->amount; - $total_ttc += $obj->amount; - $subtotal_ht += $obj->amount; - $subtotal_ttc += $obj->amount; - - $i++; - } - } - $db->free($result); - } - else - { - dol_print_error($db); - } - print ''; - print "\n"; - if ($modecompta == 'CREANCES-DETTES') - print "\n"; - print "\n"; - print "\n"; -} - - -if ($mysoc->tva_assuj != 'franchise') // Assujetti -{ - print ''; - if ($modecompta == 'CREANCES-DETTES') - print ''; - print ''; - print ''; } $action = "balanceclient"; diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php index 6043a7cbec5..20333675542 100644 --- a/htdocs/compta/resultat/index.php +++ b/htdocs/compta/resultat/index.php @@ -21,34 +21,88 @@ */ /** - * \file htdocs/compta/resultat/index.php - * \brief Page reporting result + * \file htdocs/compta/resultat/index.php + * \ingroup compta, accountancy + * \brief Page reporting result */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +$langs->loadLangs(array('compta','bills','donation','salaries')); + +$date_startmonth=GETPOST('date_startmonth','int'); +$date_startday=GETPOST('date_startday','int'); +$date_startyear=GETPOST('date_startyear','int'); +$date_endmonth=GETPOST('date_endmonth','int'); +$date_endday=GETPOST('date_endday','int'); +$date_endyear=GETPOST('date_endyear','int'); -$year_start=GETPOST('year_start'); -$year_current = strftime("%Y",time()); $nbofyear=4; -if (! $year_start) { - $year_start = $year_current - ($nbofyear-1); - $year_end = $year_current; + +// Date range +$year=GETPOST('year','int'); +if (empty($year)) +{ + $year_current = strftime("%Y",dol_now()); + $month_current = strftime("%m",dol_now()); + $year_start = $year_current - ($nbofyear - 1); +} else { + $year_current = $year; + $month_current = strftime("%m",dol_now()); + $year_start = $year - ($nbofyear - 1); } -else { - $year_end=$year_start + ($nbofyear-1); +$date_start=dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); +$date_end=dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); + +// We define date_start and date_end +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $q=GETPOST("q")?GETPOST("q"):0; + if ($q==0) + { + // We define date_start and date_end + $year_end=$year_start + ($nbofyear - 1); + $month_start=GETPOST("month")?GETPOST("month"):($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); + if (! GETPOST('month')) + { + if (! GETPOST("year") && $month_start > $month_current) + { + $year_start--; + $year_end--; + } + $month_end=$month_start-1; + if ($month_end < 1) $month_end=12; + else $year_end++; + } + else $month_end=$month_start; + $date_start=dol_get_first_day($year_start,$month_start,false); $date_end=dol_get_last_day($year_end,$month_end,false); + } + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } } +// $date_start and $date_end are defined. We force $start_year and $nbofyear +$tmps=dol_getdate($date_start); +$start_year = $tmps['year']; +$tmpe=dol_getdate($date_end); +$year_end = $tmpe['year']; +$nbofyear = ($year_end - $start_year) + 1; +//var_dump($start_year." ".$end_year." ".$nbofyear); + // Security check $socid = GETPOST('socid','int'); if ($user->societe_id > 0) $socid = $user->societe_id; if (! empty($conf->comptabilite->enabled)) $result=restrictedArea($user,'compta','','','resultat'); if (! empty($conf->accounting->enabled)) $result=restrictedArea($user,'accounting','','','comptarapport'); - -// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') -$modecompta=(GETPOST("modecompta")?GETPOST("modecompta"):$conf->global->ACCOUNTING_MODE); +// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES' or 'BOOKKEEPING') +$modecompta = $conf->global->ACCOUNTING_MODE; +if (! empty($conf->accounting->enabled)) $modecompta='BOOKKEEPING'; +if (GETPOST("modecompta",'alpha')) $modecompta=GETPOST("modecompta",'alpha'); /* @@ -59,41 +113,55 @@ llxHeader(); $form=new Form($db); -$nomlink=''; $exportlink=''; // Affiche en-tete du rapport if ($modecompta == 'CREANCES-DETTES') { - $nom=$langs->trans("AnnualSummaryDueDebtMode"); + $name = $langs->trans("ReportInOut").', '.$langs->trans("ByYear"); $calcmode=$langs->trans("CalcModeDebt"); $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; - $period="$year_start - $year_end"; - $periodlink=($year_start?"".img_previous()."".img_next()."":""); + $calcmode.='
    ('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + $periodlink=($year_start?"".img_previous()."".img_next()."":""); $description=$langs->trans("RulesAmountWithTaxIncluded"); $description.='
    '.$langs->trans("RulesResultDue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.="
    ".$langs->trans("DepositsAreNotIncluded"); else $description.="
    ".$langs->trans("DepositsAreIncluded"); - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } -else { - $nom=$langs->trans("AnnualSummaryInputOutputMode"); +else if ($modecompta=="RECETTES-DEPENSES") { + $name = $langs->trans("ReportInOut").', '.$langs->trans("ByYear"); $calcmode=$langs->trans("CalcModeEngagement"); $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; - $period="$year_start - $year_end"; - $periodlink=($year_start?"".img_previous()."".img_next()."":""); + $calcmode.='
    ('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + $periodlink=($year_start?"".img_previous()."".img_next()."":""); $description=$langs->trans("RulesAmountWithTaxIncluded"); $description.='
    '.$langs->trans("RulesResultInOut"); - $builddate=time(); + $builddate=dol_now(); + //$exportlink=$langs->trans("NotYetAvailable"); +} +else if ($modecompta=="BOOKKEEPING") +{ + $name = $langs->trans("ReportInOut").', '.$langs->trans("ByYear"); + $calcmode=$langs->trans("CalcModeBookkeeping"); + $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + $periodlink=($year_start?"".img_previous()."".img_next()."":""); + $description=$langs->trans("RulesAmountOnInOutBookkeepingRecord"); + $description.=' ('.$langs->trans("SeePageForSetup", DOL_URL_ROOT.'/accountancy/admin/account.php?mainmenu=accountancy&leftmenu=accountancy_admin', $langs->transnoentitiesnoconv("Accountancy").' / '.$langs->transnoentitiesnoconv("Setup").' / '.$langs->trans("Chartofaccounts")).')'; + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } $hselected='report'; -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array('modecompta'=>$modecompta),$calcmode); +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array('modecompta'=>$modecompta),$calcmode); -if (! empty($conf->accounting->enabled)) +if (! empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') { print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); } @@ -103,93 +171,119 @@ if (! empty($conf->accounting->enabled)) /* * Factures clients */ + $subtotal_ht = 0; $subtotal_ttc = 0; -if ($modecompta == 'CREANCES-DETTES') +if (! empty($conf->facture->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta=="RECETTES-DEPENSES")) { - $sql = "SELECT sum(f.total) as amount_ht, sum(f.total_ttc) as amount_ttc, date_format(f.datef,'%Y-%m') as dm"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."facture as f"; - $sql.= " WHERE f.fk_soc = s.rowid"; - $sql.= " AND f.fk_statut IN (1,2)"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2,5)"; - else $sql.= " AND f.type IN (0,1,2,3,5)"; -} -else -{ - /* - * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les - * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin) - */ - $sql = "SELECT sum(pf.amount) as amount_ttc, date_format(p.datep,'%Y-%m') as dm"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= ", ".MAIN_DB_PREFIX."paiement_facture as pf"; - $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; - $sql.= " WHERE p.rowid = pf.fk_paiement"; - $sql.= " AND pf.fk_facture = f.rowid"; -} -$sql.= " AND f.entity = ".$conf->entity; -if ($socid) $sql.= " AND f.fk_soc = $socid"; -$sql.= " GROUP BY dm"; -$sql.= " ORDER BY dm"; - -//print $sql; -dol_syslog("get customers invoices", LOG_DEBUG); -$result=$db->query($sql); -if ($result) -{ - $num = $db->num_rows($result); - $i = 0; - while ($i < $num) + if ($modecompta == 'CREANCES-DETTES') { - $row = $db->fetch_object($result); - $encaiss[$row->dm] = (isset($row->amount_ht)?$row->amount_ht:0); - $encaiss_ttc[$row->dm] = $row->amount_ttc; - $i++; + $sql = "SELECT sum(f.total) as amount_ht, sum(f.total_ttc) as amount_ttc, date_format(f.datef,'%Y-%m') as dm"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", ".MAIN_DB_PREFIX."facture as f"; + $sql.= " WHERE f.fk_soc = s.rowid"; + $sql.= " AND f.fk_statut IN (1,2)"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2,5)"; + else $sql.= " AND f.type IN (0,1,2,3,5)"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } + else if ($modecompta=="RECETTES-DEPENSES") + { + /* + * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les + * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin) + */ + $sql = "SELECT sum(pf.amount) as amount_ttc, date_format(p.datep,'%Y-%m') as dm"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= ", ".MAIN_DB_PREFIX."paiement_facture as pf"; + $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; + $sql.= " WHERE p.rowid = pf.fk_paiement"; + $sql.= " AND pf.fk_facture = f.rowid"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; } - $db->free($result); -} -else { - dol_print_error($db); -} -// On ajoute les paiements clients anciennes version, non lies par paiement_facture -if ($modecompta != 'CREANCES-DETTES') -{ - $sql = "SELECT sum(p.amount) as amount_ttc, date_format(p.datep,'%Y-%m') as dm"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; - $sql.= " WHERE pf.rowid IS NULL"; - $sql.= " AND p.fk_bank = b.rowid"; - $sql.= " AND b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql.= " AND f.entity = ".$conf->entity; + if ($socid) $sql.= " AND f.fk_soc = $socid"; $sql.= " GROUP BY dm"; $sql.= " ORDER BY dm"; - dol_syslog("get old customers payments not linked to invoices", LOG_DEBUG); - $result = $db->query($sql); - if ($result) { + //print $sql; + dol_syslog("get customers invoices", LOG_DEBUG); + $result=$db->query($sql); + if ($result) + { $num = $db->num_rows($result); $i = 0; while ($i < $num) { $row = $db->fetch_object($result); - - if (! isset($encaiss[$row->dm])) $encaiss[$row->dm]=0; - $encaiss[$row->dm] += (isset($row->amount_ht)?$row->amount_ht:0); - - if (! isset($encaiss_ttc[$row->dm])) $encaiss_ttc[$row->dm]=0; - $encaiss_ttc[$row->dm] += $row->amount_ttc; - + $encaiss[$row->dm] = (isset($row->amount_ht)?$row->amount_ht:0); + $encaiss_ttc[$row->dm] = $row->amount_ttc; $i++; } + $db->free($result); } else { dol_print_error($db); } } +else if ($modecompta=="BOOKKEEPING") +{ + // Nothing from this table +} + +if (! empty($conf->facture->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta=="RECETTES-DEPENSES")) +{ + // On ajoute les paiements clients anciennes version, non lies par paiement_facture + if ($modecompta != 'CREANCES-DETTES') + { + $sql = "SELECT sum(p.amount) as amount_ttc, date_format(p.datep,'%Y-%m') as dm"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; + $sql.= " WHERE pf.rowid IS NULL"; + $sql.= " AND p.fk_bank = b.rowid"; + $sql.= " AND b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + $sql.= " GROUP BY dm"; + $sql.= " ORDER BY dm"; + + dol_syslog("get old customers payments not linked to invoices", LOG_DEBUG); + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; + while ($i < $num) + { + $row = $db->fetch_object($result); + + if (! isset($encaiss[$row->dm])) $encaiss[$row->dm]=0; + $encaiss[$row->dm] += (isset($row->amount_ht)?$row->amount_ht:0); + + if (! isset($encaiss_ttc[$row->dm])) $encaiss_ttc[$row->dm]=0; + $encaiss_ttc[$row->dm] += $row->amount_ttc; + + $i++; + } + } + else { + dol_print_error($db); + } + } + else if ($modecompta=="RECETTES-DEPENSES") + { + // Nothing from this table + } +} +else if ($modecompta=="BOOKKEEPING") +{ + // Nothing from this table +} /* @@ -198,231 +292,275 @@ if ($modecompta != 'CREANCES-DETTES') $subtotal_ht = 0; $subtotal_ttc = 0; -if ($modecompta == 'CREANCES-DETTES') +if (! empty($conf->facture->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta=="RECETTES-DEPENSES")) { - $sql = "SELECT sum(f.total_ht) as amount_ht, sum(f.total_ttc) as amount_ttc, date_format(f.datef,'%Y-%m') as dm"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= " WHERE f.fk_statut IN (1,2)"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2)"; - else $sql.= " AND f.type IN (0,1,2,3)"; -} -else -{ - $sql = "SELECT sum(pf.amount) as amount_ttc, date_format(p.datep,'%Y-%m') as dm"; - $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p"; - $sql.= ", ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= ", ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf"; - $sql.= " WHERE f.rowid = pf.fk_facturefourn"; - $sql.= " AND p.rowid = pf.fk_paiementfourn"; -} -$sql.= " AND f.entity = ".$conf->entity; -if ($socid) $sql.= " AND f.fk_soc = ".$socid; -$sql.= " GROUP BY dm"; - -dol_syslog("get suppliers invoices", LOG_DEBUG); -$result=$db->query($sql); -if ($result) -{ - $num = $db->num_rows($result); - $i = 0; - while ($i < $num) + if ($modecompta == 'CREANCES-DETTES') { - $row = $db->fetch_object($result); - - if (! isset($decaiss[$row->dm])) $decaiss[$row->dm]=0; - $decaiss[$row->dm] = (isset($row->amount_ht)?$row->amount_ht:0); - - if (! isset($decaiss_ttc[$row->dm])) $decaiss_ttc[$row->dm]=0; - $decaiss_ttc[$row->dm] = $row->amount_ttc; - - $i++; + $sql = "SELECT sum(f.total_ht) as amount_ht, sum(f.total_ttc) as amount_ttc, date_format(f.datef,'%Y-%m') as dm"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= " WHERE f.fk_statut IN (1,2)"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2)"; + else $sql.= " AND f.type IN (0,1,2,3)"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } + else if ($modecompta=="RECETTES-DEPENSES") + { + $sql = "SELECT sum(pf.amount) as amount_ttc, date_format(p.datep,'%Y-%m') as dm"; + $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p"; + $sql.= ", ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= ", ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf"; + $sql.= " WHERE f.rowid = pf.fk_facturefourn"; + $sql.= " AND p.rowid = pf.fk_paiementfourn"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } + + $sql.= " AND f.entity = ".$conf->entity; + if ($socid) $sql.= " AND f.fk_soc = ".$socid; + $sql.= " GROUP BY dm"; + + dol_syslog("get suppliers invoices", LOG_DEBUG); + $result=$db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + while ($i < $num) + { + $row = $db->fetch_object($result); + + if (! isset($decaiss[$row->dm])) $decaiss[$row->dm]=0; + $decaiss[$row->dm] = (isset($row->amount_ht)?$row->amount_ht:0); + + if (! isset($decaiss_ttc[$row->dm])) $decaiss_ttc[$row->dm]=0; + $decaiss_ttc[$row->dm] = $row->amount_ttc; + + $i++; + } + $db->free($result); + } + else { + dol_print_error($db); } - $db->free($result); } -else { - dol_print_error($db); +else if ($modecompta=="BOOKKEEPING") +{ + // Nothing from this table } + /* * TVA */ + $subtotal_ht = 0; $subtotal_ttc = 0; -if ($modecompta == 'CREANCES-DETTES') +if (! empty($conf->tax->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta=="RECETTES-DEPENSES")) { - // TVA a payer - $sql = "SELECT sum(f.tva) as amount, date_format(f.datef,'%Y-%m') as dm"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= " WHERE f.fk_statut IN (1,2)"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2,5)"; - else $sql.= " AND f.type IN (0,1,2,3,5)"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " GROUP BY dm"; + if ($modecompta == 'CREANCES-DETTES') + { + // TVA a payer + $sql = "SELECT sum(f.tva) as amount, date_format(f.datef,'%Y-%m') as dm"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= " WHERE f.fk_statut IN (1,2)"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2,5)"; + else $sql.= " AND f.type IN (0,1,2,3,5)"; + $sql.= " AND f.entity = ".$conf->entity; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + $sql.= " GROUP BY dm"; - dol_syslog("get vat to pay", LOG_DEBUG); - $result=$db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $var=false; - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); + dol_syslog("get vat to pay", LOG_DEBUG); + $result=$db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $var=false; + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); - if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; - $decaiss[$obj->dm] += $obj->amount; + if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; + $decaiss[$obj->dm] += $obj->amount; - if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; - $decaiss_ttc[$obj->dm] += $obj->amount; + if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; + $decaiss_ttc[$obj->dm] += $obj->amount; - $i++; + $i++; + } } + } else { + dol_print_error($db); + } + // TVA a recuperer + $sql = "SELECT sum(f.total_tva) as amount, date_format(f.datef,'%Y-%m') as dm"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= " WHERE f.fk_statut IN (1,2)"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2)"; + else $sql.= " AND f.type IN (0,1,2,3)"; + $sql.= " AND f.entity = ".$conf->entity; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + $sql.= " GROUP BY dm"; + + dol_syslog("get vat to receive back", LOG_DEBUG); + $result=$db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $var=false; + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); + + if (! isset($encaiss[$obj->dm])) $encaiss[$obj->dm]=0; + $encaiss[$obj->dm] += $obj->amount; + + if (! isset($encaiss_ttc[$obj->dm])) $encaiss_ttc[$obj->dm]=0; + $encaiss_ttc[$obj->dm] += $obj->amount; + + $i++; + } + } + } else { + dol_print_error($db); } - } else { - dol_print_error($db); } - // TVA a recuperer - $sql = "SELECT sum(f.total_tva) as amount, date_format(f.datef,'%Y-%m') as dm"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= " WHERE f.fk_statut IN (1,2)"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2)"; - else $sql.= " AND f.type IN (0,1,2,3)"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " GROUP BY dm"; + else if ($modecompta=="RECETTES-DEPENSES") + { + // TVA reellement deja payee + $sql = "SELECT sum(t.amount) as amount, date_format(t.datev,'%Y-%m') as dm"; + $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; + $sql.= " WHERE amount > 0"; + $sql.= " AND t.entity = ".$conf->entity; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND t.datev >= '".$db->idate($date_start)."' AND t.datev <= '".$db->idate($date_end)."'"; + $sql.= " GROUP BY dm"; - dol_syslog("get vat to receive back", LOG_DEBUG); - $result=$db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $var=false; - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); + dol_syslog("get vat really paid", LOG_DEBUG); + $result=$db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $var=false; + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); - if (! isset($encaiss[$obj->dm])) $encaiss[$obj->dm]=0; - $encaiss[$obj->dm] += $obj->amount; + if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; + $decaiss[$obj->dm] += $obj->amount; - if (! isset($encaiss_ttc[$obj->dm])) $encaiss_ttc[$obj->dm]=0; - $encaiss_ttc[$obj->dm] += $obj->amount; + if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; + $decaiss_ttc[$obj->dm] += $obj->amount; - $i++; + $i++; + } } + } else { + dol_print_error($db); + } + // TVA recuperee + $sql = "SELECT sum(t.amount) as amount, date_format(t.datev,'%Y-%m') as dm"; + $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; + $sql.= " WHERE amount < 0"; + $sql.= " AND t.entity = ".$conf->entity; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND t.datev >= '".$db->idate($date_start)."' AND t.datev <= '".$db->idate($date_end)."'"; + $sql.= " GROUP BY dm"; + + dol_syslog("get vat really received back", LOG_DEBUG); + $result=$db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $var=false; + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); + + if (! isset($encaiss[$obj->dm])) $encaiss[$obj->dm]=0; + $encaiss[$obj->dm] += $obj->amount; + + if (! isset($encaiss_ttc[$obj->dm])) $encaiss_ttc[$obj->dm]=0; + $encaiss_ttc[$obj->dm] += $obj->amount; + + $i++; + } + } + } else { + dol_print_error($db); } - } else { - dol_print_error($db); } } -else { - // TVA reellement deja payee - $sql = "SELECT sum(t.amount) as amount, date_format(t.datev,'%Y-%m') as dm"; - $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; - $sql.= " WHERE amount > 0"; - $sql.= " AND t.entity = ".$conf->entity; - $sql.= " GROUP BY dm"; - - dol_syslog("get vat really paid", LOG_DEBUG); - $result=$db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $var=false; - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); - - if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; - $decaiss[$obj->dm] += $obj->amount; - - if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; - $decaiss_ttc[$obj->dm] += $obj->amount; - - $i++; - } - } - } else { - dol_print_error($db); - } - // TVA recuperee - $sql = "SELECT sum(t.amount) as amount, date_format(t.datev,'%Y-%m') as dm"; - $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; - $sql.= " WHERE amount < 0"; - $sql.= " AND t.entity = ".$conf->entity; - $sql.= " GROUP BY dm"; - - dol_syslog("get vat really received back", LOG_DEBUG); - $result=$db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $var=false; - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); - - if (! isset($encaiss[$obj->dm])) $encaiss[$obj->dm]=0; - $encaiss[$obj->dm] += $obj->amount; - - if (! isset($encaiss_ttc[$obj->dm])) $encaiss_ttc[$obj->dm]=0; - $encaiss_ttc[$obj->dm] += $obj->amount; - - $i++; - } - } - } else { - dol_print_error($db); - } +else if ($modecompta=="BOOKKEEPING") +{ + // Nothing from this table } /* * Charges sociales non deductibles */ + $subtotal_ht = 0; $subtotal_ttc = 0; -if ($modecompta == 'CREANCES-DETTES') +if (! empty($conf->tax->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta=="RECETTES-DEPENSES")) { - $sql = "SELECT c.libelle as nom, date_format(cs.date_ech,'%Y-%m') as dm, sum(cs.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; - $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= " WHERE cs.fk_type = c.id"; - $sql.= " AND c.deductible = 0"; -} -else -{ - $sql = "SELECT c.libelle as nom, date_format(p.datep,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; - $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; - $sql.= " WHERE p.fk_charge = cs.rowid"; - $sql.= " AND cs.fk_type = c.id"; - $sql.= " AND c.deductible = 0"; -} -$sql.= " AND cs.entity = ".$conf->entity; -$sql.= " GROUP BY c.libelle, dm"; - -dol_syslog("get social contributions deductible=0 ", LOG_DEBUG); -$result=$db->query($sql); -if ($result) { - $num = $db->num_rows($result); - $var=false; - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); - - if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; - $decaiss[$obj->dm] += $obj->amount; - - if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; - $decaiss_ttc[$obj->dm] += $obj->amount; - - $i++; - } + if ($modecompta == 'CREANCES-DETTES') + { + $sql = "SELECT c.libelle as nom, date_format(cs.date_ech,'%Y-%m') as dm, sum(cs.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; + $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql.= " WHERE cs.fk_type = c.id"; + $sql.= " AND c.deductible = 0"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND cs.date_ech >= '".$db->idate($date_start)."' AND cs.date_ech <= '".$db->idate($date_end)."'"; + } + else if ($modecompta=="RECETTES-DEPENSES") + { + $sql = "SELECT c.libelle as nom, date_format(p.datep,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; + $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; + $sql.= " WHERE p.fk_charge = cs.rowid"; + $sql.= " AND cs.fk_type = c.id"; + $sql.= " AND c.deductible = 0"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } + + $sql.= " AND cs.entity = ".$conf->entity; + $sql.= " GROUP BY c.libelle, dm"; + + dol_syslog("get social contributions deductible=0 ", LOG_DEBUG); + $result=$db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $var=false; + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); + + if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; + $decaiss[$obj->dm] += $obj->amount; + + if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; + $decaiss_ttc[$obj->dm] += $obj->amount; + + $i++; + } + } + } else { + dol_print_error($db); } -} else { - dol_print_error($db); } +else if ($modecompta=="BOOKKEEPING") +{ + // Nothing from this table +} + /* * Charges sociales deductibles @@ -430,108 +568,120 @@ if ($result) { $subtotal_ht = 0; $subtotal_ttc = 0; -if ($modecompta == 'CREANCES-DETTES') +if (! empty($conf->tax->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta=="RECETTES-DEPENSES")) { - $sql = "SELECT c.libelle as nom, date_format(cs.date_ech,'%Y-%m') as dm, sum(cs.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; - $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= " WHERE cs.fk_type = c.id"; - $sql.= " AND c.deductible = 1"; -} -else -{ - $sql = "SELECT c.libelle as nom, date_format(p.datep,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; - $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; - $sql.= " WHERE p.fk_charge = cs.rowid"; - $sql.= " AND cs.fk_type = c.id"; - $sql.= " AND c.deductible = 1"; -} -$sql.= " AND cs.entity = ".$conf->entity; -$sql.= " GROUP BY c.libelle, dm"; - -dol_syslog("get social contributions paid deductible=1", LOG_DEBUG); -$result=$db->query($sql); -if ($result) { - $num = $db->num_rows($result); - $var=false; - $i = 0; - if ($num) { - while ($i < $num) { - $obj = $db->fetch_object($result); - - if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; - $decaiss[$obj->dm] += $obj->amount; - - if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; - $decaiss_ttc[$obj->dm] += $obj->amount; - - $i++; - } + if ($modecompta == 'CREANCES-DETTES') + { + $sql = "SELECT c.libelle as nom, date_format(cs.date_ech,'%Y-%m') as dm, sum(cs.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; + $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql.= " WHERE cs.fk_type = c.id"; + $sql.= " AND c.deductible = 1"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND cs.date_ech >= '".$db->idate($date_start)."' AND cs.date_ech <= '".$db->idate($date_end)."'"; + } + else if ($modecompta=="RECETTES-DEPENSES") + { + $sql = "SELECT c.libelle as nom, date_format(p.datep,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; + $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; + $sql.= " WHERE p.fk_charge = cs.rowid"; + $sql.= " AND cs.fk_type = c.id"; + $sql.= " AND c.deductible = 1"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } + + $sql.= " AND cs.entity = ".$conf->entity; + $sql.= " GROUP BY c.libelle, dm"; + + dol_syslog("get social contributions paid deductible=1", LOG_DEBUG); + $result=$db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $var=false; + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); + + if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; + $decaiss[$obj->dm] += $obj->amount; + + if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; + $decaiss_ttc[$obj->dm] += $obj->amount; + + $i++; + } + } + } else { + dol_print_error($db); } -} else { - dol_print_error($db); } -$action = "balance"; -$object = array(&$encaiss, &$encaiss_ttc, &$decaiss, &$decaiss_ttc); -$parameters["mode"] = $modecompta; -// Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('externalbalance')); -$reshook=$hookmanager->executeHooks('addReportInfo',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +else if ($modecompta=="BOOKKEEPING") +{ + // Nothing from this table +} /* * Salaries */ -if (! empty($conf->salaries->enabled)) +if (! empty($conf->salaries->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta=="RECETTES-DEPENSES")) { - if ($modecompta == 'CREANCES-DETTES') { - $column = 'p.datev'; - } else { - $column = 'p.datep'; - } + if ($modecompta == 'CREANCES-DETTES') $column = 'p.datev'; + if ($modecompta == "RECETTES-DEPENSES") $column = 'p.datep'; - $subtotal_ht = 0; - $subtotal_ttc = 0; - $sql = "SELECT p.label as nom, date_format($column,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as p"; - $sql.= " WHERE p.entity = ".$conf->entity; - $sql.= " GROUP BY p.label, dm"; + $subtotal_ht = 0; + $subtotal_ttc = 0; + $sql = "SELECT p.label as nom, date_format(".$column.",'%Y-%m') as dm, sum(p.amount) as amount"; + $sql .= " FROM " . MAIN_DB_PREFIX . "payment_salary as p"; + $sql .= " WHERE p.entity = " . $conf->entity; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND ".$column." >= '".$db->idate($date_start)."' AND ".$column." <= '".$db->idate($date_end)."'"; + $sql .= " GROUP BY p.label, dm"; - dol_syslog("get social salaries payments"); - $result=$db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $var=false; - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $db->fetch_object($result); + dol_syslog("get social salaries payments"); + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $var = false; + $i = 0; + if ($num) { + while ($i < $num) { + $obj = $db->fetch_object($result); - if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; - $decaiss[$obj->dm] += $obj->amount; + if (! isset($decaiss[$obj->dm])) + $decaiss[$obj->dm] = 0; + $decaiss[$obj->dm] += $obj->amount; - if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; - $decaiss_ttc[$obj->dm] += $obj->amount; + if (! isset($decaiss_ttc[$obj->dm])) + $decaiss_ttc[$obj->dm] = 0; + $decaiss_ttc[$obj->dm] += $obj->amount; - $i++; - } - } - } - else - { - dol_print_error($db); - } + $i ++; + } + } + } else { + dol_print_error($db); + } +} +elseif ($modecompta == "BOOKKEEPING") +{ + // Nothing from this table } -if (! empty($conf->expensereport->enabled)) + +/* + * Expense reports + */ + +if (! empty($conf->expensereport->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta=="RECETTES-DEPENSES")) { $langs->load('trips'); + if ($modecompta == 'CREANCES-DETTES') { $sql = "SELECT date_format(date_valid,'%Y-%m') as dm, sum(p.total_ht) as amount_ht,sum(p.total_ttc) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; @@ -540,17 +690,21 @@ if (! empty($conf->expensereport->enabled)) $sql.= " AND p.fk_statut>=5"; $column='p.date_valid'; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND ".$column." >= '".$db->idate($date_start)."' AND ".$column." <= '".$db->idate($date_end)."'"; - } else { + } elseif ($modecompta == 'RECETTES-DEPENSES') { $sql = "SELECT date_format(pe.datep,'%Y-%m') as dm, sum(p.total_ht) as amount_ht,sum(p.total_ttc) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity = " . getEntity('c_paiement'); $sql.= " WHERE p.entity = ".getEntity('expensereport'); $sql.= " AND p.fk_statut>=5"; $column='pe.datep'; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND ".$column." >= '".$db->idate($date_start)."' AND ".$column." <= '".$db->idate($date_end)."'"; } $sql.= " GROUP BY dm"; @@ -579,12 +733,18 @@ if (! empty($conf->expensereport->enabled)) { dol_print_error($db); } + } +elseif ($modecompta == 'BOOKKEEPING') { + // Nothing from this table +} + /* * Donation get dunning paiement */ -if (! empty($conf->don->enabled)) + +if (! empty($conf->don->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta=="RECETTES-DEPENSES")) { $subtotal_ht = 0; $subtotal_ttc = 0; @@ -594,15 +754,20 @@ if (! empty($conf->don->enabled)) $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; $sql.= " WHERE p.entity = ".$conf->entity; $sql.= " AND fk_statut in (1,2)"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datedon >= '".$db->idate($date_start)."' AND p.datedon <= '".$db->idate($date_end)."'"; } - else { - $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + elseif ($modecompta == 'RECETTES-DEPENSES') { + $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(pe.datep,'%Y-%m') as dm, sum(p.amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity = " . getEntity('c_paiement'); $sql.= " WHERE p.entity = ".getEntity('donation'); $sql.= " AND fk_statut >= 2"; - } + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND pe.datep >= '".$db->idate($date_start)."' AND pe.datep <= '".$db->idate($date_end)."'"; + } + $sql.= " GROUP BY p.societe, p.firstname, p.lastname, dm"; dol_syslog("get donation payments"); @@ -633,6 +798,78 @@ if (! empty($conf->don->enabled)) dol_print_error($db); } } +elseif ($modecompta == 'BOOKKEEPING') { + // Nothing from this table +} + + + +/* + * Request in mode BOOKKEEPING + */ + +if (! empty($conf->accounting->enabled) && ($modecompta == 'BOOKKEEPING')) +{ + $subtotal_ht = 0; + $subtotal_ttc = 0; + + $sql = "SELECT b.doc_ref, b.numero_compte, b.subledger_account, b.subledger_label, pcg_type, date_format(b.doc_date,'%Y-%m') as dm, sum(b.debit) as debit, sum(b.credit) as credit, sum(b.montant) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b, ".MAIN_DB_PREFIX."accounting_account as aa"; + $sql.= " WHERE b.numero_compte = aa.account_number AND b.entity = ".$conf->entity; + //$sql.= " AND fk_statut in (1,2)"; + $sql.= " AND ("; + //$sql.= " (pcg_type = 'EXPENSE' and pcg_subtype in ('PRODUCT','SERVICE'))"; + $sql.= " (pcg_type = 'EXPENSE')"; + $sql.= " OR "; + //$sql.= " (pcg_type = 'INCOME' and pcg_subtype in ('PRODUCT','SERVICE'))"; + $sql.= " (pcg_type = 'INCOME')"; + $sql.= ")"; + //$sql.= " AND code_journal in ('VT', 'AC')"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND b.doc_date >= '".$db->idate($date_start)."' AND b.doc_date <= '".$db->idate($date_end)."'"; + $sql.= " GROUP BY b.doc_ref, b.numero_compte, b.subledger_account, b.subledger_label, pcg_type, dm"; + + //print $sql; + + dol_syslog("get bookkeeping record"); + $result=$db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $var=false; + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($result); + + if (! isset($encaiss[$obj->dm])) $encaiss[$obj->dm]=0; + $encaiss[$obj->dm] += $obj->debit; + + if (! isset($encaiss_ttc[$obj->dm])) $encaiss_ttc[$obj->dm]=0; + $encaiss_ttc[$obj->dm] += $obj->credit; + + $i++; + } + } + } + else + { + dol_print_error($db); + } +} + + + +$action = "balance"; +$object = array(&$encaiss, &$encaiss_ttc, &$decaiss, &$decaiss_ttc); +$parameters["mode"] = $modecompta; +// Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array('externalbalance')); +$reshook=$hookmanager->executeHooks('addReportInfo',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks + + /* * Show result array @@ -656,10 +893,19 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) } print ''; print ''; +// Loop on each year to ouput for ($annee = $year_start ; $annee <= $year_end ; $annee++) { - print ''; - print ''; + print ''; + print ''; } print ''; @@ -730,7 +976,7 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) { $in=(isset($totentrees[$annee])?price2num($totentrees[$annee], 'MT'):0); $out=(isset($totsorties[$annee])?price2num($totsorties[$annee],'MT'):0); - print price($in-$out).''; + print price(price2num($in-$out, 'MT')).''; // print ''; } } diff --git a/htdocs/compta/resultat/result.php b/htdocs/compta/resultat/result.php new file mode 100644 index 00000000000..3de3cea5d0f --- /dev/null +++ b/htdocs/compta/resultat/result.php @@ -0,0 +1,513 @@ + + * Copyright (C) 2016 Alexandre Spangaro + * Copyright (C) 2018 Laurent Destailleur + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/compta/resultat/result.php + * \ingroup compta, accountancy + * \brief Page for accounting result + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php'; + +$langs->loadLangs(array('compta','bills','donation','salaries','accountancy')); + +$error = 0; + +$mesg = ''; +$action = GETPOST('action','aZ09'); +$cat_id = GETPOST('account_category'); +$selectcpt = GETPOST('cpt_bk'); +$id = GETPOST('id', 'int'); +$rowid = GETPOST('rowid', 'int'); +$cancel = GETPOST('cancel','alpha'); +$showaccountdetail = GETPOST('showaccountdetail','aZ09')?GETPOST('showaccountdetail','aZ09'):'no'; + + +$date_startmonth=GETPOST('date_startmonth','int'); +$date_startday=GETPOST('date_startday','int'); +$date_startyear=GETPOST('date_startyear','int'); +$date_endmonth=GETPOST('date_endmonth','int'); +$date_endday=GETPOST('date_endday','int'); +$date_endyear=GETPOST('date_endyear','int'); + +$nbofyear=1; + +// Date range +$year=GETPOST('year','int'); +if (empty($year)) +{ + $year_current = strftime("%Y", dol_now()); + $month_current = strftime("%m", dol_now()); + $year_start = $year_current - ($nbofyear - 1); +} else { + $year_current = $year; + $month_current = strftime("%m", dol_now()); + $year_start = $year - ($nbofyear - 1); +} +$date_start=dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); +$date_end=dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); + +// We define date_start and date_end +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $q=GETPOST("q")?GETPOST("q"):0; + if ($q==0) + { + // We define date_start and date_end + $year_end=$year_start + ($nbofyear - 1); + $month_start=GETPOST("month")?GETPOST("month"):($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); + $date_startmonth = $month_start; + if (! GETPOST('month')) + { + if (! GETPOST("year") && $month_start > $month_current) + { + $year_start--; + $year_end--; + } + $month_end=$month_start-1; + if ($month_end < 1) $month_end=12; + else $year_end++; + } + else $month_end=$month_start; + $date_start=dol_get_first_day($year_start,$month_start,false); $date_end=dol_get_last_day($year_end,$month_end,false); + } + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } +} + +if (($date_start < dol_time_plus_duree($date_end, -1, 'y')) || ($date_start > $date_end)) +{ + $date_end = dol_time_plus_duree($date_start - 1, 1, 'y'); +} + +// $date_start and $date_end are defined. We force $start_year and $nbofyear +$tmps=dol_getdate($date_start); +$start_year = $tmps['year']; +$tmpe=dol_getdate($date_end); +$year_end = $tmpe['year']; +$nbofyear = ($year_end - $start_year) + 1; + +$date_start_previous = dol_time_plus_duree($date_start, -1, 'y'); +$date_end_previous = dol_time_plus_duree($date_end, -1, 'y'); + +//var_dump($date_start." ".$date_end." ".$date_start_previous." ".$date_end_previous." ".$nbofyear); + + +if($cat_id == 0){ + $cat_id = null; +} + +// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES' or 'BOOKKEEPING') +$modecompta = $conf->global->ACCOUNTING_MODE; +if (! empty($conf->accounting->enabled)) $modecompta='BOOKKEEPING'; +if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta",'alpha'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->comptarapport->lire) + accessforbidden(); + +$AccCat = new AccountancyCategory($db); + + +/* + * View + */ + +$months = array( + $langs->trans("JanuaryMin"), + $langs->trans("FebruaryMin"), + $langs->trans("MarchMin"), + $langs->trans("AprilMin"), + $langs->trans("MayMin"), + $langs->trans("JuneMin"), + $langs->trans("JulyMin"), + $langs->trans("AugustMin"), + $langs->trans("SeptemberMin"), + $langs->trans("OctoberMin"), + $langs->trans("NovemberMin"), + $langs->trans("DecemberMin"), +); + +llxheader('', $langs->trans('ReportInOut')); + +$formaccounting = new FormAccounting($db); +$form = new Form($db); + +$textprevyear = '' . img_previous() . ''; +$textnextyear = ' ' . img_next() . ''; + + + +// Affiche en-tete de rapport +if ($modecompta=="CREANCES-DETTES") +{ + $name=$langs->trans("AnnualByAccountDueDebtMode"); + $calcmode=$langs->trans("CalcModeDebt"); + $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + $calcmode.='
    ('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + //$periodlink=''.img_previous().' '.img_next().''; + $description=$langs->trans("RulesResultDue"); + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); + else $description.= $langs->trans("DepositsAreIncluded"); + $builddate=dol_now(); + //$exportlink=$langs->trans("NotYetAvailable"); +} +else if ($modecompta=="RECETTES-DEPENSES") { + $name=$langs->trans("AnnualByAccountInputOutputMode"); + $calcmode=$langs->trans("CalcModeEngagement"); + $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; + $calcmode.='
    ('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; + //$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',1,1,0,'',1,0,1); + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + //$periodlink=''.img_previous().' '.img_next().''; + $description=$langs->trans("RulesResultInOut"); + $builddate=dol_now(); + //$exportlink=$langs->trans("NotYetAvailable"); +} +else if ($modecompta=="BOOKKEEPING") +{ + $name = $langs->trans("ReportInOut").', '.$langs->trans("ByPersonalizedAccountGroups"); + $calcmode=$langs->trans("CalcModeBookkeeping"); + //$calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; + //$calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + $arraylist=array('no'=>$langs->trans("No"), 'yes'=>$langs->trans("AccountWithNonZeroValues"), 'all'=>$langs->trans("All")); + $period.='     '.$langs->trans("DetailByAccount").' '. $form->selectarray('showaccountdetail', $arraylist, $showaccountdetail, 0); + $periodlink = $textprevyear . " " . $langs->trans("Year") . " " . $start_year . " " . $textnextyear ; + $exportlink = ''; + $description=$langs->trans("RulesResultBookkeepingPersonalized"). + $description.=' ('.$langs->trans("SeePageForSetup", DOL_URL_ROOT.'/accountancy/admin/categories_list.php?search_country_id='.$mysoc->country_id.'&mainmenu=accountancy&leftmenu=accountancy_admin', $langs->transnoentitiesnoconv("Accountancy").' / '.$langs->transnoentitiesnoconv("Setup").' / '.$langs->trans("AccountingCategory")).')'; + //if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); + //else $description.= $langs->trans("DepositsAreIncluded"); + $builddate=dol_now(); +} + +report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink, array('modecompta'=>$modecompta, 'action' => ''), $calcmode); + + +if (! empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') +{ + print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); +} + + +$moreforfilter=''; + +print '
    '; +print '
    '.$langs->trans("CustomersInvoices").'
     ".$langs->trans("Bills").' '.$objp->name."".price($objp->amount_ht)."".price($objp->amount_ttc)."
     ".$langs->trans("Bills")." ".$langs->trans("Other")." (".$langs->trans("PaymentsNotLinkedToInvoice").")\n"; - - if ($modecompta == 'CREANCES-DETTES') - print "".price($objp->amount_ht)."".price($objp->amount_ttc)."
     '.$langs->trans("None").'
    '.price($total_ht).''.price($total_ttc).'
    '.$langs->trans("SuppliersInvoices").'
     ".$langs->trans("Bills")." socid."\">".$objp->name."".price(-$objp->amount_ht)."".price(-$objp->amount_ttc)."
     '.$langs->trans("None").'
    '.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
    '.$langs->trans("SocialContributionsNondeductibles").'
     '.$obj->label.''.price(-$obj->amount).''.price(-$obj->amount).'
     '.$langs->trans("None").'
    '.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
    '.$langs->trans("SocialContributionsDeductibles").'
     '.$obj->label.''.price(-$obj->amount).''.price(-$obj->amount).'
     '.$langs->trans("None").'
    '.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
     
    '.$langs->trans("Profit").''.price($total_ht).''.price($total_ttc).'
     
    '.$langs->trans("Salaries").'
    '.$objp->pcg_type.'
     '.$objp->pcg_type.($objp->pcg_subtype != 'XXXXXX'?' - '.$objp->pcg_subtype:'').($objp->name?' ('.$objp->name.')':'')."'.price($objp->amount)."
        ' . length_accountg($cpt['account_number']) . ' - ' . $cpt['account_label'] . '' . price($resultN) . '
    '.$langs->trans("NoRecordFound").'
    '.$langs->trans("CustomersInvoices").'
     ".$langs->trans("Bills").' '.$objp->name."".price($objp->amount_ht)."".price($objp->amount_ttc)."
     ".$langs->trans("Bills")." ".$langs->trans("Other")." (".$langs->trans("PaymentsNotLinkedToInvoice").")\n"; + + if ($modecompta == 'CREANCES-DETTES') + print "".price($objp->amount_ht)."".price($objp->amount_ttc)."
     '.$langs->trans("None").'
    '.price($total_ht).''.price($total_ttc).'
    '.$langs->trans("SuppliersInvoices").'
     ".$langs->trans("Bills")." socid."\">".$objp->name."".$langs->trans("Salary")." fk_user."\">".$obj->firstname." ".$obj->lastname."".price(-$objp->amount_ht)."".price(-$objp->amount_ttc)."'.price(-$obj->amount).''.price(-$obj->amount).'
    '.$langs->trans("None").'
    '.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
    '.$langs->trans("SocialContributionsNondeductibles").'
    '.$langs->trans("ExpenseReport").'
     ".$langs->trans("ExpenseReport")." userid."\">".$obj->firstname." ".$obj->lastname."'.price(-$obj->amount_ht).''.price(-$obj->amount_ttc).'
     '.$langs->trans("None").'
     '.$obj->label.''.price(-$obj->amount).''.price(-$obj->amount).'
     '.$langs->trans("None").'
    '.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
    '.price(-$subtotal_ttc).'
    '.$langs->trans("Donations").'
    '.$langs->trans("SocialContributionsDeductibles").'
     '.$obj->label.''.price(-$obj->amount).''.price(-$obj->amount).'
     '.$langs->trans("None").'
    '.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
     
    '.$langs->trans("Profit").''.price($total_ht).''.price($total_ttc).'
     
    '.$langs->trans("Salaries").'
     ".$langs->trans("Salary")." fk_user."\">".$obj->firstname." ".$obj->lastname."'.price(-$obj->amount).''.price(-$obj->amount).'
     '.$langs->trans("None").'
    '.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
    '.$langs->trans("ExpenseReport").'
     ".$langs->trans("ExpenseReport")." userid."\">".$obj->firstname." ".$obj->lastname."'.price(-$obj->amount_ht).''.price(-$obj->amount_ttc).'
     ".$langs->trans("Donation")." name."&search_name=".$obj->firstname." ".$obj->lastname."\">".$obj->name. " ".$obj->firstname." ".$obj->lastname."'.price($obj->amount).''.price($obj->amount).''.$langs->trans("None").'
     '.$langs->trans("None").'
    '.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
    '.$langs->trans("Donations").'
     ".$langs->trans("Donation")." name."&search_name=".$obj->firstname." ".$obj->lastname."\">".$obj->name. " ".$obj->firstname." ".$obj->lastname."'.price($obj->amount).''.price($obj->amount).'
     '.$langs->trans("None").'
    '.price($subtotal_ht).''.price($subtotal_ttc).'
    '.$langs->trans("VAT").'
     ".$langs->trans("VATToPay")." ".price($amount)."
     ".$langs->trans("VATToCollect")." ".price($amount)."
     ".$langs->trans("VATPaid")."".price($amount)."".price($amount)."
     ".$langs->trans("VATCollected")."".price($amount)."".price($amount)."
     '.price(price2num($subtotal_ttc,'MT')).'
    '.price($subtotal_ht).''.price($subtotal_ttc).'
    '.$langs->trans("VAT").'
     ".$langs->trans("VATToPay")." ".price($amount)."
     ".$langs->trans("VATToCollect")." ".price($amount)."
     ".$langs->trans("VATPaid")."".price($amount)."".price($amount)."
     ".$langs->trans("VATCollected")."".price($amount)."".price($amount)."
     '.price(price2num($subtotal_ttc,'MT')).'
    '.$langs->trans("Month").''.$langs->trans("Outcome").''.$langs->trans("Income").''; + $htmlhelp=''; + // if ($modecompta == 'RECETTES-DEPENSES') $htmlhelp=$langs->trans("PurchasesPlusVATEarnedAndDue"); + print $form->textwithpicto($langs->trans("Outcome"), $htmlhelp); + print ''; + $htmlhelp=''; + // if ($modecompta == 'RECETTES-DEPENSES') $htmlhelp=$langs->trans("SalesPlusVATToRetreive"); + print $form->textwithpicto($langs->trans("Income"), $htmlhelp); + print '
     
    '."\n"; + +print ''; +print ''; +print ''; +print ''; +print ''; +foreach($months as $k => $v){ + if (($k+1) >= $date_startmonth) + { + print ''; + } +} +foreach($months as $k => $v){ + if (($k+1) < $date_startmonth) + { + print ''; + } +} +print ''; + +if ($modecompta == 'CREANCES-DETTES') +{ + //if (! empty($date_start) && ! empty($date_end)) + // $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; +} +else if ($modecompta=="RECETTES-DEPENSES") +{ + //if (! empty($date_start) && ! empty($date_end)) + // $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; +} +else if ($modecompta=="BOOKKEEPING") +{ + + //All categories + $cats = $AccCat->getCats(); + if ($catsCalcule < 0) dol_print_error($db, $AccCat->error, $AccCat->errors); + + $j=1; + $sommes = array(); + $totPerAccount = array(); + + foreach ($cats as $cat) // Loop on each group + { + if (!empty($cat['category_type'])) // category calculed + { + // When we enter here, $sommes was filled by group of accounts + + $formula = $cat['formula']; + + print ''; + + // Year NP + print ''; + + $vars = array(); + + // Previous Fiscal year (N-1) + foreach($sommes as $code => $det){ + $vars[$code] = $det['NP']; + } + + + $result = strtr($formula, $vars); + + //var_dump($result); + //$r = $AccCat->calculate($result); + $r = dol_eval($result, 1); + //var_dump($r); + + print ''; + + // Year N + $code = $cat['code']; // code of categorie ('VTE', 'MAR', ...) + $sommes[$code]['NP'] += $r; + + // Current fiscal year (N) + if (is_array($sommes) && ! empty($sommes)){ + foreach($sommes as $code => $det){ + $vars[$code] = $det['N']; + } + } + + $result = strtr($formula, $vars); + + //$r = $AccCat->calculate($result); + $r = dol_eval($result, 1); + + print ''; + $sommes[$code]['N'] += $r; + + // Detail by month + foreach($months as $k => $v) + { + if (($k+1) >= $date_startmonth) + { + foreach($sommes as $code => $det){ + $vars[$code] = $det['M'][$k]; + } + $result = strtr($formula, $vars); + + //$r = $AccCat->calculate($result); + $r = dol_eval($result, 1); + + print ''; + $sommes[$code]['M'][$k] += $r; + } + } + foreach($months as $k => $v) + { + if (($k+1) < $date_startmonth) + { + foreach($sommes as $code => $det){ + $vars[$code] = $det['M'][$k]; + } + $result = strtr($formula, $vars); + + //$r = $AccCat->calculate($result); + $r = dol_eval($result, 1); + + print ''; + $sommes[$code]['M'][$k] += $r; + } + } + + + print "\n"; + + //var_dump($sommes); + } + else // normal category + { + $totCat = array(); + $totCat['NP'] = 0; + $totCat['N'] = 0; + $totCat['M'] = array(); + foreach($months as $k => $v) + { + $totCat['M'][$k] = 0; + } + + // Get cpts of category/group + $cpts = $AccCat->getCptsCat($cat['rowid']); + + print ""; + + // Column group + print ''; + + $code = $cat['code']; + + // Set value into column NPrevious, N and each month M ($totCat) + // This make 14 calls for each detail of account (NP, N and month m) + foreach($cpts as $i => $cpt) + { + // N-1 + $return = $AccCat->getResult($cpt['account_number'], 0, $date_start_previous, $date_end_previous, $cpt['dc']); + + if ($return < 0) { + setEventMessages(null, $AccCat->errors, 'errors'); + $resultNP=0; + } else { + $resultNP=$AccCat->sdc; + } + + //N + $return = $AccCat->getResult($cpt['account_number'], 0, $date_start, $date_end, $cpt['dc']); + if ($return < 0) { + setEventMessages(null, $AccCat->errors, 'errors'); + $resultN=0; + } else { + $resultN=$AccCat->sdc; + } + + $totCat['NP'] += $resultNP; + $totCat['N'] += $resultN; + $sommes[$code]['NP'] += $resultNP; + $sommes[$code]['N'] += $resultN; + $totPerAccount[$cpt['account_number']]['NP'] = $resultNP; + $totPerAccount[$cpt['account_number']]['N'] = $resultN; + + foreach($months as $k => $v) + { + $return = $AccCat->getResult($cpt['account_number'], $k+1, $date_start, $date_end, $cpt['dc']); + if ($return < 0) { + setEventMessages(null, $AccCat->errors, 'errors'); + $resultM=0; + } else { + $resultM=$AccCat->sdc; + } + $totCat['M'][$k] += $resultM; + $sommes[$code]['M'][$k] += $resultM; + $totPerAccount[$cpt['account_number']]['M'][$k] = $resultM; + } + } + + // Now output columns for row $code ('VTE', 'MAR', ...) + print ''; + print ''; + + // Each month + foreach($totCat['M'] as $k => $v){ + if (($k+1) >= $date_startmonth) print ''; + } + foreach($totCat['M'] as $k => $v){ + if (($k+1) < $date_startmonth) print ''; + } + + print "\n"; + + // Loop on detail of all accounts + // This make 14 calls for each detail of account (NP, N and month m) + if ($showaccountdetail != 'no') + { + foreach($cpts as $i => $cpt) + { + $resultNP=$totPerAccount[$cpt['account_number']]['NP']; + $resultN=$totPerAccount[$cpt['account_number']]['N']; + + if ($showaccountdetail == 'all' || $resultN > 0) + { + print ''; + print ''; + print ''; + print ''; + print ''; + + // Make one call for each month + foreach($months as $k => $v) + { + if (($k+1) >= $date_startmonth) + { + $resultM=$totPerAccount[$cpt['account_number']]['M'][$k]; + print ''; + } + } + foreach($months as $k => $v) + { + if (($k+1) < $date_startmonth) + { + $resultM=$totPerAccount[$cpt['account_number']]['M'][$k]; + print ''; + } + } + + print "\n"; + } + } + } + } + } +} + +print "
    '.$langs->trans("AccountingCategory").''.$langs->trans("PreviousPeriod").''.$langs->trans("SelectedPeriod").''.$langs->trans($v).''.$langs->trans($v).'
    '; + print $cat['code']; + print ''; + print $cat['label']; + print '' . price($r) . '' . price($r) . '' . price($r) . '' . price($r) . '
    '; + print $cat['code']; + print ''; + print $cat['label']; + if (count($cpts) > 0) // Show example of 5 first accounting accounts + { + $i=0; + foreach($cpts as $cpt) + { + if ($i > 5) + { + print '...)'; + break; + } + if ($i > 0) print ', '; + else print ' ('; + print $cpt['account_number']; + $i++; + } + if ($i <= 5) print ')'; + } + else + { + print ' - '.$langs->trans("GroupIsEmptyCheckSetup").''; + } + print '' . price($totCat['NP']) . '' . price($totCat['N']) . '' . price($v) . '' . price($v) . '
    '; + print '     ' . length_accountg($cpt['account_number']); + print ' - '; + print $cpt['account_label']; + print '' . price($resultNP) . '' . price($resultN) . '' . price($resultM) . '' . price($resultM) . '
    "; +print '
    '; + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/compta/salaries/card.php b/htdocs/compta/salaries/card.php index 2b8b6a6fe5b..a456777f631 100644 --- a/htdocs/compta/salaries/card.php +++ b/htdocs/compta/salaries/card.php @@ -73,6 +73,8 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $dateep=dol_mktime(12,0,0, $_POST["dateepmonth"], $_POST["dateepday"], $_POST["dateepyear"]); if (empty($datev)) $datev=$datep; + $type_payment = dol_getIdFromCode($db, GETPOST("paymenttype", 'alpha'), 'c_paiement'); + $object->accountid=GETPOST("accountid") > 0 ? GETPOST("accountid","int") : 0; $object->fk_user=GETPOST("fk_user") > 0 ? GETPOST("fk_user","int") : 0; $object->datev=$datev; @@ -82,7 +84,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $object->datesp=$datesp; $object->dateep=$dateep; $object->note=GETPOST("note"); - $object->type_payment=GETPOST("paymenttype") > 0 ? GETPOST("paymenttype", "int") : 0; + $object->type_payment=($type_payment > 0 ? $type_payment : 0); $object->num_payment=GETPOST("num_payment"); $object->fk_user_author=$user->id; @@ -101,7 +103,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Employee")), null, 'errors'); $error++; } - if (empty($object->type_payment) || $object->type_payment < 0) + if (empty($type_payment) || $type_payment < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentMode")), null, 'errors'); $error++; @@ -214,6 +216,12 @@ if ($action == 'create') $pastmonthyear--; } + $datespmonth = GETPOST('datespmonth', 'int'); + $datespday = GETPOST('datespday', 'int'); + $datespyear = GETPOST('datespyear', 'int'); + $dateepmonth = GETPOST('dateepmonth', 'int'); + $dateepday = GETPOST('dateepday', 'int'); + $dateepyear = GETPOST('dateepyear', 'int'); $datesp=dol_mktime(0, 0, 0, $datespmonth, $datespday, $datespyear); $dateep=dol_mktime(23, 59, 59, $dateepmonth, $dateepday, $dateepyear); @@ -253,7 +261,7 @@ if ($action == 'create') // Label print ''; print fieldLabel('Label','label',1).''; - print 'trans("SalaryPayment")).'">'; + print 'trans("SalaryPayment")).'">'; print ''; // Date start period @@ -286,7 +294,7 @@ if ($action == 'create') // Type payment print ''; print fieldLabel('PaymentMode','selectpaymenttype',1).''; - $form->select_types_paiements(GETPOST("paymenttype"), "paymenttype"); + $form->select_types_paiements(GETPOST("paymenttype"), "paymenttype", '', 2); print ''; // Number diff --git a/htdocs/compta/salaries/class/paymentsalary.class.php b/htdocs/compta/salaries/class/paymentsalary.class.php index ee2832cb08e..57d2d94f1a3 100644 --- a/htdocs/compta/salaries/class/paymentsalary.class.php +++ b/htdocs/compta/salaries/class/paymentsalary.class.php @@ -108,7 +108,7 @@ class PaymentSalary extends CommonObject $sql.= " datesp='".$this->db->idate($this->datesp)."',"; $sql.= " dateep='".$this->db->idate($this->dateep)."',"; $sql.= " note='".$this->db->escape($this->note)."',"; - $sql.= " fk_bank=".($this->fk_bank > 0 ? "'".$this->fk_bank."'":"null").","; + $sql.= " fk_bank=".($this->fk_bank > 0 ? "'".$this->db->escape($this->fk_bank)."'":"null").","; $sql.= " fk_user_author=".$this->fk_user_author.","; $sql.= " fk_user_modif=".$this->fk_user_modif; @@ -344,18 +344,18 @@ class PaymentSalary extends CommonObject $sql.= ", entity"; $sql.= ") "; $sql.= " VALUES ("; - $sql.= "'".$this->fk_user."'"; + $sql.= "'".$this->db->escape($this->fk_user)."'"; $sql.= ", '".$this->db->idate($this->datep)."'"; $sql.= ", '".$this->db->idate($this->datev)."'"; $sql.= ", ".$this->amount; $sql.= ", ".($this->salary > 0 ? $this->salary : "null"); - $sql.= ", '".$this->type_payment."'"; - $sql.= ", '".$this->num_payment."'"; + $sql.= ", ".$this->db->escape($this->type_payment); + $sql.= ", '".$this->db->escape($this->num_payment)."'"; if ($this->note) $sql.= ", '".$this->db->escape($this->note)."'"; $sql.= ", '".$this->db->escape($this->label)."'"; $sql.= ", '".$this->db->idate($this->datesp)."'"; $sql.= ", '".$this->db->idate($this->dateep)."'"; - $sql.= ", '".$user->id."'"; + $sql.= ", '".$this->db->escape($user->id)."'"; $sql.= ", '".$this->db->idate($now)."'"; $sql.= ", NULL"; $sql.= ", ".$conf->entity; diff --git a/htdocs/compta/salaries/index.php b/htdocs/compta/salaries/index.php index f7c722e3e1d..2da142aff15 100644 --- a/htdocs/compta/salaries/index.php +++ b/htdocs/compta/salaries/index.php @@ -105,7 +105,7 @@ $sql.= " s.rowid, s.fk_user, s.amount, s.salary, s.label, s.datep as datep, s.da $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel,"; $sql.= " pst.code as payment_code"; $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id AND pst.entity = " . getEntity('c_paiement'); $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid,"; $sql.= " ".MAIN_DB_PREFIX."user as u"; @@ -114,7 +114,7 @@ $sql.= " AND s.entity = ".$conf->entity; // Search criteria if ($search_ref) $sql.=" AND s.rowid=".$search_ref; -if ($search_user) $sql.=natural_search(array('u.login', 'u.lastname', 'u.firstname', 'u.email', 'u.note'), $search_user); +if ($search_user) $sql.=natural_search(array('u.login', 'u.lastname', 'u.firstname', 'u.email'), $search_user); if ($search_label) $sql.=natural_search(array('s.label'), $search_label); if ($search_amount) $sql.=natural_search("s.amount", $search_amount, 1); if ($search_account > 0) $sql .=" AND b.fk_account=".$search_account; diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index 0ab82a7cae3..6149a2a92b1 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -25,6 +25,7 @@ */ require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; @@ -33,6 +34,9 @@ if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } +if (! empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; +} $langs->load("compta"); $langs->load("bills"); @@ -63,50 +67,50 @@ if ($action == 'confirm_paid' && $user->rights->tax->charges->creer && $confirm } if ($action == 'reopen' && $user->rights->tax->charges->creer) { - $result = $object->fetch($id); - if ($object->paye) - { - $result = $object->set_unpaid($user); - if ($result > 0) - { - header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); - exit(); - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $result = $object->fetch($id); + if ($object->paye) + { + $result = $object->set_unpaid($user); + if ($result > 0) + { + header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); + exit(); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } // Link to a project if ($action == 'classin' && $user->rights->tax->charges->creer) { - $object->fetch($id); - $object->setProject(GETPOST('projectid')); + $object->fetch($id); + $object->setProject(GETPOST('projectid')); } if ($action == 'setlib' && $user->rights->tax->charges->creer) { - $object->fetch($id); - $result = $object->setValueFrom('libelle', GETPOST('lib'), '', '', 'text', '', $user, 'TAX_MODIFY'); - if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); + $object->fetch($id); + $result = $object->setValueFrom('libelle', GETPOST('lib'), '', '', 'text', '', $user, 'TAX_MODIFY'); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); } // payment mode if ($action == 'setmode' && $user->rights->tax->charges->creer) { - $object->fetch($id); - $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); + $object->fetch($id); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); } // bank account if ($action == 'setbankaccount' && $user->rights->tax->charges->creer) { - $object->fetch($id); - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->fetch($id); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Delete social contribution @@ -131,8 +135,8 @@ if ($action == 'add' && $user->rights->tax->charges->creer) { $dateech=dol_mktime(GETPOST('echhour'),GETPOST('echmin'),GETPOST('echsec'),GETPOST('echmonth'),GETPOST('echday'),GETPOST('echyear')); $dateperiod=dol_mktime(GETPOST('periodhour'),GETPOST('periodmin'),GETPOST('periodsec'),GETPOST('periodmonth'),GETPOST('periodday'),GETPOST('periodyear')); - $amount=price2num(GETPOST('amount')); - $actioncode=GETPOST('actioncode'); + $amount=price2num(GETPOST('amount')); + $actioncode=GETPOST('actioncode'); if (! $dateech) { @@ -166,8 +170,8 @@ if ($action == 'add' && $user->rights->tax->charges->creer) $object->date_ech = $dateech; $object->periode = $dateperiod; $object->amount = $amount; - $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $object->fk_account = GETPOST('fk_account', 'int'); + $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->fk_project = GETPOST('fk_project'); $id=$object->create($user); @@ -182,43 +186,43 @@ if ($action == 'add' && $user->rights->tax->charges->creer) if ($action == 'update' && ! $_POST["cancel"] && $user->rights->tax->charges->creer) { - $dateech=dol_mktime(GETPOST('echhour'),GETPOST('echmin'),GETPOST('echsec'),GETPOST('echmonth'),GETPOST('echday'),GETPOST('echyear')); - $dateperiod=dol_mktime(GETPOST('periodhour'),GETPOST('periodmin'),GETPOST('periodsec'),GETPOST('periodmonth'),GETPOST('periodday'),GETPOST('periodyear')); - $amount=price2num(GETPOST('amount')); + $dateech=dol_mktime(GETPOST('echhour'),GETPOST('echmin'),GETPOST('echsec'),GETPOST('echmonth'),GETPOST('echday'),GETPOST('echyear')); + $dateperiod=dol_mktime(GETPOST('periodhour'),GETPOST('periodmin'),GETPOST('periodsec'),GETPOST('periodmonth'),GETPOST('periodday'),GETPOST('periodyear')); + $amount=price2num(GETPOST('amount')); - if (! $dateech) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("DateDue")), null, 'errors'); - $action = 'edit'; - } - elseif (! $dateperiod) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Period")), null, 'errors'); - $action = 'edit'; - } - elseif (empty($amount)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")), null, 'errors'); - $action = 'edit'; - } + if (! $dateech) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("DateDue")), null, 'errors'); + $action = 'edit'; + } + elseif (! $dateperiod) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Period")), null, 'errors'); + $action = 'edit'; + } + elseif (empty($amount)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")), null, 'errors'); + $action = 'edit'; + } elseif (! is_numeric($amount)) { setEventMessages($langs->trans("ErrorFieldMustBeANumeric",$langs->transnoentities("Amount")), null, 'errors'); $action = 'create'; } - else + else { - $result=$object->fetch($id); + $result=$object->fetch($id); - $object->date_ech = $dateech; - $object->periode = $dateperiod; - $object->amount = price2num($amount); + $object->date_ech = $dateech; + $object->periode = $dateperiod; + $object->amount = price2num($amount); - $result=$object->update($user); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result=$object->update($user); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } } @@ -281,6 +285,7 @@ if ($action == 'confirm_clone' && $confirm == 'yes' && ($user->rights->tax->char $form = new Form($db); $formsocialcontrib = new FormSocialContrib($db); +$bankaccountstatic = new Account($db); if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } $title = $langs->trans("SocialContribution") . ' - ' . $langs->trans("Card"); @@ -293,51 +298,49 @@ if ($action == 'create') { print load_fiche_titre($langs->trans("NewSocialContribution")); - $var=false; + print '
    '; + print ''; + print ''; - print ''; - print ''; - print ''; - - dol_fiche_head(); + dol_fiche_head(); print ''; - // Label - print ""; - print ''; - print ''; - print ''; - print ''; + // Label + print ""; + print ''; + print ''; + print ''; + print ''; - // Type - print ''; - print ''; - print ''; + // Type + print ''; + print ''; + print ''; // Date end period - print ''; - print ''; - print ''; + print ''; - print ''; + print ''; + print ''; - // Amount - print ''; - print ''; - print ''; - print ''; + // Amount + print ''; + print ''; + print ''; + print ''; // Project if (! empty($conf->projet->enabled)) @@ -354,30 +357,30 @@ if ($action == 'create') print ''; } - // Payment Mode - print ''; + // Payment Mode + print ''; - // Bank Account - if (! empty($conf->banque->enabled)) - { - print ''; - } + // Bank Account + if (! empty($conf->banque->enabled)) + { + print ''; + } - // Date due - print ''; - print ''; - print ''; + print ''; - print "\n"; + print ''; + print "\n"; - print '
    '; - print $langs->trans("Label"); - print '
    '; + print $langs->trans("Label"); + print '
    '; - print $langs->trans("Type"); - print ''; - $formsocialcontrib->select_type_socialcontrib(GETPOST("actioncode")?GETPOST("actioncode"):'','actioncode',1); - print '
    '; + print $langs->trans("Type"); + print ''; + $formsocialcontrib->select_type_socialcontrib(GETPOST("actioncode",'alpha')?GETPOST("actioncode",'alpha'):'','actioncode',1); + print '
    '; - print $langs->trans("PeriodEndDate"); - print ''; - print $form->select_date(! empty($dateperiod)?$dateperiod:'-1', 'period', 0, 0, 0, 'charge', 1); + print '
    '; + print $langs->trans("PeriodEndDate"); print '
    '; + print $form->select_date(! empty($dateperiod)?$dateperiod:'-1', 'period', 0, 0, 0, 'charge', 1); + print '
    '; - print $langs->trans("Amount"); - print '
    '; + print $langs->trans("Amount"); + print '
    ' . $langs->trans('PaymentMode') . ''; - $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id'); - print '
    ' . $langs->trans('PaymentMode') . ''; + $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id'); + print '
    ' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print '
    ' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print '
    '; - print $langs->trans("DateDue"); - print ''; - print $form->select_date(! empty($dateech)?$dateech:'-1', 'ech', 0, 0, 0, 'charge', 1); + // Date due + print '
    '; + print $langs->trans("DateDue"); print '
    '; + print $form->select_date(! empty($dateech)?$dateech:'-1', 'ech', 0, 0, 0, 'charge', 1); + print '
    '; + print ''; dol_fiche_end(); @@ -387,7 +390,7 @@ if ($action == 'create') print ''; print '
    '; - print ''; + print ''; } /* *************************************************************************** */ @@ -398,7 +401,7 @@ if ($action == 'create') if ($id > 0) { $object = new ChargeSociales($db); - $result=$object->fetch($id); + $result=$object->fetch($id); if ($result > 0) { @@ -414,7 +417,7 @@ if ($id > 0) ); - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneTax'),$langs->trans('ConfirmCloneTax',$object->ref),'confirm_clone',$formclone,'yes'); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneTax'),$langs->trans('ConfirmCloneTax',$object->ref),'confirm_clone',$formclone,'yes'); } // Confirmation de la suppression de la charge @@ -445,34 +448,34 @@ if ($id > 0) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->tax->charges->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
    '; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects(0, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
    '; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->tax->charges->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects(0, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } } $morehtmlref.='
    '; @@ -492,7 +495,7 @@ if ($id > 0) print ''.$langs->trans("Type")."".$object->type_libelle.""; print ""; - // Period end date + // Period end date print "".$langs->trans("PeriodEndDate").""; print ""; if ($action == 'edit') @@ -517,51 +520,51 @@ if ($id > 0) } // Amount - if ($action == 'edit') - { - print ''.$langs->trans("AmountTTC").""; - print ''; - print ""; - } - else { - print ''.$langs->trans("AmountTTC").''.price($object->amount,0,$outputlangs,1,-1,-1,$conf->currency).''; - } + if ($action == 'edit') + { + print ''.$langs->trans("AmountTTC").""; + print ''; + print ""; + } + else { + print ''.$langs->trans("AmountTTC").''.price($object->amount,0,$outputlangs,1,-1,-1,$conf->currency).''; + } - // Mode of payment - print ''; - print ''; - if ($action != 'editmode') - print ''; - print '
    '; - print $langs->trans('PaymentMode'); - print 'id . '">' . img_edit($langs->trans('SetMode'), 1) . '
    '; - print ''; - if ($action == 'editmode') { - $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id'); - } else { - $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'none'); - } - print ''; + // Mode of payment + print ''; + print ''; + if ($action != 'editmode') + print ''; + print '
    '; + print $langs->trans('PaymentMode'); + print 'id . '">' . img_edit($langs->trans('SetMode'), 1) . '
    '; + print ''; + if ($action == 'editmode') { + $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id'); + } else { + $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'none'); + } + print ''; - // Bank Account - if (! empty($conf->banque->enabled)) - { - print ''; - print ''; - print '
    '; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $user->rights->tax->charges->creer) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; - print ''; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print ''; - print ''; - } + // Bank Account + if (! empty($conf->banque->enabled)) + { + print ''; + print ''; + print '
    '; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->tax->charges->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; + print ''; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print ''; + print ''; + } print ''; @@ -569,77 +572,108 @@ if ($id > 0) print '
    '; print '
    '; + $nbcols = 3; + if (! empty($conf->banque->enabled)) { + $nbcols ++; + } + /* * Payments */ $sql = "SELECT p.rowid, p.num_paiement, datep as dp, p.amount,"; - $sql.= "c.code as type_code,c.libelle as paiement_type"; + $sql.= " c.code as type_code,c.libelle as paiement_type,"; + $sql.= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as p"; + $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; + $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; $sql.= ", ".MAIN_DB_PREFIX."c_paiement as c "; $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " WHERE p.fk_charge = ".$id; $sql.= " AND p.fk_charge = cs.rowid"; $sql.= " AND cs.entity = ".$conf->entity; $sql.= " AND p.fk_typepaiement = c.id"; + $sql.= " AND c.entity = " . getEntity('c_paiement'); $sql.= " ORDER BY dp DESC"; //print $sql; $resql = $db->query($sql); if ($resql) { - $totalpaye = 0; + $totalpaye = 0; - $num = $db->num_rows($resql); - $i = 0; $total = 0; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + $num = $db->num_rows($resql); + $i = 0; $total = 0; + print '
    '.$langs->trans("RefPayment").''.$langs->trans("Date").''.$langs->trans("Type").''.$langs->trans("Amount").'
    '; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) { + print ''; + } + print ''; + print ''; - $var=true; - if ($num > 0) - { - while ($i < $num) - { - $objp = $db->fetch_object($resql); + if ($num > 0) + { + while ($i < $num) + { + $objp = $db->fetch_object($resql); - print "'; - print '\n"; - $labeltype=$langs->trans("PaymentType".$objp->type_code)!=("PaymentType".$objp->type_code)?$langs->trans("PaymentType".$objp->type_code):$objp->paiement_type; - print "\n"; - print '\n"; - print ""; - $totalpaye += $objp->amount; - $i++; - } - } - else - { + print ''; + print '\n"; + $labeltype=$langs->trans("PaymentType".$objp->type_code)!=("PaymentType".$objp->type_code)?$langs->trans("PaymentType".$objp->type_code):$objp->paiement_type; + print "\n"; + if (! empty($conf->banque->enabled)) + { + $bankaccountstatic->id = $objp->baid; + $bankaccountstatic->ref = $objp->baref; + $bankaccountstatic->label = $objp->baref; + $bankaccountstatic->number = $objp->banumber; - print ''; - } + if (! empty($conf->accounting->enabled)) { + $bankaccountstatic->account_number = $objp->account_number; - //if ($object->status == ChargeSociales::STATUS_DRAFT) - //{ - print "\n"; - print "\n"; + $accountingjournal = new AccountingJournal($db); + $accountingjournal->fetch($objp->fk_accountancy_journal); + $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0,1,1,'',1); + } - $resteapayer = $object->amount - $totalpaye; - $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + print ''; + } + print '\n"; + print ""; + $totalpaye += $objp->amount; + $i++; + } + } + else + { - print ""; - print '\n"; - //} - print "
    '.$langs->trans("RefPayment").''.$langs->trans("Date").''.$langs->trans("Type").'' . $langs->trans('BankAccount') . ''.$langs->trans("Amount").'
    "; - print ''.img_object($langs->trans("Payment"),"payment").' '.$objp->rowid.''.dol_print_date($db->jdate($objp->dp),'day')."".$labeltype.' '.$objp->num_paiement."'.price($objp->amount)."
    '; + print ''.img_object($langs->trans("Payment"),"payment").' '.$objp->rowid.''.dol_print_date($db->jdate($objp->dp),'day')."".$labeltype.' '.$objp->num_paiement."
    '.$langs->trans("None").'
    ".$langs->trans("AlreadyPaid")." :".price($totalpaye)."
    ".$langs->trans("AmountExpected")." :".price($object->amount)."
    '; + if ($bankaccountstatic->id) + print $bankaccountstatic->getNomUrl(1, 'transactions'); + print ''.price($objp->amount)."
    ".$langs->trans("RemainderToPay")." :'.price($resteapayer)."
    "; - $db->free($resql); + print ''.$langs->trans("None").''; + print ''; + print ''; + } + + print ''.$langs->trans("AlreadyPaid")." :".price($totalpaye)."\n"; + print ''.$langs->trans("AmountExpected")." :".price($object->amount)."\n"; + + $resteapayer = $object->amount - $totalpaye; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + + print ''.$langs->trans("RemainderToPay")." :"; + print ''.price($resteapayer)."\n"; + + print ""; + $db->free($resql); } else { - dol_print_error($db); + dol_print_error($db); } print '
    '; diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index cf359d691ec..dc089c13e30 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -26,7 +26,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; -/** +/** * Classe permettant la gestion des paiements des charges * La tva collectee n'est calculee que sur les factures payees. */ @@ -36,7 +36,7 @@ class ChargeSociales extends CommonObject public $table='chargesociales'; public $table_element='chargesociales'; public $picto = 'bill'; - + /** * {@inheritdoc} */ @@ -83,7 +83,7 @@ class ChargeSociales extends CommonObject $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql.= " FROM ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as c ON cs.fk_type = c.id"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement').')'; if ($ref) $sql.= " WHERE cs.rowid = ".$ref; else $sql.= " WHERE cs.rowid = ".$id; @@ -110,7 +110,7 @@ class ChargeSociales extends CommonObject $this->paye = $obj->paye; $this->periode = $this->db->jdate($obj->periode); $this->import_key = $this->import_key; - + $this->db->free($resql); return 1; @@ -171,8 +171,8 @@ class ChargeSociales extends CommonObject $sql = "INSERT INTO ".MAIN_DB_PREFIX."chargesociales (fk_type, fk_account, fk_mode_reglement, libelle, date_ech, periode, amount, fk_projet, entity, fk_user_author, date_creation)"; $sql.= " VALUES (".$this->type; - $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); - $sql.= ", ".($this->mode_reglement_id>0?"'".$this->mode_reglement_id."'":"NULL"); + $sql.= ", ".($this->fk_account>0 ? $this->fk_account:'NULL'); + $sql.= ", ".($this->mode_reglement_id>0 ? $this->mode_reglement_id:"NULL"); $sql.= ", '".$this->db->escape($this->lib)."'"; $sql.= ", '".$this->db->idate($this->date_ech)."'"; $sql.= ", '".$this->db->idate($this->periode)."'"; @@ -378,7 +378,7 @@ class ChargeSociales extends CommonObject if ($return) return 1; else return -1; } - + /** * Retourne le libelle du statut d'une charge (impaye, payee) * @@ -445,7 +445,7 @@ class ChargeSociales extends CommonObject if ($statut == 0 && $alreadypaid > 0) return $langs->trans("BillStatusStarted").' '.img_picto($langs->trans("BillStatusStarted"), 'statut3'); if ($statut == 1) return $langs->trans("Paid").' '.img_picto($langs->trans("Paid"), 'statut6'); } - + return "Error, mode/status not found"; } diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index 1d553831f99..0036c61fef9 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -33,6 +33,7 @@ class PaymentSocialContribution extends CommonObject { public $element='paiementcharge'; //!< Id that identify managed objects public $table_element='paiementcharge'; //!< Name of table without prefix where object is stored + public $picto = 'payment'; var $fk_charge; var $datec=''; @@ -78,7 +79,7 @@ class PaymentSocialContribution extends CommonObject $now=dol_now(); dol_syslog(get_class($this)."::create", LOG_DEBUG); - + // Validate parametres if (! $this->datepaye) { @@ -125,7 +126,7 @@ class PaymentSocialContribution extends CommonObject if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."paiementcharge"); - + // Insere tableau des montants / factures foreach ($this->amounts as $key => $amount) { @@ -137,7 +138,7 @@ class PaymentSocialContribution extends CommonObject // If we want to closed payed invoices if ($closepaidcontrib) { - + $contrib=new ChargeSociales($this->db); $contrib->fetch($contribid); $paiement = $contrib->getSommePaiement(); @@ -205,6 +206,7 @@ class PaymentSocialContribution extends CommonObject $sql.= " FROM (".MAIN_DB_PREFIX."c_paiement as pt, ".MAIN_DB_PREFIX."paiementcharge as t)"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id." AND t.fk_typepaiement = pt.id"; + $sql.= " AND pt.entity = " . getEntity('c_paiement'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -612,6 +614,68 @@ class PaymentSocialContribution extends CommonObject } } + + /** + * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * + * @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 Libelle + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut,$mode); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $status Statut + * @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 Libelle du statut + */ + function LibStatut($status,$mode=0) + { + global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage + + $langs->load('compta'); + /*if ($mode == 0) + { + if ($status == 0) return $langs->trans('ToValidate'); + if ($status == 1) return $langs->trans('Validated'); + } + if ($mode == 1) + { + if ($status == 0) return $langs->trans('ToValidate'); + if ($status == 1) return $langs->trans('Validated'); + } + if ($mode == 2) + { + if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate'); + if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated'); + } + if ($mode == 3) + { + if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1'); + if ($status == 1) return img_picto($langs->trans('Validated'),'statut4'); + } + if ($mode == 4) + { + if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate'); + if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated'); + } + if ($mode == 5) + { + if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1'); + if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4'); + } + if ($mode == 6) + { + if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1'); + if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4'); + }*/ + return ''; + } + /** * Return clicable name (with picto eventually) * diff --git a/htdocs/compta/sociales/document.php b/htdocs/compta/sociales/document.php index ce2f853c935..048d35d73f1 100644 --- a/htdocs/compta/sociales/document.php +++ b/htdocs/compta/sociales/document.php @@ -88,6 +88,7 @@ if ($action == 'setlib' && $user->rights->tax->charges->creer) setEventMessages($object->error, $object->errors, 'errors'); } + /* * View */ @@ -125,7 +126,7 @@ if ($object->id) } else { $morehtmlref.=''; } - } + } $morehtmlref.='
    '; $linkback = '' . $langs->trans("BackToList") . ''; @@ -153,9 +154,9 @@ if ($object->id) print ''; print '
    '; - + print '
    '; - + dol_fiche_end(); $modulepart = 'tax'; diff --git a/htdocs/compta/sociales/info.php b/htdocs/compta/sociales/info.php index b67c844a7b9..dfa6439a3f4 100644 --- a/htdocs/compta/sociales/info.php +++ b/htdocs/compta/sociales/info.php @@ -42,6 +42,8 @@ $socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', $id, 'chargesociales','charges'); +$object = new ChargeSociales($db); + /* * Actions @@ -68,7 +70,6 @@ $title = $langs->trans("SocialContribution") . ' - ' . $langs->trans("Info"); $help_url = 'EN:Module_Taxes_and_social_contributions|FR:Module Taxes et dividendes|ES:Módulo Impuestos y cargas sociales (IVA, impuestos)'; llxHeader("",$title,$help_url); -$object = new ChargeSociales($db); $object->fetch($id); $object->info($id); diff --git a/htdocs/compta/sociales/payments.php b/htdocs/compta/sociales/payments.php index 879e9b69ee7..0bdff23007a 100644 --- a/htdocs/compta/sociales/payments.php +++ b/htdocs/compta/sociales/payments.php @@ -133,7 +133,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs,"; $sql.= " ".MAIN_DB_PREFIX."paiementcharge as pc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id AND pct.entity = " . getEntity('c_paiement'); $sql.= " WHERE cs.fk_type = c.id AND pc.fk_charge = cs.rowid"; $sql.= " AND cs.entity = ".$conf->entity; if ($year > 0) diff --git a/htdocs/compta/stats/cabyprodserv.php b/htdocs/compta/stats/cabyprodserv.php index ee6e7f1be27..f367f8ee436 100644 --- a/htdocs/compta/stats/cabyprodserv.php +++ b/htdocs/compta/stats/cabyprodserv.php @@ -27,7 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $langs->load("products"); $langs->load("categories"); @@ -143,12 +143,14 @@ foreach($allparams as $key => $value) { /* * View */ + llxHeader(); + $form=new Form($db); $formother = new FormOther($db); // Show report header -$nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByProductsAndServices"); +$name=$langs->trans("SalesTurnover").', '.$langs->trans("ByProductsAndServices"); if ($modecompta=="CREANCES-DETTES") { $calcmode=$langs->trans("CalcModeDebt"); @@ -163,7 +165,7 @@ if ($modecompta=="CREANCES-DETTES") { $description.= $langs->trans("DepositsAreIncluded"); } - $builddate=time(); + $builddate=dol_now(); } else { $calcmode=$langs->trans("CalcModeEngagement"); $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; @@ -173,17 +175,20 @@ if ($modecompta=="CREANCES-DETTES") { $description=$langs->trans("RulesCAIn"); $description.= $langs->trans("DepositsAreIncluded"); - $builddate=time(); + $builddate=dol_now(); } -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$tableparams,$calcmode); +report_header($name,$namelink,$period,$periodlink,$description,$builddate,$exportlink,$tableparams,$calcmode); -if (! empty($conf->accounting->enabled)) +if (! empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') { print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); } + +$name=array(); + // SQL request $catotal=0; $catotal_ht=0; @@ -266,7 +271,7 @@ if ($modecompta == 'CREANCES-DETTES') print '
    '; print ''."\n"; - + // Category filter print ''; print ''; - + print ''; - + // Array header print ""; print_liste_field_titre( @@ -357,7 +362,7 @@ if ($modecompta == 'CREANCES-DETTES') if (count($name)) { foreach($name as $key=>$value) { - + print ''; // Product @@ -369,15 +374,15 @@ if ($modecompta == 'CREANCES-DETTES') } print "\n"; - + // Quantity print ''; - + // Percent; print ''; - + // Amount w/o VAT print ''; - + // Amount with VAT print ''; - + // Percent; print ''; - + // TODO: statistics? - + print "\n"; $i++; } @@ -423,7 +428,7 @@ if ($modecompta == 'CREANCES-DETTES') } print "
    '; @@ -283,11 +288,11 @@ if ($modecompta == 'CREANCES-DETTES') print $langs->trans("Type"). ': '; $form->select_type_of_lines(isset($selected_type)?$selected_type:-1,'search_type',1,1,1); print ''; print ''; print '
    ".$linkname."'; print $qty[$key]; print ''.($qtytotal > 0 ? round(100 * $qty[$key] / $qtytotal, 2).'%' : ' ').''; /*if ($key > 0) { @@ -388,7 +393,7 @@ if ($modecompta == 'CREANCES-DETTES') print price($amount_ht[$key]); //print ''; print ''; /*if ($key > 0) { @@ -399,12 +404,12 @@ if ($modecompta == 'CREANCES-DETTES') print price($amount[$key]); //print ''; print ''.($catotal > 0 ? round(100 * $amount[$key] / $catotal, 2).'%' : ' ').'
    "; print '
    '; - + print ''; } else { // $modecompta != 'CREANCES-DETTES' diff --git a/htdocs/compta/stats/cabyuser.php b/htdocs/compta/stats/cabyuser.php index ad9a8fbd346..4904f1ee5ca 100644 --- a/htdocs/compta/stats/cabyuser.php +++ b/htdocs/compta/stats/cabyuser.php @@ -131,12 +131,11 @@ foreach($allparams as $key => $value) { llxHeader(); - $form=new Form($db); // Show report header if ($modecompta=="CREANCES-DETTES") { - $nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice"); + $name=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice"); $calcmode=$langs->trans("CalcModeDebt"); $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); @@ -144,30 +143,32 @@ if ($modecompta=="CREANCES-DETTES") { $description=$langs->trans("RulesCADue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } else { - $nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice"); + $name=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice"); $calcmode=$langs->trans("CalcModeEngagement"); $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); //$periodlink="".img_previous()." ".img_next().""; $description=$langs->trans("RulesCAIn"); $description.= $langs->trans("DepositsAreIncluded"); - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } $moreparam=array(); if (! empty($modecompta)) $moreparam['modecompta']=$modecompta; -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$moreparam,$calcmode); +report_header($name,$namelink,$period,$periodlink,$description,$builddate,$exportlink,$moreparam,$calcmode); -if (! empty($conf->accounting->enabled)) +if (! empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') { print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); } +$name=array(); + // Show array print '
    '; // Extra parameters management @@ -350,9 +351,9 @@ if (count($amount)) { } $i = 0; - + foreach($arrayforsort as $key => $value) { - + print ''; // Third party diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php index fdba026ac6f..f59b6fc454f 100644 --- a/htdocs/compta/stats/casoc.php +++ b/htdocs/compta/stats/casoc.php @@ -32,7 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $langs->load("companies"); $langs->load("categories"); @@ -165,7 +165,7 @@ $formother = new FormOther($db); // Show report header if ($modecompta=="CREANCES-DETTES") { - $nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByThirdParties"); + $name=$langs->trans("SalesTurnover").', '.$langs->trans("ByThirdParties"); $calcmode=$langs->trans("CalcModeDebt"); $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); @@ -173,28 +173,30 @@ if ($modecompta=="CREANCES-DETTES") $description=$langs->trans("RulesCADue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } else { - $nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByThirdParties"); + $name=$langs->trans("SalesTurnover").', '.$langs->trans("ByThirdParties"); $calcmode=$langs->trans("CalcModeEngagement"); $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); //$periodlink=''.img_previous().' '.img_next().''; $description=$langs->trans("RulesCAIn"); $description.= $langs->trans("DepositsAreIncluded"); - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$tableparams,$calcmode); +report_header($name,$namelink,$period,$periodlink,$description,$builddate,$exportlink,$tableparams,$calcmode); -if (! empty($conf->accounting->enabled)) +if (! empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') { print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); } +$name=array(); + // Show Array $catotal=0; if ($modecompta == 'CREANCES-DETTES') { diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index 19c106a44dc..335cf581740 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -2,6 +2,7 @@ /* Copyright (C) 2001-2004 Rodolphe Quiedeville * Copyright (C) 2004-2012 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2017 Olivier Geffroy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,21 +25,69 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + +$langs->loadLangs(array('compta','bills','donation','salaries')); + +$date_startmonth=GETPOST('date_startmonth'); +$date_startday=GETPOST('date_startday'); +$date_startyear=GETPOST('date_startyear'); +$date_endmonth=GETPOST('date_endmonth'); +$date_endday=GETPOST('date_endday'); +$date_endyear=GETPOST('date_endyear'); -$year_start=GETPOST("year_start"); -$year_current = strftime("%Y",time()); $nbofyear=4; -if (! $year_start) { - $year_start = $year_current - ($nbofyear-1); - $year_end = $year_current; + +// Date range +$year=GETPOST('year','int'); +if (empty($year)) +{ + $year_current = strftime("%Y",dol_now()); + $month_current = strftime("%m",dol_now()); + $year_start = $year_current - ($nbofyear - 1); +} else { + $year_current = $year; + $month_current = strftime("%m",dol_now()); + $year_start = $year - ($nbofyear - 1); } -else { - $year_end=$year_start + ($nbofyear-1); +$date_start=dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); +$date_end=dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); + +// We define date_start and date_end +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $q=GETPOST("q")?GETPOST("q"):0; + if ($q==0) + { + // We define date_start and date_end + $year_end=$year_start + ($nbofyear - 1); + $month_start=GETPOST("month")?GETPOST("month"):($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); + if (! GETPOST('month')) + { + if (! GETPOST("year") && $month_start > $month_current) + { + $year_start--; + $year_end--; + } + $month_end=$month_start-1; + if ($month_end < 1) $month_end=12; + else $year_end++; + } + else $month_end=$month_start; + $date_start=dol_get_first_day($year_start,$month_start,false); $date_end=dol_get_last_day($year_end,$month_end,false); + } + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } } + $userid=GETPOST('userid','int'); $socid = GETPOST('socid','int'); -// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') + +// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES' or 'BOOKKEEPING') $modecompta = $conf->global->ACCOUNTING_MODE; +if (! empty($conf->accounting->enabled)) $modecompta='BOOKKEEPING'; if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta",'alpha'); // Security check @@ -54,38 +103,57 @@ if (! empty($conf->accounting->enabled)) $result=restrictedArea($user,'accountin */ llxHeader(); + $form=new Form($db); // Affiche en-tete du rapport if ($modecompta=="CREANCES-DETTES") { - $nom=$langs->trans("SalesTurnover"); + $name=$langs->trans("SalesTurnover"); $calcmode=$langs->trans("CalcModeDebt"); $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; - $period="$year_start - $year_end"; + $calcmode.='
    ('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); $periodlink=($year_start?"".img_previous()." ".img_next()."":""); $description=$langs->trans("RulesCADue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } -else { - $nom=$langs->trans("SalesTurnover"); +else if ($modecompta=="RECETTES-DEPENSES") +{ + $name=$langs->trans("SalesTurnover"); $calcmode=$langs->trans("CalcModeEngagement"); $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; - $period="$year_start - $year_end"; + $calcmode.='
    ('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); $periodlink=($year_start?"".img_previous()." ".img_next()."":""); $description=$langs->trans("RulesCAIn"); $description.= $langs->trans("DepositsAreIncluded"); - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } +else if ($modecompta=="BOOKKEEPING") +{ + $name=$langs->trans("SalesTurnover"); + $calcmode=$langs->trans("CalcModeBookkeeping"); + $calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; + $calcmode.='
    ('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + $periodlink=($year_start?"".img_previous()." ".img_next()."":""); + $description=$langs->trans("RulesCADue"); + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); + else $description.= $langs->trans("DepositsAreIncluded"); + $builddate=dol_now(); + //$exportlink=$langs->trans("NotYetAvailable"); +} + $moreparam=array(); if (! empty($modecompta)) $moreparam['modecompta']=$modecompta; -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$moreparam,$calcmode); +report_header($name,$namelink,$period,$periodlink,$description,$builddate,$exportlink,$moreparam,$calcmode); -if (! empty($conf->accounting->enabled)) +if (! empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') { print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); } @@ -98,8 +166,10 @@ if ($modecompta == 'CREANCES-DETTES') $sql.= " WHERE f.fk_statut in (1,2)"; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2,5)"; else $sql.= " AND f.type IN (0,1,2,3,5)"; + $sql.= " AND f.entity = ".$conf->entity; +if ($socid) $sql.= " AND f.fk_soc = ".$socid; } -else +else if ($modecompta=="RECETTES-DEPENSES") { /* * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les @@ -111,9 +181,19 @@ else $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; $sql.= " WHERE p.rowid = pf.fk_paiement"; $sql.= " AND pf.fk_facture = f.rowid"; -} -$sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND f.entity = ".$conf->entity; if ($socid) $sql.= " AND f.fk_soc = ".$socid; +} +else if ($modecompta=="BOOKKEEPING") +{ + $sql = "SELECT date_format(b.doc_date,'%Y-%m') as dm, sum(b.credit) as amount_ttc"; + $sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b"; + $sql.= " WHERE b.numero_compte IN (SELECT a.account_number" ; + $sql.= " FROM ".MAIN_DB_PREFIX."accounting_account as a"; + $sql.= " WHERE a.fk_accounting_category = 1 ) " ; // todo sql with accounting category, but we need to define category in turnover +} + + $sql.= " GROUP BY dm"; $sql.= " ORDER BY dm"; @@ -222,7 +302,7 @@ for ($mois = 1+$nb_mois_decalage ; $mois <= 12+$nb_mois_decalage ; $mois++) { $mois_modulo = $mois;// ajout if($mois>12){$mois_modulo = $mois-12;} // ajout - + print ''; print "".dol_print_date(dol_mktime(12,0,0,$mois_modulo,1,2000),"%B").""; @@ -312,7 +392,7 @@ for ($mois = 1+$nb_mois_decalage ; $mois <= 12+$nb_mois_decalage ; $mois++) /* for ($mois = 1 ; $mois < 13 ; $mois++) { - + print ''; print "".dol_print_date(dol_mktime(12,0,0,$mois,1,2000),"%B").""; @@ -480,8 +560,8 @@ print '
    '; $totalam_Rac += $obj->am; $i++; } - - print "Facture a encaisser : ".price($total_ttc_Rac)."<-- bug ici car n'exclut pas le deja r�gl� des factures partiellement r�gl�es"; + + print "Facture a encaisser : ".price($total_ttc_Rac)."<-- bug ici car n'exclut pas le deja r?gl? des factures partiellement r?gl?es"; } $db->free($resql); } @@ -530,7 +610,7 @@ print '
    '; $total_pr += $obj->total_ttc-$obj->tot_fttc; $i++; } - + print "Signe et non facture:".price($total_pr)."<-- bug ici, ca devrait exclure le deja facture"; } $db->free($resql); diff --git a/htdocs/compta/tva/class/tva.class.php b/htdocs/compta/tva/class/tva.class.php index df1bc8c03cf..5d170faf67e 100644 --- a/htdocs/compta/tva/class/tva.class.php +++ b/htdocs/compta/tva/class/tva.class.php @@ -106,12 +106,12 @@ class Tva extends CommonObject $sql.= " '".$this->db->idate($now)."',"; $sql.= " '".$this->db->idate($this->datep)."',"; $sql.= " '".$this->db->idate($this->datev)."',"; - $sql.= " '".$this->amount."',"; - $sql.= " '".$this->label."',"; - $sql.= " '".$this->note."',"; - $sql.= " ".($this->fk_bank <= 0 ? "NULL" : "'".$this->fk_bank."'").","; - $sql.= " '".$this->fk_user_creat."',"; - $sql.= " '".$this->fk_user_modif."'"; + $sql.= " '".$this->db->escape($this->amount)."',"; + $sql.= " '".$this->db->escape($this->label)."',"; + $sql.= " '".$this->db->escape($this->note)."',"; + $sql.= " ".($this->fk_bank <= 0 ? "NULL" : "'".$this->db->escape($this->fk_bank)."'").","; + $sql.= " '".$this->db->escape($this->fk_user_creat)."',"; + $sql.= " '".$this->db->escape($this->fk_user_modif)."'"; $sql.= ")"; @@ -535,11 +535,11 @@ class Tva extends CommonObject $sql.= "'".$this->db->idate($this->datep)."'"; $sql.= ", '".$this->db->idate($this->datev)."'"; $sql.= ", ".$this->amount; - $sql.= ", '".$this->type_payment."'"; - $sql.= ", '".$this->num_payment."'"; + $sql.= ", '".$this->db->escape($this->type_payment)."'"; + $sql.= ", '".$this->db->escape($this->num_payment)."'"; if ($this->note) $sql.=", '".$this->db->escape($this->note)."'"; if ($this->label) $sql.=", '".$this->db->escape($this->label)."'"; - $sql.= ", '".$user->id."'"; + $sql.= ", '".$this->db->escape($user->id)."'"; $sql.= ", NULL"; $sql.= ", ".$conf->entity; $sql.= ")"; diff --git a/htdocs/compta/tva/clients.php b/htdocs/compta/tva/clients.php index 0ede7fa091e..276f801d05b 100644 --- a/htdocs/compta/tva/clients.php +++ b/htdocs/compta/tva/clients.php @@ -160,7 +160,7 @@ if ($modetax==1) { // Calculate on invoice for goods and services . $langs->trans('AddExtraReport') . '' . '
    '; - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); $elementcust=$langs->trans("CustomersInvoices"); @@ -204,7 +204,7 @@ if ($modetax==0) { // Invoice for goods, payment for services . $langs->trans('AddExtraReport') . '' . '
    '; - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); $elementcust=$langs->trans("CustomersInvoices"); @@ -220,7 +220,7 @@ if ($modetax==0) { // Invoice for goods, payment for services $vatsup.=' ('.$langs->trans("ToGetBack").')'; } } -report_header($name,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); $vatcust=$langs->trans("VATReceived"); $vatsup=$langs->trans("VATPaid"); @@ -260,7 +260,7 @@ if (is_array($coll_list)) { $i = 1; foreach ($coll_list as $coll) { if ($min == 0 or ($min > 0 && $coll->amount > $min)) { - + $intra = str_replace($find,$replace,$coll->tva_intra); if(empty($intra)) { if($coll->assuj == '1') { @@ -340,7 +340,7 @@ if (is_array($coll_list)) { $i = 1; foreach ($coll_list as $coll) { if ($min == 0 or ($min > 0 && $coll->amount > $min)) { - + $intra = str_replace($find,$replace,$coll->tva_intra); if (empty($intra)) { if ($coll->assuj == '1') { diff --git a/htdocs/compta/tva/quadri_detail.php b/htdocs/compta/tva/quadri_detail.php index 513eb25ff7e..c622881d273 100644 --- a/htdocs/compta/tva/quadri_detail.php +++ b/htdocs/compta/tva/quadri_detail.php @@ -133,7 +133,7 @@ $fsearch.=' '; // Affiche en-tete du rapport if ($modetax==1) // Calculate on invoice for goods and services { - $nom=$langs->trans("VATReportByQuartersInDueDebtMode"); + $name=$langs->trans("VATReportByQuartersInDueDebtMode"); $calcmode=$langs->trans("CalcModeVATDebt"); $calcmode.='
    ('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); @@ -152,7 +152,7 @@ if ($modetax==1) // Calculate on invoice for goods and services if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.='
    '.$langs->trans("DepositsAreNotIncluded"); else $description.='
    '.$langs->trans("DepositsAreIncluded"); $description.=$fsearch; - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); // Customers invoices @@ -172,7 +172,7 @@ if ($modetax==1) // Calculate on invoice for goods and services } if ($modetax==0) // Invoice for goods, payment for services { - $nom=$langs->trans("VATReportByQuartersInInputOutputMode"); + $name=$langs->trans("VATReportByQuartersInInputOutputMode"); $calcmode=$langs->trans("CalcModeVATEngagement"); $calcmode.='
    ('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); @@ -192,7 +192,7 @@ if ($modetax==0) // Invoice for goods, payment for services //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
    '.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
    '.$langs->trans("WarningDepositsNotIncluded"); $description.=$fsearch; - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); // Customers invoices @@ -210,7 +210,7 @@ if ($modetax==0) // Invoice for goods, payment for services if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')'; } -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); $vatcust=$langs->trans("VATReceived"); $vatsup=$langs->trans("VATPaid"); @@ -396,7 +396,7 @@ else if (! empty($fields['ddate_start'])) $type=1; if (! empty($fields['ddate_end'])) $type=1; - + print ''; // Ref @@ -553,7 +553,7 @@ else if (! empty($fields['ddate_start'])) $type=1; if (! empty($fields['ddate_end'])) $type=1; - + print ''; // Ref diff --git a/htdocs/compta/tva/quarter_report.php b/htdocs/compta/tva/quarter_report.php index a3d902ed3f3..4c054923837 100644 --- a/htdocs/compta/tva/quarter_report.php +++ b/htdocs/compta/tva/quarter_report.php @@ -146,7 +146,7 @@ $fsearch.=' '; // Affiche en-tete du rapport if ($modetax==1) { // Calculate on invoice for goods and services - $nom=$langs->trans("VATReportByQuartersInDueDebtMode"); + $name=$langs->trans("VATReportByQuartersInDueDebtMode"); $calcmode=$langs->trans("CalcModeVATDebt"); $calcmode.='
    ('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); @@ -174,7 +174,7 @@ if ($modetax==1) { // Calculate on invoice for goods and services $description.='
    '.$langs->trans("DepositsAreIncluded"); } $description.=$fsearch; - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); $elementcust=$langs->trans("CustomersInvoices"); @@ -195,7 +195,7 @@ if ($modetax==1) { // Calculate on invoice for goods and services } } if ($modetax==0) { // Invoice for goods, payment for services - $nom=$langs->trans("VATReportByQuartersInInputOutputMode"); + $name=$langs->trans("VATReportByQuartersInInputOutputMode"); $calcmode=$langs->trans("CalcModeVATEngagement"); $calcmode.='
    ('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); @@ -224,7 +224,7 @@ if ($modetax==0) { // Invoice for goods, payment for services //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
    '.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
    '.$langs->trans("WarningDepositsNotIncluded"); $description.=$fsearch; - $builddate=time(); + $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); $elementcust=$langs->trans("CustomersInvoices"); @@ -244,7 +244,7 @@ if ($modetax==0) { // Invoice for goods, payment for services $vatsup.=' ('.$langs->trans("ToGetBack").')'; } } -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); $vatcust=$langs->trans("VATReceived"); $vatsup=$langs->trans("VATPaid"); @@ -373,18 +373,18 @@ if (!is_array($x_coll) || !is_array($x_paye)) { print ''.$langs->trans("AmountHTVATRealReceived").''; print ''.$vatcust.''; print ''; - + $action = "tvadetail"; $parameters["mode"] = $modetax; $parameters["start"] = $date_start; $parameters["end"] = $date_end; $parameters["type"] = 'vat'; - + $object = array(&$x_coll, &$x_paye, &$x_both); // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('externalbalance')); $reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - + foreach (array_keys($x_coll) as $rate) { $subtot_coll_total_ht = 0; $subtot_coll_vat = 0; @@ -408,7 +408,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) { $type=1; } - + print ''; // Ref @@ -576,7 +576,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) { $type=1; } - + print ''; // Ref diff --git a/htdocs/compta/tva/reglement.php b/htdocs/compta/tva/reglement.php index 0d4d827e694..c22fb4ed30a 100644 --- a/htdocs/compta/tva/reglement.php +++ b/htdocs/compta/tva/reglement.php @@ -100,7 +100,7 @@ $bankstatic = new Account($db); $sql = "SELECT t.rowid, t.amount, t.label, t.datev as dv, t.datep as dp, t.fk_typepayment as type, t.num_payment, t.fk_bank, pst.code as payment_code,"; $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON t.fk_typepayment = pst.id"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON t.fk_typepayment = pst.id AND pst.entity = " . getEntity('c_paiement'); $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE t.entity = ".$conf->entity; diff --git a/htdocs/contact/agenda.php b/htdocs/contact/agenda.php index cc7f36261cc..c885f0869de 100644 --- a/htdocs/contact/agenda.php +++ b/htdocs/contact/agenda.php @@ -115,7 +115,7 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { // Cancel - if (GETPOST("cancel") && ! empty($backtopage)) + if (GETPOST('cancel','alpha') && ! empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -210,7 +210,7 @@ else dol_fiche_head($head, 'agenda', $title, -1, 'contact'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
    '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) @@ -257,30 +257,33 @@ else } - print '
    '; + //print '
    '; + //print '
    '; + + $morehtmlcenter=''; if (! empty($conf->agenda->enabled)) { if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) { - print ''.$langs->trans("AddAction").''; + $morehtmlcenter.= ''.$langs->trans("AddAction").''; } else { - print ''.$langs->trans("AddAction").''; + $morehtmlcenter.= ''.$langs->trans("AddAction").''; } } - print '
    '; if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) )) { + print '
    '; + $param='&id='.$id; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - - print load_fiche_titre($langs->trans("TasksHistoryForThisContact"),'',''); + print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $morehtmlcenter, 0, -1, '', '', '', '', 0, 1, 1); // List of all actions $filters=array(); diff --git a/htdocs/contact/canvas/actions_contactcard_common.class.php b/htdocs/contact/canvas/actions_contactcard_common.class.php index 3d6b792d99b..b5df91ce210 100644 --- a/htdocs/contact/canvas/actions_contactcard_common.class.php +++ b/htdocs/contact/canvas/actions_contactcard_common.class.php @@ -79,18 +79,18 @@ abstract class ActionsContactCardCommon */ function getObject($id) { - $ret = $this->getInstanceDao(); + /*$ret = $this->getInstanceDao(); if (is_object($this->object) && method_exists($this->object,'fetch')) { if (! empty($id)) $this->object->fetch($id); } else - { + {*/ $object = new Contact($this->db); if (! empty($id)) $object->fetch($id); $this->object = $object; - } + //} } /** diff --git a/htdocs/contact/canvas/default/actions_contactcard_default.class.php b/htdocs/contact/canvas/default/actions_contactcard_default.class.php index 30a52469da2..bfcb5a21142 100644 --- a/htdocs/contact/canvas/default/actions_contactcard_default.class.php +++ b/htdocs/contact/canvas/default/actions_contactcard_default.class.php @@ -75,6 +75,7 @@ class ActionsContactCardDefault extends ActionsContactCardCommon */ function assign_values(&$action, $id) { + global $limit, $offset, $sortfield, $sortorder; global $conf, $db, $langs, $user; global $form; @@ -113,14 +114,14 @@ class ActionsContactCardDefault extends ActionsContactCardCommon if ($action == 'list') { - $this->LoadListDatas($GLOBALS['limit'], $GLOBALS['offset'], $GLOBALS['sortfield'], $GLOBALS['sortorder']); + $this->LoadListDatas($limit, $offset, $sortfield, $sortorder); } } /** - * Fetch datas list + * Fetch datas list and save into ->list_datas * * @param int $limit Limit number of responses * @param int $offset Offset for first response diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index d5854297f43..dc6d19614f9 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -91,7 +91,7 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { // Cancel - if (GETPOST("cancel") && ! empty($backtopage)) + if (GETPOST('cancel','alpha') && ! empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -224,7 +224,7 @@ if (empty($reshook)) $action = 'create'; } else { // Categories association - $contcats = GETPOST( 'contcats', 'array' ); + $contcats = GETPOST( 'contcats', 'array'); $object->setCategories($contcats); } } @@ -383,7 +383,7 @@ if (empty($reshook)) $db->query( $sql ); // Then we add the associated categories - $categories = GETPOST( 'contcats', 'array' ); + $categories = GETPOST( 'contcats', 'array'); $object->setCategories($categories); $object->old_lastname=''; @@ -396,6 +396,15 @@ if (empty($reshook)) $action = 'edit'; } } + + if (! $error && empty($errors)) + { + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + } } } @@ -541,7 +550,7 @@ else { print ''; print ''; - print $objsoc->getNomUrl(1); + print $objsoc->getNomUrl(1, 'contact'); print ''; print ''; print ''; @@ -1055,7 +1064,7 @@ else } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
    '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) @@ -1063,7 +1072,7 @@ else $objsoc->fetch($object->socid); // Thirdparty $morehtmlref.=$langs->trans('ThirdParty') . ' : '; - if ($objsoc->id > 0) $morehtmlref.=$objsoc->getNomUrl(1); + if ($objsoc->id > 0) $morehtmlref.=$objsoc->getNomUrl(1, 'contact'); else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany"); } $morehtmlref.='
    '; diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 3b7ce848731..494533fce75 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -39,7 +39,8 @@ class Contact extends CommonObject { public $element='contact'; public $table_element='socpeople'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $picto = 'contact'; public $civility_id; // In fact we store civility_code public $civility_code; @@ -200,7 +201,7 @@ class Contact extends CommonObject $sql.= " ".(! empty($this->canvas)?"'".$this->db->escape($this->canvas)."'":"null").","; $sql.= " ".$conf->entity.","; $sql.= "'".$this->db->escape($this->ref_ext)."',"; - $sql.= " ".(! empty($this->import_key)?"'".$this->import_key."'":"null"); + $sql.= " ".(! empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null"); $sql.= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); @@ -319,9 +320,9 @@ class Contact extends CommonObject $sql .= ", jabberid = ".(isset($this->jabberid)?"'".$this->db->escape($this->jabberid)."'":"null"); $sql .= ", priv = '".$this->db->escape($this->priv)."'"; $sql .= ", statut = ".$this->statut; - $sql .= ", fk_user_modif=".($user->id > 0 ? "'".$user->id."'":"NULL"); - $sql .= ", default_lang=".($this->default_lang?"'".$this->default_lang."'":"NULL"); - $sql .= ", no_email=".($this->no_email?"'".$this->no_email."'":"0"); + $sql .= ", fk_user_modif=".($user->id > 0 ? "'".$this->db->escape($user->id)."'":"NULL"); + $sql .= ", default_lang=".($this->default_lang?"'".$this->db->escape($this->default_lang)."'":"NULL"); + $sql .= ", no_email=".($this->no_email?"'".$this->db->escape($this->no_email)."'":"0"); $sql .= " WHERE rowid=".$this->db->escape($id); dol_syslog(get_class($this)."::update", LOG_DEBUG); @@ -492,7 +493,7 @@ class Contact extends CommonObject // Mis a jour contact $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET"; $sql.= " birthday=".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null"); - $sql.= ", photo = ".($this->photo? "'".$this->photo."'" : "null"); + $sql.= ", photo = ".($this->photo? "'".$this->db->escape($this->photo)."'" : "null"); if ($user) $sql .= ", fk_user_modif=".$user->id; $sql.= " WHERE rowid=".$this->db->escape($id); @@ -987,38 +988,52 @@ class Contact extends CommonObject * Return name of contact with link (and eventually picto) * Use $this->id, $this->lastname, $this->firstname, this->civility_id * - * @param int $withpicto Include picto with link - * @param string $option Where the link point to - * @param int $maxlen Max length of - * @param string $moreparam Add more param into URL - * @return string String with URL + * @param int $withpicto Include picto with link + * @param string $option Where the link point to + * @param int $maxlen Max length of + * @param string $moreparam Add more param into URL + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - function getNomUrl($withpicto=0,$option='',$maxlen=0,$moreparam='') + function getNomUrl($withpicto=0, $option='', $maxlen=0, $moreparam='', $save_lastsearch_value=-1) { global $conf, $langs, $hookmanager; $result=''; - $label = '' . $langs->trans("ShowContact") . ''; - $label.= '
    ' . $langs->trans("Name") . ': '.$this->getFullName($langs); - //if ($this->civility_id) $label.= '
    ' . $langs->trans("Civility") . ': '.$this->civility_id; // TODO Translate cibilty_id code - if (! empty($this->poste)) $label.= '
    ' . $langs->trans("Poste") . ': '.$this->poste; - $label.= '
    ' . $langs->trans("EMail") . ': '.$this->email; - $phonelist=array(); - if ($this->phone_pro) $phonelist[]=$this->phone_pro; - if ($this->phone_mobile) $phonelist[]=$this->phone_mobile; - if ($this->phone_perso) $phonelist[]=$this->phone_perso; - $label.= '
    ' . $langs->trans("Phone") . ': '.join(', ',$phonelist); - $label.= '
    ' . $langs->trans("Address") . ': '.dol_format_address($this, 1, ' ', $langs); - $link = 'global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label=$langs->trans("ShowContact"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.= ' class="classfortooltip">'; + $label = '' . $langs->trans("ShowContact") . ''; + $label.= '
    ' . $langs->trans("Name") . ': '.$this->getFullName($langs); + //if ($this->civility_id) $label.= '
    ' . $langs->trans("Civility") . ': '.$this->civility_id; // TODO Translate cibilty_id code + if (! empty($this->poste)) $label.= '
    ' . $langs->trans("Poste") . ': '.$this->poste; + $label.= '
    ' . $langs->trans("EMail") . ': '.$this->email; + $phonelist=array(); + if ($this->phone_pro) $phonelist[]=$this->phone_pro; + if ($this->phone_mobile) $phonelist[]=$this->phone_mobile; + if ($this->phone_perso) $phonelist[]=$this->phone_perso; + $label.= '
    ' . $langs->trans("Phone") . ': '.join(', ',$phonelist); + $label.= '
    ' . $langs->trans("Address") . ': '.dol_format_address($this, 1, ' ', $langs); + + $url = DOL_URL_ROOT.'/contact/card.php?id='.$this->id; + + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + + $url .= $moreparam; + + $linkstart = '
    global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowContact"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.= ' class="classfortooltip">'; if (! is_object($hookmanager)) { @@ -1030,18 +1045,21 @@ class Contact extends CommonObject $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if ($reshook > 0) $linkclose = $hookmanager->resPrint; - $link.=$linkclose; - + $linkstart.=$linkclose; $linkend=''; if ($option == 'xxx') { - $link = ''; + $linkstart = ''; $linkend=''; } - if ($withpicto) $result.=($link.img_object($label, 'contact', 'class="classfortooltip"').$linkend.' '); - $result.=$link.($maxlen?dol_trunc($this->getFullName($langs),$maxlen):$this->getFullName($langs)).$linkend; + + $result.=$linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.=($maxlen?dol_trunc($this->getFullName($langs),$maxlen):$this->getFullName($langs)); + $result.=$linkend; + return $result; } diff --git a/htdocs/contact/document.php b/htdocs/contact/document.php index da8ef616a4f..a016fa87b31 100644 --- a/htdocs/contact/document.php +++ b/htdocs/contact/document.php @@ -107,8 +107,8 @@ if ($object->id) $totalsize+=$file['size']; } - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
    '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { @@ -120,11 +120,11 @@ if ($object->id) else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany"); } $morehtmlref.='
    '; - + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); - + print '
    '; - + print '
    '; print ''; @@ -147,7 +147,7 @@ if ($object->id) print ''; } }*/ - + // Civility print '
    '.$langs->trans("UserTitle").''; print $object->getCivilityLabel(); @@ -160,7 +160,7 @@ if ($object->id) print ''; dol_fiche_end(); - + $modulepart = 'contact'; $permission = $user->rights->societe->contact->creer; $permtoedit = $user->rights->societe->contact->creer; diff --git a/htdocs/contact/info.php b/htdocs/contact/info.php index 20d379b50d0..287c27d8b10 100644 --- a/htdocs/contact/info.php +++ b/htdocs/contact/info.php @@ -61,7 +61,7 @@ if ($id > 0) dol_fiche_head($head, 'info', $title, -1, 'contact'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', ''); @@ -71,11 +71,11 @@ if ($id > 0) print '
    '; print '
    '; - + dol_print_object_info($object); print ''; - + dol_fiche_end(); } diff --git a/htdocs/contact/ldap.php b/htdocs/contact/ldap.php index 16c00bf92cb..02a25d8005c 100644 --- a/htdocs/contact/ldap.php +++ b/htdocs/contact/ldap.php @@ -1,6 +1,6 @@ - * Copyright (C) 2006-2012 Regis Houssin + * Copyright (C) 2006-2017 Regis Houssin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -90,8 +90,10 @@ $head = contact_prepare_head($object); dol_fiche_head($head, 'ldap', $title, -1, 'contact'); +$linkback = ''.$langs->trans("BackToList").''; + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', ''); - + print '
    '; print '
    '; @@ -196,15 +198,11 @@ if ($result > 0) } else { - dol_print_error('',$ldap->error); + setEventMessages($ldap->error, $ldap->errors, 'errors'); } print '
    '; - - - llxFooter(); - $db->close(); diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 7508381e6cd..a97e6687126 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -51,6 +51,7 @@ $sall=GETPOST('sall', 'alphanohtml'); $search_cti=preg_replace('/^0+/', '', preg_replace('/[^0-9]/', '', GETPOST('search_cti', 'alphanohtml'))); // Phone number without any special chars $search_phone=GETPOST("search_phone"); +$search_id=trim(GETPOST("search_id","int")); $search_firstlast_only=GETPOST("search_firstlast_only"); $search_lastname=GETPOST("search_lastname"); $search_firstname=GETPOST("search_firstname"); @@ -68,6 +69,7 @@ $search_categ_thirdparty=GETPOST("search_categ_thirdparty",'int'); $search_categ_supplier=GETPOST("search_categ_supplier",'int'); $search_status=GETPOST("search_status",'int'); $search_type=GETPOST('search_type','alpha'); +$search_import_key = GETPOST("search_import_key","alpha"); if ($search_status=='') $search_status=1; // always display activ customer first $optioncss = GETPOST('optioncss','alpha'); @@ -93,25 +95,25 @@ $contextpage='contactlist'; $titre = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); if ($type == "p") { - $contextpage='contactprospectlist'; + $contextpage='contactprospectlist'; $titre.=' ('.$langs->trans("ThirdPartyProspects").')'; $urlfiche="card.php"; } if ($type == "c") { - $contextpage='contactcustomerlist'; + $contextpage='contactcustomerlist'; $titre.=' ('.$langs->trans("ThirdPartyCustomers").')'; $urlfiche="card.php"; } else if ($type == "f") { - $contextpage='contactsupplierlist'; + $contextpage='contactsupplierlist'; $titre.=' ('.$langs->trans("ThirdPartySuppliers").')'; $urlfiche="card.php"; } else if ($type == "o") { - $contextpage='contactotherlist'; + $contextpage='contactotherlist'; $titre.=' ('.$langs->trans("OthersNotLinkedToThirdParty").')'; $urlfiche=""; } @@ -126,45 +128,47 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'p.lastname'=>'Lastname', - 'p.firstname'=>'Firstname', - 'p.email'=>'EMail', - 's.nom'=>"ThirdParty", + 'p.lastname'=>'Lastname', + 'p.firstname'=>'Firstname', + 'p.email'=>'EMail', + 's.nom'=>"ThirdParty", ); // Definition of fields for list $arrayfields=array( - 'p.lastname'=>array('label'=>$langs->trans("Lastname"), 'checked'=>1), - 'p.firstname'=>array('label'=>$langs->trans("Firstname"), 'checked'=>1), - 'p.poste'=>array('label'=>$langs->trans("PostOrFunction"), 'checked'=>1), - 'p.town'=>array('label'=>$langs->trans("Town"), 'checked'=>0), - 'p.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), - 'p.phone'=>array('label'=>$langs->trans("Phone"), 'checked'=>1), - 'p.phone_perso'=>array('label'=>$langs->trans("PhonePerso"), 'checked'=>0), - 'p.phone_mobile'=>array('label'=>$langs->trans("PhoneMobile"), 'checked'=>1), - 'p.fax'=>array('label'=>$langs->trans("Fax"), 'checked'=>1), - 'p.email'=>array('label'=>$langs->trans("EMail"), 'checked'=>1), - 'p.skype'=>array('label'=>$langs->trans("Skype"), 'checked'=>1, 'enabled'=>(! empty($conf->skype->enabled))), - 'p.thirdparty'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'enabled'=>empty($conf->global->SOCIETE_DISABLE_CONTACTS)), - 'p.priv'=>array('label'=>$langs->trans("ContactVisibility"), 'checked'=>1, 'position'=>200), - 'p.datec'=>array('label'=>$langs->trans("DateCreationShort"), 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'p.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'p.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0)), + 'p.lastname'=>array('label'=>"Lastname", 'checked'=>1), + 'p.firstname'=>array('label'=>"Firstname", 'checked'=>1), + 'p.poste'=>array('label'=>"PostOrFunction", 'checked'=>1), + 'p.town'=>array('label'=>"Town", 'checked'=>0), + 'p.zip'=>array('label'=>"Zip", 'checked'=>0), + 'p.phone'=>array('label'=>"Phone", 'checked'=>1), + 'p.phone_perso'=>array('label'=>"PhonePerso", 'checked'=>0), + 'p.phone_mobile'=>array('label'=>"PhoneMobile", 'checked'=>1), + 'p.fax'=>array('label'=>"Fax", 'checked'=>1), + 'p.email'=>array('label'=>"EMail", 'checked'=>1), + 'p.skype'=>array('label'=>"Skype", 'checked'=>1, 'enabled'=>(! empty($conf->skype->enabled))), + 'p.thirdparty'=>array('label'=>"ThirdParty", 'checked'=>1, 'enabled'=>empty($conf->global->SOCIETE_DISABLE_CONTACTS)), + 'p.priv'=>array('label'=>"ContactVisibility", 'checked'=>1, 'position'=>200), + 'p.datec'=>array('label'=>"DateCreationShort", 'checked'=>0, 'position'=>500), + 'p.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), + 'p.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), + 'p.import_key'=>array('label'=>"ImportId", 'checked'=>0, 'position'=>1100), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } $object=new Contact($db); if (($id > 0 || ! empty($ref)) && $action != 'add') { - $result=$object->fetch($id,$ref); - if ($result < 0) dol_print_error($db); + $result=$object->fetch($id,$ref); + if ($result < 0) dol_print_error($db); } @@ -172,8 +176,8 @@ if (($id > 0 || ! empty($ref)) && $action != 'add') * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters, $object, $action); // Note that $action and $object may have been modified by some hooks @@ -181,41 +185,43 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // 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=""; - $search_firstlast_only=""; - $search_lastname=""; - $search_firstname=""; - $search_societe=""; - $search_poste=""; - $search_phone=""; - $search_phone_perso=""; - $search_phone_pro=""; - $search_phone_mobile=""; - $search_fax=""; - $search_email=""; - $search_skype=""; - $search_priv=""; - $search_status=-1; - $search_categ=''; - $search_categ_thirdparty=''; - $search_categ_supplier=''; - $toselect=''; - $search_array_options=array(); - } + // 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=""; + $search_id=''; + $search_firstlast_only=""; + $search_lastname=""; + $search_firstname=""; + $search_societe=""; + $search_poste=""; + $search_phone=""; + $search_phone_perso=""; + $search_phone_pro=""; + $search_phone_mobile=""; + $search_fax=""; + $search_email=""; + $search_skype=""; + $search_priv=""; + $search_status=-1; + $search_categ=''; + $search_categ_thirdparty=''; + $search_categ_supplier=''; + $search_import_key=''; + $toselect=''; + $search_array_options=array(); + } - // Mass actions - $objectclass='Contact'; - $objectlabel='Contact'; - $permtoread = $user->rights->societe->lire; - $permtodelete = $user->rights->societe->supprimer; - $uploaddir = $conf->societe->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Mass actions + $objectclass='Contact'; + $objectlabel='Contact'; + $permtoread = $user->rights->societe->lire; + $permtodelete = $user->rights->societe->supprimer; + $uploaddir = $conf->societe->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } if ($search_priv < 0) $search_priv=''; @@ -256,7 +262,7 @@ if (!$user->rights->societe->client->voir && !$socid) //restriction } if (! empty($userid)) // propre au commercial { - $sql .= " AND p.fk_user_creat=".$db->escape($userid); + $sql .= " AND p.fk_user_creat=".$db->escape($userid); } // Filter to exclude not owned private contacts @@ -282,6 +288,7 @@ if (strlen($search_phone)) $sql.= natural_search(array('p.phone', 'p.ph if (strlen($search_cti)) $sql.= natural_search(array('p.phone', 'p.phone_perso', 'p.phone_mobile'), $search_cti); if (strlen($search_firstlast_only)) $sql.= natural_search(array('p.lastname', 'p.firstname'), $search_firstlast_only); +if ($search_id > 0) $sql.= natural_search("p.rowid",$search_id,1); if ($search_lastname) $sql.= natural_search('p.lastname', $search_lastname); if ($search_firstname) $sql.= natural_search('p.firstname', $search_firstname); if ($search_societe) $sql.= natural_search('s.nom', $search_societe); @@ -293,39 +300,40 @@ if (strlen($search_fax)) $sql.= natural_search('p.phone_fax', $search if (strlen($search_skype)) $sql.= natural_search('p.skype', $search_skype); if (strlen($search_email)) $sql.= natural_search('p.email', $search_email); if ($search_status != '' && $search_status >= 0) $sql.= " AND p.statut = ".$db->escape($search_status); +if ($search_import_key) $sql.= natural_search("p.import_key",$search_import_key); if ($type == "o") // filtre sur type { - $sql .= " AND p.fk_soc IS NULL"; + $sql .= " AND p.fk_soc IS NULL"; } else if ($type == "f") // filtre sur type { - $sql .= " AND s.fournisseur = 1"; + $sql .= " AND s.fournisseur = 1"; } else if ($type == "c") // filtre sur type { - $sql .= " AND s.client IN (1, 3)"; + $sql .= " AND s.client IN (1, 3)"; } else if ($type == "p") // filtre sur type { - $sql .= " AND s.client IN (2, 3)"; + $sql .= " AND s.client IN (2, 3)"; } if (! empty($socid)) { - $sql .= " AND s.rowid = ".$socid; + $sql .= " AND s.rowid = ".$socid; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -334,19 +342,19 @@ $sql.=$hookmanager->resPrint; // Add order if ($view == "recent") { - $sql.= $db->order("p.datec","DESC"); + $sql.= $db->order("p.datec","DESC"); } else { - $sql.= $db->order($sortfield,$sortorder); + $sql.= $db->order($sortfield,$sortorder); } // Count total nb of records $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1, $offset); @@ -354,8 +362,8 @@ $sql.= $db->plimit($limit+1, $offset); $result = $db->query($sql); if (! $result) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($result); @@ -364,10 +372,10 @@ $arrayofselected=is_array($toselect)?$toselect:array(); if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && ($sall != '' || $seearch_cti != '')) { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); + exit; } $help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'; @@ -382,6 +390,7 @@ if (!empty($search_categ)) $param.='&search_categ='.urlencode($search_categ); if (!empty($search_categ_thirdparty)) $param.='&search_categ_thirdparty='.urlencode($search_categ_thirdparty); if (!empty($search_categ_supplier)) $param.='&search_categ_supplier='.urlencode($search_categ_supplier); if ($sall != '') $param.='&sall='.urlencode($sall); +if ($search_id > 0) $param.= "&search_id=".urlencode($search_id); if ($search_lastname != '') $param.='&search_lastname='.urlencode($search_lastname); if ($search_firstname != '') $param.='&search_firstname='.urlencode($search_firstname); if ($search_societe != '') $param.='&search_societe='.urlencode($search_societe); @@ -395,13 +404,14 @@ if ($search_fax != '') $param.='&search_fax='.urlencode($search_fax); if ($search_email != '') $param.='&search_email='.urlencode($search_email); if ($search_status != '') $param.='&search_status='.urlencode($search_status); if ($search_priv == '0' || $search_priv == '1') $param.="&search_priv=".urlencode($search_priv); +if ($search_import_key != '') $param.='&search_import_key='.urlencode($search_import_key); if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available @@ -427,37 +437,37 @@ print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } if ($search_firstlast_only) { - print $langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname"); + 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'; - $moreforfilter.='
    '; + $moreforfilter.='
    '; $moreforfilter.=$langs->trans('Categories'). ': '; $moreforfilter.=$formother->select_categories(Categorie::TYPE_CONTACT,$search_categ,'search_categ',1); $moreforfilter.='
    '; if (empty($type) || $type == 'c' || $type == 'p') { - $moreforfilter.='
    '; - if ($type == 'c') $moreforfilter.=$langs->trans('CustomersCategoriesShort'). ': '; - else if ($type == 'p') $moreforfilter.=$langs->trans('ProspectsCategoriesShort'). ': '; - else $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_CUSTOMER,$search_categ_thirdparty,'search_categ_thirdparty',1); - $moreforfilter.='
    '; + $moreforfilter.='
    '; + if ($type == 'c') $moreforfilter.=$langs->trans('CustomersCategoriesShort'). ': '; + else if ($type == 'p') $moreforfilter.=$langs->trans('ProspectsCategoriesShort'). ': '; + else $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort'). ': '; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_CUSTOMER,$search_categ_thirdparty,'search_categ_thirdparty',1); + $moreforfilter.='
    '; } if (empty($type) || $type == 'f') { - $moreforfilter.='
    '; + $moreforfilter.='
    '; $moreforfilter.=$langs->trans('SuppliersCategoriesShort'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_SUPPLIER,$search_categ_supplier,'search_categ_supplier',1); - $moreforfilter.='
    '; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_SUPPLIER,$search_categ_supplier,'search_categ_supplier',1); + $moreforfilter.='
    '; } } if ($moreforfilter) @@ -466,7 +476,7 @@ if ($moreforfilter) print $moreforfilter; $parameters=array('type'=>$type); $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; print '
    '; } @@ -479,81 +489,87 @@ print ''; +if (! empty($arrayfields['p.rowid']['checked'])) +{ + print ''; +} if (! empty($arrayfields['p.lastname']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.firstname']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.poste']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.zip']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.town']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.phone']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.phone_perso']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.phone_mobile']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.fax']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.email']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.skype']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.thirdparty']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.priv']['checked'])) { - print ''; @@ -565,12 +581,12 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { if (! empty($arrayfields["ef.".$key]['checked'])) { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; + print ''; } // Date modification if (! empty($arrayfields['p.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['p.statut']['checked'])) { - print ''; + print ''; +} +if (! empty($arrayfields['p.import_key']['checked'])) +{ + print ''; } // Action column print ''; // Ligne des titres print ''; -if (! empty($arrayfields['p.lastname']['checked'])) print_liste_field_titre("Lastname",$_SERVER["PHP_SELF"],"p.lastname", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.firstname']['checked'])) print_liste_field_titre("Firstname",$_SERVER["PHP_SELF"],"p.firstname", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.zip']['checked'])) print_liste_field_titre("Zip",$_SERVER["PHP_SELF"],"p.zip", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.town']['checked'])) print_liste_field_titre("Town",$_SERVER["PHP_SELF"],"p.town", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.poste']['checked'])) print_liste_field_titre("PostOrFunction",$_SERVER["PHP_SELF"],"p.poste", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.phone']['checked'])) print_liste_field_titre("Phone",$_SERVER["PHP_SELF"],"p.phone", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.phone_perso']['checked'])) print_liste_field_titre("PhonePerso",$_SERVER["PHP_SELF"],"p.phone_perso", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.phone_mobile']['checked'])) print_liste_field_titre("PhoneMobile",$_SERVER["PHP_SELF"],"p.phone_mobile", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.fax']['checked'])) print_liste_field_titre("Fax",$_SERVER["PHP_SELF"],"p.fax", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.email']['checked'])) print_liste_field_titre("EMail",$_SERVER["PHP_SELF"],"p.email", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.skype']['checked'])) print_liste_field_titre("Skype",$_SERVER["PHP_SELF"],"p.skype", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.thirdparty']['checked'])) print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"s.nom", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.priv']['checked'])) print_liste_field_titre("ContactVisibility",$_SERVER["PHP_SELF"],"p.priv", $begin, $param, 'align="center"', $sortfield,$sortorder); +if (! empty($arrayfields['p.rowid']['checked'])) print_liste_field_titre($arrayfields['p.rowid']['label'], $_SERVER["PHP_SELF"],"p.rowid","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['p.lastname']['checked'])) print_liste_field_titre($arrayfields['p.lastname']['label'],$_SERVER["PHP_SELF"],"p.lastname", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.firstname']['checked'])) print_liste_field_titre($arrayfields['p.firstname']['label'],$_SERVER["PHP_SELF"],"p.firstname", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.zip']['checked'])) print_liste_field_titre($arrayfields['p.zip']['label'],$_SERVER["PHP_SELF"],"p.zip", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.town']['checked'])) print_liste_field_titre($arrayfields['p.town']['label'],$_SERVER["PHP_SELF"],"p.town", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.poste']['checked'])) print_liste_field_titre($arrayfields['p.poste']['label'],$_SERVER["PHP_SELF"],"p.poste", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.phone']['checked'])) print_liste_field_titre($arrayfields['p.phone']['label'],$_SERVER["PHP_SELF"],"p.phone", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.phone_perso']['checked'])) print_liste_field_titre($arrayfields['p.phone_perso']['label'],$_SERVER["PHP_SELF"],"p.phone_perso", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.phone_mobile']['checked'])) print_liste_field_titre($arrayfields['p.phone_mobile']['label'],$_SERVER["PHP_SELF"],"p.phone_mobile", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.fax']['checked'])) print_liste_field_titre($arrayfields['p.fax']['label'],$_SERVER["PHP_SELF"],"p.fax", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.email']['checked'])) print_liste_field_titre($arrayfields['p.email']['label'],$_SERVER["PHP_SELF"],"p.email", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.skype']['checked'])) print_liste_field_titre($arrayfields['p.skype']['label'],$_SERVER["PHP_SELF"],"p.skype", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.thirdparty']['checked'])) print_liste_field_titre($arrayfields['p.thirdparty']['label'],$_SERVER["PHP_SELF"],"s.nom", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.priv']['checked'])) print_liste_field_titre($arrayfields['p.priv']['label'],$_SERVER["PHP_SELF"],"p.priv", $begin, $param, 'align="center"', $sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre("DateCreationShort",$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); -if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre("DateModificationShort",$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); -if (! empty($arrayfields['p.statut']['checked'])) print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"p.statut","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['p.statut']['checked'])) print_liste_field_titre($arrayfields['p.statut']['label'],$_SERVER["PHP_SELF"],"p.statut","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['p.import_key']['checked'])) print_liste_field_titre($arrayfields['p.import_key']['label'],$_SERVER["PHP_SELF"],"p.import_key","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; @@ -656,9 +680,9 @@ $i = 0; $totalarray=array(); while ($i < min($num,$limit)) { - $obj = $db->fetch_object($result); + $obj = $db->fetch_object($result); - print ''; + print ''; $contactstatic->lastname=$obj->lastname; $contactstatic->firstname=''; @@ -672,96 +696,104 @@ while ($i < min($num,$limit)) $contactstatic->zip=$obj->zip; $contactstatic->town=$obj->town; - // Name - if (! empty($arrayfields['p.lastname']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // ID + if (! empty($arrayfields['p.rowid']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + // Name + if (! empty($arrayfields['p.lastname']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Firstname - if (! empty($arrayfields['p.firstname']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.firstname']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Zip - if (! empty($arrayfields['p.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.zip']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Town - if (! empty($arrayfields['p.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Function - if (! empty($arrayfields['p.poste']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Phone - if (! empty($arrayfields['p.phone']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Phone perso - if (! empty($arrayfields['p.phone_perso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Phone mobile - if (! empty($arrayfields['p.phone_mobile']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Fax - if (! empty($arrayfields['p.fax']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // EMail - if (! empty($arrayfields['p.email']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Skype - if (! empty($arrayfields['p.skype']['checked'])) - { - if (! empty($conf->skype->enabled)) { print ''; } - if (! $i) $totalarray['nbfield']++; - } - // Company - if (! empty($arrayfields['p.thirdparty']['checked'])) - { + if (! empty($arrayfields['p.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Function + if (! empty($arrayfields['p.poste']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Phone + if (! empty($arrayfields['p.phone']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Phone perso + if (! empty($arrayfields['p.phone_perso']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Phone mobile + if (! empty($arrayfields['p.phone_mobile']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Fax + if (! empty($arrayfields['p.fax']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // EMail + if (! empty($arrayfields['p.email']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Skype + if (! empty($arrayfields['p.skype']['checked'])) + { + if (! empty($conf->skype->enabled)) { print ''; } + if (! $i) $totalarray['nbfield']++; + } + // Company + if (! empty($arrayfields['p.thirdparty']['checked'])) + { print ''; - if (! $i) $totalarray['nbfield']++; - } + } + else + print ' '; + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Private/Public - if (! empty($arrayfields['p.priv']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Private/Public + if (! empty($arrayfields['p.priv']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -777,50 +809,57 @@ while ($i < min($num,$limit)) $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['p.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['p.statut']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['p.statut']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['p.import_key']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + } + print ''; + if (! $i) $totalarray['nbfield']++; - print "\n"; - $i++; + print "\n"; + $i++; } $db->free($result); diff --git a/htdocs/contact/note.php b/htdocs/contact/note.php index b52f9bf8727..1fa766e0913 100644 --- a/htdocs/contact/note.php +++ b/htdocs/contact/note.php @@ -74,8 +74,8 @@ if ($id > 0) $head = contact_prepare_head($object); dol_fiche_head($head, 'note', $title, -1, 'contact'); - - $linkback = ''.$langs->trans("BackToList").''; + + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
    '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) @@ -88,13 +88,13 @@ if ($id > 0) else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany"); } $morehtmlref.='
    '; - + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); - + $cssclass='titlefield'; //if ($action == 'editnote_public') $cssclass='titlefieldcreate'; //if ($action == 'editnote_private') $cssclass='titlefieldcreate'; - + print '
    '; print '
    '; @@ -107,12 +107,12 @@ if ($id > 0) print "
    '; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; + print ''; $selectarray=array('0'=>$langs->trans("ContactPublic"),'1'=>$langs->trans("ContactPrivate")); print $form->selectarray('search_priv',$selectarray,$search_priv,1); print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { - $crit=$val; + $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); $searchclass=''; if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; @@ -588,21 +604,27 @@ print $hookmanager->resPrint; // Date creation if (! empty($arrayfields['p.datec']['checked'])) { - print ''; - print ''; + print ''; - print ''; + print ''; - print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); - print ''; + print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); + print ''; + print ''; + print ''; @@ -614,40 +636,42 @@ print '
    '; - print $contactstatic->getNomUrl(1,'',0); - print ''; + print $obj->rowid; + print "'; + print $contactstatic->getNomUrl(1,'',0); + print ''.$obj->firstname.''.$obj->firstname.''.$obj->zip.''.$obj->zip.''.$obj->town.''.dol_trunc($obj->poste,20).''.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->rowid,$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->rowid,$obj->socid,'AC_TEL').''.dol_print_email($obj->email,$obj->rowid,$obj->socid,'AC_EMAIL',18).''.dol_print_skype($obj->skype,$obj->rowid,$obj->socid,'AC_SKYPE',18).''.$obj->town.''.dol_trunc($obj->poste,20).''.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->rowid,$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->rowid,$obj->socid,'AC_TEL').''.dol_print_email($obj->email,$obj->rowid,$obj->socid,'AC_EMAIL',18).''.dol_print_skype($obj->skype,$obj->rowid,$obj->socid,'AC_SKYPE',18).''; - if ($obj->socid) - { + if ($obj->socid) + { $objsoc = new Societe($db); $objsoc->fetch($obj->socid); print $objsoc->getNomUrl(1); - } - else - print ' '; - print ''.$contactstatic->LibPubPriv($obj->priv).''.$contactstatic->LibPubPriv($obj->priv).''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$contactstatic->getLibStatut(3).''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$contactstatic->getLibStatut(3).''; + print $obj->import_key; + 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; + // Action column + 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 '
    "; - + $cssclass="titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print '
    '; - + dol_fiche_end(); } diff --git a/htdocs/contact/perso.php b/htdocs/contact/perso.php index 30fa10b5ddc..9e85ef98294 100644 --- a/htdocs/contact/perso.php +++ b/htdocs/contact/perso.php @@ -60,7 +60,7 @@ if ($action == 'update' && ! $_POST["cancel"] && $user->rights->societe->contact $object->old_firstname=''; // Logo/Photo save $dir= $conf->societe->dir_output.'/contact/' . get_exdir($object->id,0,0,1,$object,'contact').'/photos'; - + $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); if ($file_OK) { @@ -88,7 +88,7 @@ if ($action == 'update' && ! $_POST["cancel"] && $user->rights->societe->contact else { // Create thumbs - $object->addThumbs($newfile); + $object->addThumbs($newfile); } } } @@ -147,26 +147,26 @@ if ($action == 'edit') print ''; dol_fiche_head($head, 'perso', $title, 0, 'contact'); - + print ''; // Ref print ''; - + // Photo print ''; // Name @@ -216,7 +216,7 @@ if ($action == 'edit') print "
    '.$langs->trans("Ref").''; print $object->id; print ''; print $form->showphoto('contact',$object)."\n"; if ($object->photo) print "
    \n"; - + print ''; - + if ($object->photo) print ''; print ''; print ''; print '
    '.$langs->trans("Delete").'

    '.$langs->trans("PhotoFile").'
    '; - + print '
    "; dol_fiche_end(); - + print '
    '; print ''; print '     '; @@ -228,11 +228,11 @@ if ($action == 'edit') else { // View mode - + dol_fiche_head($head, 'perso', $title, -1, 'contact'); - - $linkback = ''.$langs->trans("BackToList").''; - + + $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
    '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { @@ -244,13 +244,13 @@ else else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany"); } $morehtmlref.='
    '; - - + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); - - + + print '
    '; - + print '
    '; print ''; diff --git a/htdocs/contrat/admin/contract_extrafields.php b/htdocs/contrat/admin/contract_extrafields.php index 509c5307ef8..abfc2b2b65d 100644 --- a/htdocs/contrat/admin/contract_extrafields.php +++ b/htdocs/contrat/admin/contract_extrafields.php @@ -41,7 +41,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/contrat/admin/contractdet_extrafields.php b/htdocs/contrat/admin/contractdet_extrafields.php index 39c691e7ddc..e2eb2bacc6c 100644 --- a/htdocs/contrat/admin/contractdet_extrafields.php +++ b/htdocs/contrat/admin/contractdet_extrafields.php @@ -41,7 +41,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 39a708bcdad..b761eb1864b 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -109,16 +109,16 @@ if (empty($reshook)) if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer) { - $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment')); + $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment')); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else { - setEventMessages($object->error, $object->errors, 'errors'); - } + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else { + setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer) @@ -130,47 +130,47 @@ if (empty($reshook)) } if (! $error) { - $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment'))); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment'))); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } } // Si ajout champ produit predefini if (GETPOST('mode')=='predefined') { - $date_start=''; - $date_end=''; - if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) - { - $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - } - if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) - { - $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - } + $date_start=''; + $date_end=''; + if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) + { + $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + } + if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) + { + $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + } } // Si ajout champ produit libre if (GETPOST('mode')=='libre') { - $date_start_sl=''; - $date_end_sl=''; - if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear')) - { - $date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear')); - } - if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear')) - { - $date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear')); - } + $date_start_sl=''; + $date_end_sl=''; + if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear')) + { + $date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear')); + } + if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear')) + { + $date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear')); + } } // Param dates @@ -181,23 +181,23 @@ if (empty($reshook)) $date_end_real_update=''; if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear')) { - $date_start_update=dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear')); + $date_start_update=dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear')); } if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear')) { - $date_end_update=dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear')); + $date_end_update=dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear')); } if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear')) { - $date_start_real_update=dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear')); + $date_start_real_update=dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear')); } if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear')) { - $date_end_real_update=dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear')); + $date_end_real_update=dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear')); } if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear')) { - $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); } // Add contract @@ -228,74 +228,74 @@ if (empty($reshook)) if (! $error) { $object->socid = $socid; - $object->date_contrat = $datecontrat; + $object->date_contrat = $datecontrat; - $object->commercial_suivi_id = GETPOST('commercial_suivi_id','int'); - $object->commercial_signature_id = GETPOST('commercial_signature_id','int'); + $object->commercial_suivi_id = GETPOST('commercial_suivi_id','int'); + $object->commercial_signature_id = GETPOST('commercial_signature_id','int'); - $object->note_private = GETPOST('note_private','alpha'); - $object->note_public = GETPOST('note_public','alpha'); - $object->fk_project = GETPOST('projectid','int'); - $object->remise_percent = GETPOST('remise_percent','alpha'); - $object->ref = GETPOST('ref','alpha'); - $object->ref_customer = GETPOST('ref_customer','alpha'); - $object->ref_supplier = GETPOST('ref_supplier','alpha'); + $object->note_private = GETPOST('note_private','alpha'); + $object->note_public = GETPOST('note_public','alpha'); + $object->fk_project = GETPOST('projectid','int'); + $object->remise_percent = GETPOST('remise_percent','alpha'); + $object->ref = GETPOST('ref','alpha'); + $object->ref_customer = GETPOST('ref_customer','alpha'); + $object->ref_supplier = GETPOST('ref_supplier','alpha'); - // If creation from another object of another module (Example: origin=propal, originid=1) - if (! empty($origin) && ! empty($originid)) - { - // Parse element/subelement (ex: project_task) - $element = $subelement = $origin; - if (preg_match('/^([^_]+)_([^_]+)/i',$origin,$regs)) - { - $element = $regs[1]; - $subelement = $regs[2]; - } + // If creation from another object of another module (Example: origin=propal, originid=1) + if (! empty($origin) && ! empty($originid)) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = $origin; + if (preg_match('/^([^_]+)_([^_]+)/i',$origin,$regs)) + { + $element = $regs[1]; + $subelement = $regs[2]; + } - // For compatibility - if ($element == 'order') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + // For compatibility + if ($element == 'order') { $element = $subelement = 'commande'; } + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } - $object->origin = $origin; - $object->origin_id = $originid; + $object->origin = $origin; + $object->origin_id = $originid; - // Possibility to add external linked objects with hooks - $object->linked_objects[$object->origin] = $object->origin_id; - if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects'])) - { - $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); - } + // Possibility to add external linked objects with hooks + $object->linked_objects[$object->origin] = $object->origin_id; + if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects'])) + { + $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); + } - $id = $object->create($user); - if ($id < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $id = $object->create($user); + if ($id < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } - if ($id > 0) - { - dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); + if ($id > 0) + { + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); - $classname = ucfirst($subelement); - $srcobject = new $classname($db); + $classname = ucfirst($subelement); + $srcobject = new $classname($db); - dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); - $result=$srcobject->fetch($object->origin_id); - if ($result > 0) - { - $srcobject->fetch_thirdparty(); + dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); + $result=$srcobject->fetch($object->origin_id); + if ($result > 0) + { + $srcobject->fetch_thirdparty(); $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject,'fetch_lines')) - { - $srcobject->fetch_lines(); - $lines = $srcobject->lines; - } + if (empty($lines) && method_exists($srcobject,'fetch_lines')) + { + $srcobject->fetch_lines(); + $lines = $srcobject->lines; + } - $fk_parent_line=0; - $num=count($lines); + $fk_parent_line=0; + $num=count($lines); - for ($i=0;$i<$num;$i++) - { - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + for ($i=0;$i<$num;$i++) + { + $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); if ($product_type == 1 || (! empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0,1)))) { // TODO Exclude also deee // service prédéfini @@ -329,8 +329,8 @@ if (empty($reshook)) $desc = ($lines[$i]->desc && $lines[$i]->desc!=$lines[$i]->libelle)?dol_htmlentitiesbr($lines[$i]->desc):''; } else { - $desc = dol_htmlentitiesbr($lines[$i]->desc); - } + $desc = dol_htmlentitiesbr($lines[$i]->desc); + } // Extrafields $array_options = array(); @@ -347,72 +347,72 @@ if (empty($reshook)) $localtax1_tx = get_localtax($txtva, 1, $object->thirdparty); $localtax2_tx = get_localtax($txtva, 2, $object->thirdparty); - $result = $object->addline( - $desc, - $lines[$i]->subprice, - $lines[$i]->qty, - $txtva, - $localtax1_tx, - $localtax2_tx, - $lines[$i]->fk_product, - $lines[$i]->remise_percent, - $lines[$i]->date_start, - $lines[$i]->date_end, - 'HT', - 0, - $lines[$i]->info_bits, - $lines[$i]->fk_fournprice, - $lines[$i]->pa_ht, - $array_options, - $lines[$i]->fk_unit - ); + $result = $object->addline( + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $txtva, + $localtax1_tx, + $localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $lines[$i]->date_start, + $lines[$i]->date_end, + 'HT', + 0, + $lines[$i]->info_bits, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $array_options, + $lines[$i]->fk_unit + ); - if ($result < 0) - { - $error++; - break; - } + if ($result < 0) + { + $error++; + break; + } } - } - } - else - { - setEventMessages($srcobject->error, $srcobject->errors, 'errors'); - $error++; - } + } + } + else + { + setEventMessages($srcobject->error, $srcobject->errors, 'errors'); + $error++; + } - // Hooks - $parameters = array('objFrom' => $srcobject); - $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook - if ($reshook < 0) - $error++; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } - else - { - $result = $object->create($user); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else { - setEventMessages($object->error, $object->errors, 'errors'); - } - $action='create'; + // Hooks + $parameters = array('objFrom' => $srcobject); + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been + // modified by hook + if ($reshook < 0) + $error++; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } - } + else + { + $result = $object->create($user); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else { + setEventMessages($object->error, $object->errors, 'errors'); + } + $action='create'; + } + } } else if ($action == 'classin' && $user->rights->contrat->creer) { - $object->setProject(GETPOST('projectid')); + $object->setProject(GETPOST('projectid')); } // Add a new line @@ -437,64 +437,72 @@ if (empty($reshook)) $qty = GETPOST('qty'.$predef); $remise_percent = GETPOST('remise_percent'.$predef); - if ($qty == '') - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); - $error++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); - $error++; - } + if ($qty == '') + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); + $error++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); + $error++; + } - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - // Unset extrafield - if (is_array($extralabelsline)) { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); - } - } + $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); + $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); + if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) + { + setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); + $error++; + } - if (! $error) - { + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } + + if (! $error) + { // Clean parameters $date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); $price_base_type = (GETPOST('price_base_type', 'alpha')?GETPOST('price_base_type', 'alpha'):'HT'); - // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $tva_tx par celui du produit - // Ecrase $base_price_type par celui du produit - if ($idprod > 0) - { - $prod = new Product($db); - $prod->fetch($idprod); + // Ecrase $pu par celui du produit + // Ecrase $desc par celui du produit + // Ecrase $tva_tx par celui du produit + // Ecrase $base_price_type par celui du produit + if ($idprod > 0) + { + $prod = new Product($db); + $prod->fetch($idprod); - // Update if prices fields are defined - $tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id); - $tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id); - if (empty($tva_tx)) $tva_npr=0; + // Update if prices fields are defined + $tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id); + $tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id); + if (empty($tva_tx)) $tva_npr=0; - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; + $pu_ht = $prod->price; + $pu_ttc = $prod->price_ttc; + $price_min = $prod->price_min; + $price_base_type = $prod->price_base_type; - // On defini prix unitaire - if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) - { - $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; - $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; - $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; - $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) + // On defini prix unitaire + if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) + { + $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; + $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; + $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; + $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; + } + elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; @@ -517,35 +525,35 @@ if (empty($reshook)) $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); // On reevalue prix selon taux tva car taux tva transaction peut etre different - // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - if ($tmpvat != $tmpprodvat) - { - if ($price_base_type != 'HT') - { - $pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU'); - } - else - { - $pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU'); - } - } + // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). + if ($tmpvat != $tmpprodvat) + { + if ($price_base_type != 'HT') + { + $pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU'); + } + else + { + $pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU'); + } + } - $desc=$prod->description; - $desc=dol_concatdesc($desc,$product_desc); - $fk_unit = $prod->fk_unit; - } - else + $desc=$prod->description; + $desc=dol_concatdesc($desc,$product_desc); + $fk_unit = $prod->fk_unit; + } + else { - $pu_ht=GETPOST('price_ht'); - $price_base_type = 'HT'; - $tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0; // tva_tx field may be disabled, so we use vat rate 0 - $tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0; - $desc=$product_desc; + $pu_ht=GETPOST('price_ht'); + $price_base_type = 'HT'; + $tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0; // tva_tx field may be disabled, so we use vat rate 0 + $tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0; + $desc=$product_desc; $fk_unit= GETPOST('units', 'alpha'); - } + } - $localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty,$mysoc,$tva_npr); - $localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty,$mysoc,$tva_npr); + $localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty,$mysoc,$tva_npr); + $localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty,$mysoc,$tva_npr); // ajout prix achat $fk_fournprice = $_POST['fournprice']; @@ -554,41 +562,41 @@ if (empty($reshook)) else $pa_ht = null; - $info_bits=0; - if ($tva_npr) $info_bits |= 0x01; + $info_bits=0; + if ($tva_npr) $info_bits |= 0x01; - if($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))) - { - $object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency)); - $result = -1 ; - } - else + if($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))) { - // Insert line - $result = $object->addline( - $desc, - $pu_ht, - $qty, - $tva_tx, - $localtax1_tx, - $localtax2_tx, - $idprod, - $remise_percent, - $date_start, - $date_end, - $price_base_type, - $pu_ttc, - $info_bits, - $fk_fournprice, - $pa_ht, - $array_options, - $fk_unit - ); - } + $object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency)); + $result = -1 ; + } + else + { + // Insert line + $result = $object->addline( + $desc, + $pu_ht, + $qty, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $idprod, + $remise_percent, + $date_start, + $date_end, + $price_base_type, + $pu_ttc, + $info_bits, + $fk_fournprice, + $pa_ht, + $array_options, + $fk_unit + ); + } - if ($result > 0) - { - // Define output language + if ($result > 0) + { + // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && ! empty($conf->global->CONTRACT_ADDON_PDF)) // No generation if default type not defined { $outputlangs = $langs; @@ -624,143 +632,159 @@ if (empty($reshook)) unset($_POST['dp_desc']); unset($_POST['idprod']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } - else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel')) + else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel','alpha')) { - $objectline = new ContratLigne($db); - if ($objectline->fetch(GETPOST('elrowid'))) - { - $db->begin(); + if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) + { + setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); + $action = 'editline'; + $_GET['rowid'] = GETPOST('elrowid'); + $error++; + } - if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; - if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; + if (!$error) { + $objectline = new ContratLigne($db); + if ($objectline->fetch(GETPOST('elrowid'))) + { + $db->begin(); - $vat_rate = GETPOST('eltva_tx'); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) - $info_bits |= 0x01; + if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; + if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; - // Define vat_rate - $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc); - $localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc); + $vat_rate = GETPOST('eltva_tx'); + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $vat_rate)) + $info_bits |= 0x01; - $txtva = $vat_rate; + // Define vat_rate + $vat_rate = str_replace('*', '', $vat_rate); + $localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc); + $localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc); - // Clean vat code - $vat_src_code=''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + $txtva = $vat_rate; - // ajout prix d'achat - $fk_fournprice = $_POST['fournprice']; - if ( ! empty($_POST['buying_price']) ) - $pa_ht = $_POST['buying_price']; - else - $pa_ht = null; + // Clean vat code + $vat_src_code=''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } - $fk_unit = GETPOST('unit', 'alpha'); + // ajout prix d'achat + $fk_fournprice = $_POST['fournprice']; + if ( ! empty($_POST['buying_price']) ) + $pa_ht = $_POST['buying_price']; + else + $pa_ht = null; - $objectline->description=GETPOST('product_desc'); - $objectline->price_ht=GETPOST('elprice'); - $objectline->subprice=GETPOST('elprice'); - $objectline->qty=GETPOST('elqty'); - $objectline->remise_percent=GETPOST('elremise_percent'); - $objectline->tva_tx=($txtva?$txtva:0); // Field may be disabled, so we use vat rate 0 - $objectline->vat_src_code=$vat_src_code; - $objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0; - $objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0; - $objectline->date_ouverture_prevue=$date_start_update; - $objectline->date_ouverture=$date_start_real_update; - $objectline->date_fin_validite=$date_end_update; - $objectline->date_cloture=$date_end_real_update; - $objectline->fk_user_cloture=$user->id; - $objectline->fk_fournprice=$fk_fournprice; - $objectline->pa_ht=$pa_ht; + $fk_unit = GETPOST('unit', 'alpha'); - if ($fk_unit > 0) { - $objectline->fk_unit = GETPOST('unit'); - } else { - $objectline->fk_unit = null; - } + $objectline->description=GETPOST('product_desc','none'); + $objectline->price_ht=GETPOST('elprice'); + $objectline->subprice=GETPOST('elprice'); + $objectline->qty=GETPOST('elqty'); + $objectline->remise_percent=GETPOST('elremise_percent'); + $objectline->tva_tx=($txtva?$txtva:0); // Field may be disabled, so we use vat rate 0 + $objectline->vat_src_code=$vat_src_code; + $objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0; + $objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0; + $objectline->date_ouverture_prevue=$date_start_update; + $objectline->date_ouverture=$date_start_real_update; + $objectline->date_fin_validite=$date_end_update; + $objectline->date_cloture=$date_end_real_update; + $objectline->fk_user_cloture=$user->id; + $objectline->fk_fournprice=$fk_fournprice; + $objectline->pa_ht=$pa_ht; - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - $objectline->array_options=$array_options; + if ($fk_unit > 0) { + $objectline->fk_unit = GETPOST('unit'); + } else { + $objectline->fk_unit = null; + } - // TODO verifier price_min si fk_product et multiprix + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + $objectline->array_options=$array_options; - $result=$objectline->update($user); - if ($result > 0) - { - $db->commit(); - } - else - { - setEventMessages($objectline->error, $objectline->errors, 'errors'); - $db->rollback(); - } - } - else - { - setEventMessages($objectline->error, $objectline->errors, 'errors'); - } + // TODO verifier price_min si fk_product et multiprix + + $result=$objectline->update($user); + if ($result > 0) + { + $db->commit(); + } + else + { + setEventMessages($objectline->error, $objectline->errors, 'errors'); + $db->rollback(); + } + } + else + { + setEventMessages($objectline->error, $objectline->errors, 'errors'); + } + } } else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) { - $result = $object->deleteline(GETPOST('lineid'),$user); + $result = $object->deleteline(GETPOST('lineid'),$user); - if ($result >= 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + if ($result >= 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) { - $result = $object->validate($user); + $result = $object->validate($user); } else if ($action == 'reopen' && $user->rights->contrat->creer) { - $result = $object->reopen($user); + $result = $object->reopen($user); } // Close all lines else if ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->cloture($user); + $object->closeAll($user); + } + + // Close all lines + else if ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) + { + $object->activateAll($user); } else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) @@ -805,26 +829,24 @@ if (empty($reshook)) // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); - if ($ret < 0) - $error ++; + if ($ret < 0) $error++; if (! $error) { - - $result = $object->insertExtraFields(); - if ($result < 0) { - $error ++; - } - } else if ($reshook < 0) - $error ++; + $result = $object->insertExtraFields(); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } if ($error) { $action = 'edit_extras'; - setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action=='setref_supplier') { - $cancelbutton = GETPOST('cancel'); + $cancelbutton = GETPOST('cancel','alpha'); if (!$cancelbutton) { $result = $object->fetch($id); @@ -832,7 +854,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); + $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'editref_supplier'; @@ -841,14 +863,14 @@ if (empty($reshook)) exit; } } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } elseif ($action=='setref_customer') { - $cancelbutton = GETPOST('cancel'); + $cancelbutton = GETPOST('cancel','alpha'); if (!$cancelbutton) { @@ -857,8 +879,8 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); - if ($result < 0) { + $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'editref_customer'; } else { @@ -866,107 +888,74 @@ if (empty($reshook)) exit; } } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } elseif ($action=='setref') { - $cancelbutton = GETPOST('cancel'); + $cancelbutton = GETPOST('cancel','alpha'); - if (!$cancelbutton) { - $result = $object->fetch($id); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + if (!$cancelbutton) { + $result = $object->fetch($id); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } - $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'editref'; - } else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); - exit; - } - } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'editref'; + } else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + exit; + } + } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } elseif ($action=='setdate_contrat') { - $cancelbutton = GETPOST('cancel'); + $cancelbutton = GETPOST('cancel','alpha'); - if (!$cancelbutton) { - $result = $object->fetch($id); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + if (!$cancelbutton) { + $result = $object->fetch($id); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } $datacontrat=dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear')); - $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY'); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'editdate_contrat'; - } else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); - exit; - } - } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } - } - - // Generation doc (depuis lien ou depuis cartouche doc) - else if ($action == 'builddoc' && $user->rights->contrat->creer) { - if (GETPOST('model')) { - $object->setDocModel($user, GETPOST('model')); + $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'editdate_contrat'; + } else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + exit; + } } - - // Define output language - $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { - $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id','aZ09') ? GETPOST('lang_id','aZ09') : $object->thirdparty->default_lang); - $outputlangs->setDefaultLang($newlang); - } - $ret = $object->fetch($id); // Reload to get new records - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $action=''; + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; } } - // Remove file in doc form - else if ($action == 'remove_file' && $user->rights->contrat->creer) { - if ($object->id > 0) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $langs->load("other"); - $upload_dir = $conf->contrat->dir_output; - $file = $upload_dir . '/' . GETPOST('file'); - $ret = dol_delete_file($file, 0, 0, 0, $object); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); - } - } - - /* - * Send mail - */ + // Actions to build doc + $upload_dir = $conf->contrat->dir_output; + $permissioncreate = $user->rights->contrat->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; // Actions to send emails $trigger_name='CONTRACT_SENTBYMAIL'; $paramname='id'; $mode='emailfromcontract'; - $trackid='cont'.$object->id; + $trackid='con'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer) { if ($action == 'addcontact') @@ -1068,74 +1057,74 @@ if ($action == 'create') { print load_fiche_titre($langs->trans('AddContract'),'','title_commercial.png'); - $soc = new Societe($db); - if ($socid>0) $soc->fetch($socid); + $soc = new Societe($db); + if ($socid>0) $soc->fetch($socid); - if (GETPOST('origin') && GETPOST('originid')) - { - // Parse element/subelement (ex: project_task) - $element = $subelement = GETPOST('origin'); - if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs)) - { - $element = $regs[1]; - $subelement = $regs[2]; - } + if (GETPOST('origin') && GETPOST('originid')) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = GETPOST('origin'); + if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs)) + { + $element = $regs[1]; + $subelement = $regs[2]; + } - if ($element == 'project') - { - $projectid=GETPOST('originid'); - } - else - { - // For compatibility - if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + if ($element == 'project') + { + $projectid=GETPOST('originid'); + } + else + { + // For compatibility + if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } - dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); - $classname = ucfirst($subelement); - $objectsrc = new $classname($db); - $objectsrc->fetch(GETPOST('originid')); - if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines')) $objectsrc->fetch_lines(); - $objectsrc->fetch_thirdparty(); + $classname = ucfirst($subelement); + $objectsrc = new $classname($db); + $objectsrc->fetch(GETPOST('originid')); + if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines')) $objectsrc->fetch_lines(); + $objectsrc->fetch_thirdparty(); - $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); + $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); - $soc = $objectsrc->thirdparty; + $soc = $objectsrc->thirdparty; - $note_private = (! empty($objectsrc->note_private) ? $objectsrc->note_private : ''); - $note_public = (! empty($objectsrc->note_public) ? $objectsrc->note_public : ''); + $note_private = (! empty($objectsrc->note_private) ? $objectsrc->note_private : ''); + $note_public = (! empty($objectsrc->note_public) ? $objectsrc->note_public : ''); - // Object source contacts list - $srccontactslist = $objectsrc->liste_contact(-1,'external',1); - } - } - else { + // Object source contacts list + $srccontactslist = $objectsrc->liste_contact(-1,'external',1); + } + } + else { $projectid = GETPOST('projectid','int'); $note_private = GETPOST("note_private"); $note_public = GETPOST("note_public"); } - $object->date_contrat = dol_now(); + $object->date_contrat = dol_now(); - print ''; - print ''; + print ''; + print ''; - print ''; - print ''."\n"; - print ''; + print ''; + print ''."\n"; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print '
    '; + print '
    '; - // Ref + // Ref print ''; @@ -1147,7 +1136,7 @@ if ($action == 'create') print ''; print ''; - // Thirdparty + // Thirdparty print ''; print ''; if ($socid>0) @@ -1161,6 +1150,7 @@ if ($action == 'create') { print ''; } print ''."\n"; @@ -1179,75 +1169,75 @@ if ($action == 'create') print ''; } - // Commercial suivi - print ''; + // Commercial suivi + print ''; - // Commercial signature - print ''; + // Commercial signature + print ''; - print '"; + print '"; - // Project - if (! empty($conf->projet->enabled)) - { - $formproject=new FormProjets($db); + // Project + if (! empty($conf->projet->enabled)) + { + $formproject=new FormProjets($db); - print '"; - } - - print ''; - - if (empty($user->societe_id)) - { - print ''; - } - - // Other attributes - $parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"', 'cols'=>3); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - - // Other attributes - if (empty($reshook) && ! empty($extrafields->attribute_label)) { - print $object->showOptionals($extrafields, 'edit'); - } - - print "
    '.$langs->trans('Ref').''; - if (! empty($modCodeContract->code_auto)) { - $tmpcode=$langs->trans("Draft"); - } else { - $tmpcode=''; - } + if (! empty($modCodeContract->code_auto)) { + $tmpcode=$langs->trans("Draft"); + } else { + $tmpcode=''; + } print $tmpcode; print '
    '.$langs->trans('RefSupplier').'
    '.$langs->trans('ThirdParty').''; print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300'); + print ' '.$langs->trans("AddThirdParty").''; print '
    '.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").''; - print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,''); - print '
    '.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").''; + print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,''); + print '
    '.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").''; - print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,''); - print '
    '.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").''; + print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,''); + print '
    '.$langs->trans("Date").''; - $form->select_date($datecontrat,'',0,0,'',"contrat"); - print "
    '.$langs->trans("Date").''; + $form->select_date($datecontrat,'',0,0,'',"contrat"); + print "
    '.$langs->trans("Project").''; - $formproject->select_projects(($soc->id>0?$soc->id:-1),$projectid,"projectid",0,0,1,1); - print "
    '.$langs->trans("NotePublic").''; - $doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
    '.$langs->trans("NotePrivate").''; - $doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
    \n"; - - dol_fiche_end(); - - print '
    '; - print ''; - print '     '; - print ''; - print '
    '; - - if (is_object($objectsrc)) - { - print ''; - print ''; - - if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) - { - print '
    '.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed"); - } + print ''.$langs->trans("Project").''; + $formproject->select_projects(($soc->id>0?$soc->id:-1),$projectid,"projectid",0,0,1,1); + print ""; } - print "\n"; + print ''.$langs->trans("NotePublic").''; + $doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print ''; + + if (empty($user->societe_id)) + { + print ''.$langs->trans("NotePrivate").''; + $doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print ''; + } + + // Other attributes + $parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"', 'cols'=>3); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + // Other attributes + if (empty($reshook) && ! empty($extrafields->attribute_label)) { + print $object->showOptionals($extrafields, 'edit'); + } + + print "\n"; + + dol_fiche_end(); + + print '
    '; + print ''; + print '     '; + print ''; + print '
    '; + + if (is_object($objectsrc)) + { + print ''; + print ''; + + if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) + { + print '
    '.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed"); + } + } + + print "\n"; } else /* *************************************************************************** */ @@ -1256,100 +1246,105 @@ else /* */ /* *************************************************************************** */ { - $now=dol_now(); + $now=dol_now(); - if ($object->id > 0) - { - $object->fetch_thirdparty(); + if ($object->id > 0) + { + $object->fetch_thirdparty(); - $result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed - if ($result < 0) dol_print_error($db,$object->error); + $result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed + if ($result < 0) dol_print_error($db,$object->error); - $nbofservices=count($object->lines); + $nbofservices=count($object->lines); - $author = new User($db); - $author->fetch($object->user_author_id); + $author = new User($db); + $author->fetch($object->user_author_id); - $commercial_signature = new User($db); - $commercial_signature->fetch($object->commercial_signature_id); + $commercial_signature = new User($db); + $commercial_signature->fetch($object->commercial_signature_id); - $commercial_suivi = new User($db); - $commercial_suivi->fetch($object->commercial_suivi_id); + $commercial_suivi = new User($db); + $commercial_suivi->fetch($object->commercial_suivi_id); - $head = contract_prepare_head($object); + $head = contract_prepare_head($object); - $hselected = 0; + $hselected = 0; - dol_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract'); + dol_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract'); - /* + /* * Confirmation de la suppression du contrat */ - if ($action == 'delete') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("DeleteAContract"),$langs->trans("ConfirmDeleteAContract"),"confirm_delete",'',0,1); + if ($action == 'delete') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("DeleteAContract"),$langs->trans("ConfirmDeleteAContract"),"confirm_delete",'',0,1); - } + } - /* + /* * Confirmation de la validation */ - if ($action == 'valid') - { - $ref = substr($object->ref, 1, 4); - if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) - { - $numref = $object->getNextNumRef($object->thirdparty); - } - else - { - $numref = $object->ref; - } + if ($action == 'valid') + { + $ref = substr($object->ref, 1, 4); + if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) + { + $numref = $object->getNextNumRef($object->thirdparty); + } + else + { + $numref = $object->ref; + } - $text=$langs->trans('ConfirmValidateContract',$numref); + $text=$langs->trans('ConfirmValidateContract',$numref); - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ValidateAContract"),$text,"confirm_valid",'',0,1); + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ValidateAContract"),$text,"confirm_valid",'',0,1); - } + } - /* + /* * Confirmation de la fermeture */ - if ($action == 'close') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("CloseAContract"),$langs->trans("ConfirmCloseContract"),"confirm_close",'',0,1); + if ($action == 'close') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("CloseAContract"),$langs->trans("ConfirmCloseContract"),"confirm_close",'',0,1); - } + } + if ($action == 'activate') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ActivateAllOnContract"),$langs->trans("ConfirmActivateAllOnContract"),"confirm_activate",'',0,1); - /* + } + + /* * Contrat */ - if (! empty($object->brouillon) && $user->rights->contrat->creer) - { - print '
    '; - print ''; - print ''; - } + if (! empty($object->brouillon) && $user->rights->contrat->creer) + { + print ''; + print ''; + print ''; + } - // Clone confirmation - if ($action == 'clone') { - $formquestion = array(array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)'))); - print $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloneContract'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); - } + // Clone confirmation + if ($action == 'clone') { + $formquestion = array(array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)'))); + print $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloneContract'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + } // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref=''; - if (! empty($modCodeContract->code_auto)) { - $morehtmlref.=$object->ref; - } else { - $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,3); - $morehtmlref.=$form->editfieldval("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,2); - } + $morehtmlref=''; + if (! empty($modCodeContract->code_auto)) { + $morehtmlref.=$object->ref; + } else { + $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,3); + $morehtmlref.=$form->editfieldval("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,2); + } $morehtmlref.='
    '; // Ref customer @@ -1360,64 +1355,64 @@ else $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->contrat->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - } - $morehtmlref.='
    '; + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->contrat->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
    '; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref); - print '
    '; - print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; - // Ligne info remises tiers - print ''; + // Ligne info remises tiers + print ''; - // Date - print ''; + // Date + print ''; print ''; print ''; - // Other attributes - $cols = 3; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $cols = 3; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print "
    '.$langs->trans('Discount').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); - $absolute_discount=$object->thirdparty->getAvailableDiscounts(); - print '. '; - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; - print '
    '.$langs->trans('Discount').''; + if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); + else print $langs->trans("CompanyHasNoRelativeDiscount"); + $absolute_discount=$object->thirdparty->getAvailableDiscounts(); + print '. '; + if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency)); + else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + print '.'; + print '
    '; print $form->editfieldkey("Date",'date_contrat',$object->date_contrat,$object,$user->rights->contrat->creer); print ''; @@ -1425,577 +1420,577 @@ else print '
    "; + print ""; - print '
    '; + print '
    '; - if (! empty($object->brouillon) && $user->rights->contrat->creer) - { - print ''; - } + if (! empty($object->brouillon) && $user->rights->contrat->creer) + { + print ''; + } - echo '
    '; + echo '
    '; - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { - $blocname = 'contacts'; - $title = $langs->trans('ContactsAddresses'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) + { + $blocname = 'contacts'; + $title = $langs->trans('ContactsAddresses'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $blocname = 'notes'; - $title = $langs->trans('Notes'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $blocname = 'notes'; + $title = $langs->trans('Notes'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - $colorb='666666'; + $colorb='666666'; - $arrayothercontracts=$object->getListOfContracts('others'); + $arrayothercontracts=$object->getListOfContracts('others'); - /* + /* * Lines of contracts */ $productstatic=new Product($db); - $usemargins=0; + $usemargins=0; if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1; - $var=false; + $var=false; // Title line for service - $cursorline=1; - while ($cursorline <= $nbofservices) - { - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; + $cursorline=1; + while ($cursorline <= $nbofservices) + { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - // Area with common detail of line - print ''; + // Area with common detail of line + print '
    '; - $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,"; - $sql.= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,"; - $sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,"; - $sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,"; - $sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,"; - $sql.= " cd.fk_unit,"; - $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; - $sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id; + $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,"; + $sql.= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,"; + $sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,"; + $sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,"; + $sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,"; + $sql.= " cd.fk_unit,"; + $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; + $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; + $sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id; - $result = $db->query($sql); - if ($result) - { - $total = 0; + $result = $db->query($sql); + if ($result) + { + $total = 0; - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->multicurrency->enabled)) { - print ''; - } - print ''; - if ($conf->global->PRODUCT_USE_UNITS) print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + if (!empty($conf->multicurrency->enabled)) { + print ''; + } + print ''; + if ($conf->global->PRODUCT_USE_UNITS) print ''; + print ''; if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; - print ''; - print "\n"; + print ''; + print "\n"; - $objp = $db->fetch_object($result); + $objp = $db->fetch_object($result); - // + // - if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) - { - print ''; - // Label - if ($objp->fk_product > 0) - { - print ''; + // Label + if ($objp->fk_product > 0) + { + print ''; - } - else + print ''; + } + else { - print '\n"; - } - // TVA - print ''; - // Price - print '\n"; - // Price multicurrency - if (!empty($conf->multicurrency->enabled)) { - print ''; - } - // Quantite - print ''; - // Unit - if($conf->global->PRODUCT_USE_UNITS) print ''; - // Remise - if ($objp->remise_percent > 0) - { - print '\n"; - } - else - { - print ''; - } + print '\n"; + } + // TVA + print ''; + // Price + print '\n"; + // Price multicurrency + if (!empty($conf->multicurrency->enabled)) { + print ''; + } + // Quantite + print ''; + // Unit + if($conf->global->PRODUCT_USE_UNITS) print ''; + // Remise + if ($objp->remise_percent > 0) + { + print '\n"; + } + else + { + print ''; + } // Margin if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; - // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme) - print ''; + // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme) + print ''; - print "\n"; + print "\n"; - // Dates of service planed and real - if ($objp->subprice >= 0) - { - $colspan = 6; + // Dates of service planed and real + if ($objp->subprice >= 0) + { + $colspan = 6; - if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) { - $colspan = 8; - } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) { - $colspan = 7; - } + if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) { + $colspan = 8; + } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) { + $colspan = 7; + } - print ''; - print ''; + print ''; - print ''; - } + print ''; + print ''; + } - // Display lines extrafields - if (is_array($extralabelslines) && count($extralabelslines)>0) { - print ''; - $line = new ContratLigne($db); - $line->fetch_optionals($objp->rowid,$extralabelslines); - print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); - print ''; - } - } - // Ligne en mode update - else - { - // Ligne carac - print ""; - print ''; + $line = new ContratLigne($db); + $line->fetch_optionals($objp->rowid,$extralabelslines); + print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); + print ''; + } + } + // Ligne en mode update + else + { + // Ligne carac + print ""; + print ''; - print ''; - print ''; - print ''; - if ($conf->global->PRODUCT_USE_UNITS) - { - print ''; - } - print ''; + print ''; + print ''; + print ''; + print ''; + if ($conf->global->PRODUCT_USE_UNITS) + { + print ''; + } + print ''; if (! empty($usemargins)) { - print ''; } - print ''; + print ''; - $colspan=6; - if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++; - if($conf->global->PRODUCT_USE_UNITS) $colspan++; + $colspan=6; + if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++; + if($conf->global->PRODUCT_USE_UNITS) $colspan++; - // Ligne dates prevues - print ""; - print ''; + // Ligne dates prevues + print ""; + print ''; - if (is_array($extralabelslines) && count($extralabelslines)>0) { - print ''; - $line = new ContratLigne($db); - $line->fetch_optionals($objp->rowid,$extralabelslines); - print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); - print ''; - } + if (is_array($extralabelslines) && count($extralabelslines)>0) { + print ''; + $line = new ContratLigne($db); + $line->fetch_optionals($objp->rowid,$extralabelslines); + print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); + print ''; + } - print ''; - } + print ''; + } - $db->free($result); - } - else + $db->free($result); + } + else { - dol_print_error($db); - } + dol_print_error($db); + } - if ($object->statut > 0) - { - print ''; - print ''; - print "\n"; - } + if ($object->statut > 0) + { + print ''; + print ''; + print "\n"; + } - print "
    '.$langs->trans("ServiceNb",$cursorline).''.$langs->trans("VAT").''.$langs->trans("PriceUHT").''.$langs->trans("PriceUHTCurrency").''.$langs->trans("Qty").''.$langs->trans("Unit").''.$langs->trans("ReductionShort").'
    '.$langs->trans("ServiceNb",$cursorline).''.$langs->trans("VAT").''.$langs->trans("PriceUHT").''.$langs->trans("PriceUHTCurrency").''.$langs->trans("Qty").''.$langs->trans("Unit").''.$langs->trans("ReductionShort").''.$langs->trans("BuyingPrice").' 
     
    '; - $productstatic->id=$objp->fk_product; - $productstatic->type=$objp->ptype; - $productstatic->ref=$objp->pref; + if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) + { + print '
    '; + $productstatic->id=$objp->fk_product; + $productstatic->type=$objp->ptype; + $productstatic->ref=$objp->pref; $productstatic->entity=$objp->pentity; $productstatic->label=$objp->plabel; $text = $productstatic->getNomUrl(1,'',20); - if ($objp->plabel) - { - $text .= ' - '; - //$productstatic->ref=$objp->label; - //$text .= $productstatic->getNomUrl(0,'',16); - $text .= $objp->plabel; - } - $description = $objp->description; + if ($objp->plabel) + { + $text .= ' - '; + //$productstatic->ref=$objp->label; + //$text .= $productstatic->getNomUrl(0,'',16); + $text .= $objp->plabel; + } + $description = $objp->description; - // Add description in form + // Add description in form if (! empty($conf->global->PRODUIT_DESC_IN_FORM)) { $text .= (! empty($objp->description) && $objp->description!=$objp->plabel)?'
    '.dol_htmlentitiesbr($objp->description):''; $description = ''; // Already added into main visible desc } - echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):'')); + echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):'')); - print '
    '.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."'; - print vatrate($objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), '%', $objp->info_bits); - print ''.($objp->subprice != '' ? price($objp->subprice) : '')."'.price($objp->multicurrency_subprice).''.$objp->qty.''.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).''.$objp->remise_percent."% '.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."'; + print vatrate($objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), '%', $objp->info_bits); + print ''.($objp->subprice != '' ? price($objp->subprice) : '')."'.price($objp->multicurrency_subprice).''.$objp->qty.''.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).''.$objp->remise_percent."% '.price($objp->pa_ht).''; - if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) - { - print ''; - print img_picto($langs->trans("MoveToAnotherContract"),'uparrow'); - print ''; - } - if ($user->rights->contrat->creer && ($object->statut >= 0)) - { - print ''; - print img_edit(); - print ''; - } - if ( $user->rights->contrat->creer && ($object->statut >= 0)) - { - print ''; - print img_delete(); - print ''; - } - print ''; + if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) + { + print ''; + print img_picto($langs->trans("MoveToAnotherContract"),'uparrow'); + print ''; + } + if ($user->rights->contrat->creer && ($object->statut >= 0)) + { + print ''; + print img_edit(); + print ''; + } + if ( $user->rights->contrat->creer && ($object->statut >= 0)) + { + print ''; + print img_delete(); + print ''; + } + print '
    '; + print '
    '; - // Date planned - print $langs->trans("DateStartPlanned").': '; - if ($objp->date_debut) - { - print dol_print_date($db->jdate($objp->date_debut)); - // Warning si date prevu passee et pas en service - if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) { - $warning_delay=$conf->contrat->services->inactifs->warning_delay / 3600 / 24; - $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); - print " ".img_warning($textlate); - } - } - else print $langs->trans("Unknown"); - print '  -  '; - print $langs->trans("DateEndPlanned").': '; - if ($objp->date_fin) - { - print dol_print_date($db->jdate($objp->date_fin)); - if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { - $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; - $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); - print " ".img_warning($textlate); - } - } - else print $langs->trans("Unknown"); + // Date planned + print $langs->trans("DateStartPlanned").': '; + if ($objp->date_debut) + { + print dol_print_date($db->jdate($objp->date_debut), 'day'); + // Warning si date prevu passee et pas en service + if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) { + $warning_delay=$conf->contrat->services->inactifs->warning_delay / 3600 / 24; + $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); + print " ".img_warning($textlate); + } + } + else print $langs->trans("Unknown"); + print '  -  '; + print $langs->trans("DateEndPlanned").': '; + if ($objp->date_fin) + { + print dol_print_date($db->jdate($objp->date_fin), 'day'); + if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { + $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; + $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); + print " ".img_warning($textlate); + } + } + else print $langs->trans("Unknown"); - print '
    '; - if ($objp->fk_product) - { - $productstatic->id=$objp->fk_product; - $productstatic->type=$objp->ptype; - $productstatic->ref=$objp->pref; + // Display lines extrafields + if (is_array($extralabelslines) && count($extralabelslines)>0) { + print '
    '; + if ($objp->fk_product) + { + $productstatic->id=$objp->fk_product; + $productstatic->type=$objp->ptype; + $productstatic->ref=$objp->pref; $productstatic->entity=$objp->pentity; - print $productstatic->getNomUrl(1,'',20); - print $objp->label?' - '.dol_trunc($objp->label,16):''; - print '
    '; - } - else - { - print $objp->label?$objp->label.'
    ':''; - } + print $productstatic->getNomUrl(1,'',20); + print $objp->label?' - '.dol_trunc($objp->label,16):''; + print '
    '; + } + else + { + print $objp->label?$objp->label.'
    ':''; + } - // editeur wysiwyg - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $nbrows=ROWS_2; - if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT; - $enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0); - $doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%'); - $doleditor->Create(); + // editeur wysiwyg + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $nbrows=ROWS_2; + if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT; + $enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0); + $doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%'); + $doleditor->Create(); - print '
    '; - print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1); - print ''; - print $form->selectUnits($objp->fk_unit, "unit"); - print '%'; + print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1); + print ''; + print $form->selectUnits($objp->fk_unit, "unit"); + print '%'; - if ($objp->fk_product) print ''; + print ''; + if ($objp->fk_product) print ''; print ''; - print ''; - print '
    '; - print '
    '; + print ''; + print '
    '; + print '
    '; - print $langs->trans("DateStartPlanned").' '; - $form->select_date($db->jdate($objp->date_debut),"date_start_update",$usehm,$usehm,($db->jdate($objp->date_debut)>0?0:1),"update"); - print '   '.$langs->trans("DateEndPlanned").' '; - $form->select_date($db->jdate($objp->date_fin),"date_end_update",$usehm,$usehm,($db->jdate($objp->date_fin)>0?0:1),"update"); - print '
    '; + print $langs->trans("DateStartPlanned").' '; + $form->select_date($db->jdate($objp->date_debut),"date_start_update",$usehm,$usehm,($db->jdate($objp->date_debut)>0?0:1),"update"); + print '   '.$langs->trans("DateEndPlanned").' '; + $form->select_date($db->jdate($objp->date_fin),"date_end_update",$usehm,$usehm,($db->jdate($objp->date_fin)>0?0:1),"update"); + print '


    "; + print ""; - print "
    \n"; + print "\n"; - /* + /* * Confirmation to delete service line of contract */ - if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1); - if ($ret == 'html') print '
    '; - } + if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1); + if ($ret == 'html') print '
    '; + } - /* + /* * Confirmation to move service toward another contract */ - if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) - { - $arraycontractid=array(); - foreach($arrayothercontracts as $contractcursor) - { - $arraycontractid[$contractcursor->id]=$contractcursor->ref; - } - //var_dump($arraycontractid); - // Cree un tableau formulaire - $formquestion=array( + if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) + { + $arraycontractid=array(); + foreach($arrayothercontracts as $contractcursor) + { + $arraycontractid[$contractcursor->id]=$contractcursor->ref; + } + //var_dump($arraycontractid); + // Cree un tableau formulaire + $formquestion=array( 'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"), - array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid)); + array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid)); - $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion); - print '
    '; - } + $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion); + print '
    '; + } - /* + /* * Confirmation de la validation activation */ - if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - $comment = GETPOST('comment','alpha'); - $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1); - print '
    '; - } + if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + $comment = GETPOST('comment','alpha'); + $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1); + print '
    '; + } - /* + /* * Confirmation de la validation fermeture */ - if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - $comment = GETPOST('comment','alpha'); + if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + $comment = GETPOST('comment','alpha'); - if (empty($dateactend)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors'); - } - else - { - $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1); - } - print '
    '; - } + if (empty($dateactend)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors'); + } + else + { + $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1); + } + print '
    '; + } - // Area with status and activation info of line - if ($object->statut > 0) - { - print ''; + // Area with status and activation info of line + if ($object->statut > 0) + { + print '
    '; - print ''; - print ''; - print ''; + print ''; + print ''; - print "\n"; + } + } + print ''; + print "\n"; - print ''; + print ''; - print ''; + print ''; - print ''; + print ''; - print ''; - print '
    '.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).''; - if ($user->societe_id == 0) - { - if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') - { - $tmpaction='activateline'; - $tmpactionpicto='play'; - $tmpactiontext=$langs->trans("Activate"); - if ($objp->statut == 4) - { - $tmpaction='unactivateline'; - $tmpactionpicto='playstop'; - $tmpactiontext=$langs->trans("Unactivate"); - } + print '
    '.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).''; + if ($user->societe_id == 0) + { + if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') + { + $tmpaction='activateline'; + $tmpactionpicto='play'; + $tmpactiontext=$langs->trans("Activate"); + if ($objp->statut == 4) + { + $tmpaction='unactivateline'; + $tmpactionpicto='playstop'; + $tmpactiontext=$langs->trans("Unactivate"); + } if (($tmpaction=='activateline' && $user->rights->contrat->activer) || ($tmpaction=='unactivateline' && $user->rights->contrat->desactiver)) { print ''; print img_picto($tmpactiontext, $tmpactionpicto); print ''; } - } - } - print '
    '; - // Si pas encore active - if (! $objp->date_debut_reelle) { - print $langs->trans("DateStartReal").': '; - if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle); - else print $langs->trans("ContractStatusNotRunning"); - } - // Si active et en cours - if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) { - print $langs->trans("DateStartReal").': '; - print dol_print_date($objp->date_debut_reelle); - } - // Si desactive - if ($objp->date_debut_reelle && $objp->date_fin_reelle) { - print $langs->trans("DateStartReal").': '; - print dol_print_date($objp->date_debut_reelle); - print '  -  '; - print $langs->trans("DateEndReal").': '; - print dol_print_date($objp->date_fin_reelle); - } - if (! empty($objp->comment)) print "
    ".$objp->comment; - print '
    '; + // Si pas encore active + if (! $objp->date_debut_reelle) { + print $langs->trans("DateStartReal").': '; + if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle, 'day'); + else print $langs->trans("ContractStatusNotRunning"); + } + // Si active et en cours + if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) { + print $langs->trans("DateStartReal").': '; + print dol_print_date($objp->date_debut_reelle, 'day'); + } + // Si desactive + if ($objp->date_debut_reelle && $objp->date_fin_reelle) { + print $langs->trans("DateStartReal").': '; + print dol_print_date($objp->date_debut_reelle, 'day'); + print '  -  '; + print $langs->trans("DateEndReal").': '; + print dol_print_date($objp->date_fin_reelle, 'day'); + } + if (! empty($objp->comment)) print "
    ".$objp->comment; + print '
      
    '; - } + print ''; + print ''; + } - // Form to activate line - if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - print '
    '; - print ''; + // Form to activate line + if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + print ''; + print ''; - print ''; + print '
    '; - // Definie date debut et fin par defaut - $dateactstart = $objp->date_debut; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (! $dateactstart) $dateactstart = time(); + // Definie date debut et fin par defaut + $dateactstart = $objp->date_debut; + if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + elseif (! $dateactstart) $dateactstart = time(); - $dateactend = $objp->date_fin; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (! $dateactend) - { - if ($objp->fk_product > 0) - { - $product=new Product($db); - $product->fetch($objp->fk_product); - $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); - } - } + $dateactend = $objp->date_fin; + if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + elseif (! $dateactend) + { + if ($objp->fk_product > 0) + { + $product=new Product($db); + $product->fetch($objp->fk_product); + $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); + } + } - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print '
    '.$langs->trans("DateServiceActivate").''; - print $form->select_date($dateactstart,'',$usehm,$usehm,'',"active",1,0,1); - print ''.$langs->trans("DateEndPlanned").''; - print $form->select_date($dateactend,"end",$usehm,$usehm,'',"active",1,0,1); - print ''; - print '
    '.$langs->trans("DateServiceActivate").''; + print $form->select_date($dateactstart,'',$usehm,$usehm,'',"active",1,0,1); + print ''.$langs->trans("DateEndPlanned").''; + print $form->select_date($dateactend,"end",$usehm,$usehm,'',"active",1,0,1); + print ''; + print '
    '.$langs->trans("Comment").''; - print '   '; - print ''; - print '
    '.$langs->trans("Comment").''; + print '   '; + print ''; + print '
    '; + print ''; - print '
    '; - } + print ''; + } - if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - /** - * Disable a contract line - */ - print ''."\n"; - print '
    '; + if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + /** + * Disable a contract line + */ + print ''."\n"; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; + print '
    '; - // Definie date debut et fin par defaut - $dateactstart = $objp->date_debut_reelle; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (! $dateactstart) $dateactstart = time(); + // Definie date debut et fin par defaut + $dateactstart = $objp->date_debut_reelle; + if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + elseif (! $dateactstart) $dateactstart = time(); - $dateactend = $objp->date_fin_reelle; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (! $dateactend) - { - if ($objp->fk_product > 0) - { - $product=new Product($db); - $product->fetch($objp->fk_product); - $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); - } - } - $now=dol_now(); - if ($dateactend > $now) $dateactend=$now; + $dateactend = $objp->date_fin_reelle; + if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + elseif (! $dateactend) + { + if ($objp->fk_product > 0) + { + $product=new Product($db); + $product->fetch($objp->fk_product); + $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); + } + } + $now=dol_now(); + if ($dateactend > $now) $dateactend=$now; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print '
    '; - if ($objp->statut >= 4) - { - if ($objp->statut == 4) - { - print $langs->trans("DateEndReal").' '; - print $form->select_date($dateactend,"end",$usehm,$usehm,($objp->date_fin_reelle>0?0:1),"closeline",1,1,1); - } - } - print ''; - print '
    '; + if ($objp->statut >= 4) + { + if ($objp->statut == 4) + { + print $langs->trans("DateEndReal").' '; + print $form->select_date($dateactend,"end",$usehm,$usehm,($objp->date_fin_reelle>0?0:1),"closeline",1,1,1); + } + } + print ''; + print '
    '.$langs->trans("Comment").''; - print '   '; - print ''; - print '
    '.$langs->trans("Comment").''; + print '   '; + print ''; + print '
    '; + print ''; - print '
    '; - } + print ''; + } - $cursorline++; - } + $cursorline++; + } // Form to add new line - if ($user->rights->contrat->creer && ($object->statut == 0)) - { - $dateSelector=1; + if ($user->rights->contrat->creer && ($object->statut == 0)) + { + $dateSelector=1; print "\n"; print '
    @@ -2005,15 +2000,15 @@ else '; - print '
    '; + print '
    '; print ''; // Array with (n*2)+1 lines - // Trick to not show product entries - $savproductenabled=$conf->product->enabled; - if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $conf->product->enabled = 0; + // Trick to not show product entries + $savproductenabled=$conf->product->enabled; + if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $conf->product->enabled = 0; - // Form to add new line - if ($action != 'editline') + // Form to add new line + if ($action != 'editline') { $var = true; @@ -2026,245 +2021,147 @@ else $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook } - // Restore correct setup - $conf->product->enabled = $savproductenabled; + // Restore correct setup + $conf->product->enabled = $savproductenabled; - print '
    '; - print '
    '; - print ''; - } + print ''; + print '
    '; + print ''; + } dol_fiche_end(); - /* + /* * Buttons */ - if ($user->societe_id == 0) - { - print '
    '; + if ($user->societe_id == 0) + { + print '
    '; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + $parameters=array(); + $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - if ($object->statut == 0 && $nbofservices) - { - if ($user->rights->contrat->creer) print ''; - else print ''; - } - if ($object->statut == 1) - { - if ($user->rights->contrat->creer) print ''; - else print ''; - } + if (empty($reshook)) + { + // Send + if ($object->statut == 1) { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) { + print ''; + } else + print ''; + } - if (! empty($conf->facture->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) - { - $langs->load("bills"); - if ($user->rights->facture->creer) print ''; - else print ''; - } + if ($object->statut == 0 && $nbofservices) + { + if ($user->rights->contrat->creer) print ''; + else print ''; + } + if ($object->statut == 1) + { + if ($user->rights->contrat->creer) print ''; + else print ''; + } - if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) - { - $langs->load("orders"); - if ($user->rights->commande->creer) print ''; - else print ''; - } + if (! empty($conf->facture->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) + { + $langs->load("bills"); + if ($user->rights->facture->creer) print ''; + else print ''; + } - // Clone - if ($user->rights->contrat->creer) { - print ''; - } + if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) + { + $langs->load("orders"); + if ($user->rights->commande->creer) print ''; + else print ''; + } - if ($object->nbofservicesclosed < $nbofservices) - { - //if (! $numactive) - //{ - print ''; - //} - //else - //{ - // print ''; - //} - } + // Clone + if ($user->rights->contrat->creer) { + print ''; + } - // On peut supprimer entite si - // - Droit de creer + mode brouillon (erreur creation) - // - Droit de supprimer - if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer) - { - print ''; - } - else - { - print ''; - } + if ($object->nbofservicesclosed > 0) + { + print ''; + } + if ($object->nbofservicesclosed < $nbofservices) + { + //if (! $numactive) + //{ + print ''; + //} + //else + //{ + // print ''; + //} + } - print "
    "; - } + // On peut supprimer entite si + // - Droit de creer + mode brouillon (erreur creation) + // - Droit de supprimer + if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer) + { + print ''; + } + else + { + print ''; + } + } - // Select mail models is same action as presend - if (GETPOST('modelselected')) { - $action = 'presend'; - } + print "
    "; + } - if ($action != 'presend') - { - 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->lire; - $delallowed = $user->rights->contrat->creer; + $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->lire; + $delallowed = $user->rights->contrat->creer; - $var = true; + $var = true; - print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); + 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); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
    '; + 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); + $somethingshown = $formactions->showactions($object, 'contract', $socid, 1); - print '
    '; - } - - /* - * Action presend - */ - if ($action == 'presend') - { - $object->fetch_projet(); - - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($conf->contrat->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - - if (!empty($newlang)) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($newlang); - $outputlangs->load('commercial'); - } - - // Build document if it not exists - if (! $file || ! is_readable($file)) { - $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) { - dol_print_error($db, $object->error, $object->errors); - exit(); - } - $fileparams = dol_most_recent_file($conf->contrat->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - } - - print '
    '; - print '
    '; - print '
    '; - print load_fiche_titre($langs->trans('SendContractByMail')); - - dol_fiche_head(''); - - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - $formmail->trackid='ord'.$object->id; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'ord'.$object->id); - } - $formmail->withfrom = 1; - $liste = array(); - foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) - $liste [$key] = $value; - $formmail->withto = GETPOST('sendto') ? GETPOST('sendto') : $liste; - $formmail->withtocc = $liste; - $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; - if (empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->trans('SendContractRef', '__CONTRACTREF__'); - } else if (! empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->trans('SendContractRef', '__CONTRACTREF__ (__REFCLIENT__)'); - } - $formmail->withfile = 2; - $formmail->withbody = 1; - $formmail->withdeliveryreceipt = 1; - $formmail->withcancel = 1; - // Tableau des substitutions - $formmail->setSubstitFromObject($object); - $formmail->substit ['__CONTRACTREF__'] = $object->ref; - - $custcontact = ''; - $contactarr = array(); - $contactarr = $object->liste_contact(- 1, 'external'); - - if (is_array($contactarr) && count($contactarr) > 0) - { - foreach ($contactarr as $contact) - { - if ($contact['libelle'] == $langs->trans('TypeContact_contract_external_CUSTOMER')) { // TODO Use code and not label - $contactstatic = new Contact($db); - $contactstatic->fetch($contact ['id']); - $custcontact = $contactstatic->getFullName($langs, 1); - } - } - - if (! empty($custcontact)) { - $formmail->substit['__CONTACTCIVNAME__'] = $custcontact; - } - } - - // Tableau des parametres complementaires - $formmail->param['action'] = 'send'; - $formmail->param['models'] = 'contract_send'; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['contractid'] = $object->id; - $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; - - // Init list of files - if (GETPOST("mode") == 'init') { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file, basename($file), dol_mimetype($file)); - } - - // Show form - print $formmail->get_form(); - - dol_fiche_end(); + print '
    '; } - } + // Presend form + $modelmail='contract'; + $defaulttopic='SendContractRef'; + $diroutput = $conf->contrat->dir_output; + $trackid = 'con'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; + } } diff --git a/htdocs/contrat/class/api_contracts.class.php b/htdocs/contrat/class/api_contracts.class.php new file mode 100644 index 00000000000..0bc02458869 --- /dev/null +++ b/htdocs/contrat/class/api_contracts.class.php @@ -0,0 +1,587 @@ + + * Copyright (C) 2016 Laurent Destailleur + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + use Luracast\Restler\RestException; + + require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; + +/** + * API class for contracts + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class Contracts extends DolibarrApi +{ + + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid', + 'date_contrat', + 'commercial_signature_id', + 'commercial_suivi_id' + ); + + /** + * @var Contrat $contract {@type Contrat} + */ + public $contract; + + /** + * Constructor + */ + function __construct() + { + global $db, $conf; + $this->db = $db; + $this->contract = new Contrat($this->db); + } + + /** + * Get properties of a contrat object + * + * Return an array with contrat informations + * + * @param int $id ID of contract + * @return array|mixed data without useless information + * + * @throws RestException + */ + function get($id) + { + if(! DolibarrApiAccess::$user->rights->contrat->lire) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $this->contract->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->contract); + } + + + + /** + * List contracts + * + * Get a list of contracts + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $thirdparty_ids Thirdparty ids to filter contracts of. {@example '1' or '1,2,3'} {@pattern /^[0-9,]*$/i} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return array Array of contract objects + * + * @throws RestException + */ + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { + global $db, $conf; + + $obj_ret = array(); + + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $thirdparty_ids; + + // If the internal user must only see his customers, force searching by him + $search_sale = 0; + if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + + $sql = "SELECT t.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + $sql.= " FROM ".MAIN_DB_PREFIX."contrat as t"; + + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + + $sql.= ' WHERE t.entity IN ('.getEntity('contrat').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc"; + if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")"; + if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + // Insert sale filter + if ($search_sale > 0) + { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $db->plimit($limit + 1, $offset); + } + + dol_syslog("API Rest request"); + $result = $db->query($sql); + + if ($result) + { + $num = $db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + $i=0; + while ($i < $min) + { + $obj = $db->fetch_object($result); + $contrat_static = new Contrat($db); + if($contrat_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($contrat_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve contrat list : '.$db->lasterror()); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No contract found'); + } + return $obj_ret; + } + + /** + * Create contract object + * + * @param array $request_data Request data + * @return int ID of contrat + */ + function post($request_data = NULL) + { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach($request_data as $field => $value) { + $this->contract->$field = $value; + } + /*if (isset($request_data["lines"])) { + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->contract->lines = $lines; + }*/ + if ($this->contract->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating contract", array_merge(array($this->contract->error), $this->contract->errors)); + } + + return $this->contract->id; + } + + /** + * Get lines of a contract + * + * @param int $id Id of contract + * + * @url GET {id}/lines + * + * @return int + */ + function getLines($id) { + if(! DolibarrApiAccess::$user->rights->contrat->lire) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->contract->getLinesArray(); + $result = array(); + foreach ($this->contract->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + + /** + * Add a line to given contract + * + * @param int $id Id of contrat to update + * @param array $request_data Contractline data + * + * @url POST {id}/lines + * + * @return int + */ + function postLine($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->contract->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->date_start, // date_start = date planned start, date ouverture = date_start_real + $request_data->date_end, // date_end = date planned end, date_cloture = date_end_real + $request_data->HT, + $request_data->subprice_excl_tax, + $request_data->info_bits, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->array_options, + $request_data->fk_unit, + $request_data->rang + ); + + if ($updateRes > 0) { + return $updateRes; + + } + return false; + } + + /** + * Update a line to given contract + * + * @param int $id Id of contrat to update + * @param int $lineid Id of line to update + * @param array $request_data Contractline data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + */ + function putLine($id, $lineid, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contrat not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + + $updateRes = $this->contract->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->date_ouveture_prevue, + $request_data->date_fin_validite, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->date_ouverture, + $request_data->date_cloture, + 'HT', + $request_data->info_bits, + $request_data->fk_fourn_price, + $request_data->pa_ht, + $request_data->array_options, + $request_data->fk_unit + ); + + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + + return false; + } + + /** + * Delete a line to given contract + * + * + * @param int $id Id of contract to update + * @param int $lineid Id of line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return int + * @throws 401 + * @throws 404 + */ + function deleteLine($id, $lineid) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contrat not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + $updateRes = $this->contract->deleteline($lineid, DolibarrApiAccess::$user); + if ($updateRes > 0) { + return $this->get($id); + } + return false; + } + + /** + * Update contract general fields (won't touch lines of contract) + * + * @param int $id Id of contrat to update + * @param array $request_data Datas + * + * @return int + */ + function put($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contrat not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + foreach($request_data as $field => $value) { + if ($field == 'id') continue; + $this->contract->$field = $value; + } + + if($this->contract->update(DolibarrApiAccess::$user, 0)) + return $this->get($id); + + return false; + } + + /** + * Delete contract + * + * @param int $id Contract ID + * + * @return array + */ + function delete($id) + { + if(! DolibarrApiAccess::$user->rights->contrat->supprimer) { + throw new RestException(401); + } + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if( ! $this->contract->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete contract : '.$this->contract->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contract deleted' + ) + ); + + } + + /** + * Validate an contract + * + * @param int $id Contract ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/validate + * + * @return array + * FIXME An error 403 is returned if the request has an empty body. + * Error message: "Forbidden: Content type `text/plain` is not supported." + * Workaround: send this in the body + * { + * "notrigger": 0 + * } + */ + function validate($id, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->contract->validate(DolibarrApiAccess::$user, '', $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error when validating Contract: '.$this->contract->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contract validated (Ref='.$this->contract->ref.')' + ) + ); + } + + /** + * Close all services of a contract + * + * @param int $id Contract ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/close + * + * @return array + * FIXME An error 403 is returned if the request has an empty body. + * Error message: "Forbidden: Content type `text/plain` is not supported." + * Workaround: send this in the body + * { + * "notrigger": 0 + * } + */ + function close($id, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->contract->closeAll(DolibarrApiAccess::$user, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already close'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Contract: '.$this->contract->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contract closed (Ref='.$this->contract->ref.'). All services were closed.' + ) + ); + } + + + + /** + * 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->address); + + unset($object->date_ouverture_prevue); + unset($object->date_ouverture); + unset($object->date_fin_validite); + unset($object->date_cloture); + unset($object->date_debut_prevue); + unset($object->date_debut_reel); + unset($object->date_fin_prevue); + unset($object->date_fin_reel); + unset($object->civility_id); + + return $object; + } + + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + function _validate($data) + { + $contrat = array(); + foreach (Contracts::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $contrat[$field] = $data[$field]; + + } + return $contrat; + } +} diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 6885e766603..47a40c1b0a3 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -44,7 +44,7 @@ class Contrat extends CommonObject public $table_element='contrat'; public $table_element_line='contratdet'; public $fk_element='fk_contrat'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='contract'; /** @@ -248,12 +248,63 @@ class Contrat extends CommonObject /** - * Close all lines of a contract + * Open all lines of a contract * - * @param User $user Object User making action - * @return void + * @param User $user Object User making action + * @param int|string $date_start Date start (now if empty) + * @return int <0 if KO, >0 if OK */ - function cloture($user) + function activateAll($user, $date_start='') + { + if (empty($date_start)) $date_start = dol_now(); + + $this->db->begin(); + + // Load lines + $this->fetch_lines(); + + $ok=true; + foreach($this->lines as $contratline) + { + // Open lines not already open + if ($contratline->statut != 4) + { + $result = $contratline->active_line($user, $date_start, -1); + if ($result < 0) + { + $ok=false; + break; + } + } + } + + if ($this->statut == 0) + { + $result=$this->validate($user); + if ($result < 0) $ok=false; + } + + if ($ok) + { + $this->db->commit(); + return 1; + } + else + { + dol_print_error($this->db,'Error in activateAll function'); + $this->db->rollback(); + return -1; + } + } + + /** + * Close all lines of a contract + * + * @param User $user Object User making action + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function closeAll(User $user, $notrigger=0) { $this->db->begin(); @@ -263,7 +314,7 @@ class Contrat extends CommonObject $ok=true; foreach($this->lines as $contratline) { - // Close line not already closed + // Close lines not already closed if ($contratline->statut != 5) { $contratline->date_cloture=dol_now(); @@ -280,18 +331,20 @@ class Contrat extends CommonObject if ($this->statut == 0) { - $result=$this->validate($user); + $result=$this->validate($user, '', $notrigger); if ($result < 0) $ok=false; } if ($ok) { $this->db->commit(); + return 1; } else { - dol_print_error($this->db,'Error in cloture function'); + dol_print_error($this->db,'Error in closeAll function'); $this->db->rollback(); + return -1; } } @@ -303,7 +356,7 @@ class Contrat extends CommonObject * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - function validate($user, $force_number='', $notrigger=0) + function validate(User $user, $force_number='', $notrigger=0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; global $langs, $conf; @@ -486,11 +539,13 @@ class Contrat extends CommonObject /** * Load a contract from database * - * @param int $id Id of contract to load - * @param string $ref Ref - * @return int <0 if KO, id of contract if OK + * @param int $id Id of contract to load + * @param string $ref Ref + * @param string $ref_customer Customer ref + * @param string $ref_supplier Supplier ref + * @return int <0 if KO, 0 if not found, Id of contract if OK */ - function fetch($id,$ref='') + function fetch($id, $ref='', $ref_customer='', $ref_supplier='') { $sql = "SELECT rowid, statut, ref, fk_soc, mise_en_service as datemise,"; $sql.= " ref_supplier, ref_customer,"; @@ -501,12 +556,20 @@ class Contrat extends CommonObject $sql.= " fk_commercial_signature, fk_commercial_suivi,"; $sql.= " note_private, note_public, model_pdf, extraparams"; $sql.= " FROM ".MAIN_DB_PREFIX."contrat"; + if (! $id) $sql.=" WHERE entity IN (".getEntity('contract', 0).")"; + else $sql.= " WHERE rowid=".$id; + if ($ref_customer) + { + $sql.= " AND ref_customer = '".$this->db->escape($ref_customer)."'"; + } + if ($ref_supplier) + { + $sql.= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'"; + } if ($ref) { - $sql.= " WHERE ref='".$this->db->escape($ref)."'"; - $sql.= " AND entity IN (".getEntity('contract', 0).")"; + $sql.= " AND ref='".$this->db->escape($ref)."'"; } - else $sql.= " WHERE rowid=".$id; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -576,7 +639,7 @@ class Contrat extends CommonObject { dol_syslog(get_class($this)."::Fetch Erreur contrat non trouve"); $this->error="Contract not found"; - return -2; + return 0; } } else @@ -629,8 +692,8 @@ class Contrat extends CommonObject $sql.= " d.fk_user_ouverture,"; $sql.= " d.fk_user_cloture,"; $sql.= " d.fk_unit"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d, ".MAIN_DB_PREFIX."product as p"; - $sql.= " WHERE d.fk_contrat = ".$this->id ." AND d.fk_product = p.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; + $sql.= " WHERE d.fk_contrat = ".$this->id; $sql.= " ORDER by d.rowid ASC"; dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); @@ -666,7 +729,7 @@ class Contrat extends CommonObject $line->total_localtax1 = $objp->total_localtax1; $line->total_localtax2 = $objp->total_localtax2; $line->total_ttc = $objp->total_ttc; - $line->fk_product = $objp->fk_product; + $line->fk_product = (($objp->fk_product > 0)?$objp->fk_product:0); $line->info_bits = $objp->info_bits; $line->fk_fournprice = $objp->fk_fournprice; @@ -678,26 +741,38 @@ class Contrat extends CommonObject $line->fk_user_cloture = $objp->fk_user_cloture; $line->fk_unit = $objp->fk_unit; - $line->ref = $objp->product_ref; // deprecated - $line->label = $objp->product_label; // deprecated - $line->libelle = $objp->product_label; // deprecated + $line->ref = $objp->product_ref; // deprecated + if (empty($objp->fk_product)) + { + $line->label = ''; // deprecated + $line->libelle = $objp->description; // deprecated + } + else + { + $line->label = $objp->product_label; // deprecated + $line->libelle = $objp->product_label; // deprecated + } $line->product_ref = $objp->product_ref; // Ref product $line->product_desc = $objp->product_desc; // Description product $line->product_label = $objp->product_label; // Label product $line->description = $objp->description; + $line->date_start = $this->db->jdate($objp->date_ouverture_prevue); + $line->date_start_real = $this->db->jdate($objp->date_ouverture); + $line->date_end = $this->db->jdate($objp->date_fin_validite); + $line->date_end_real = $this->db->jdate($objp->date_cloture); + // For backward compatibility $line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue); $line->date_ouverture = $this->db->jdate($objp->date_ouverture); $line->date_fin_validite = $this->db->jdate($objp->date_fin_validite); $line->date_cloture = $this->db->jdate($objp->date_cloture); - // For backward compatibility $line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue); $line->date_debut_reel = $this->db->jdate($objp->date_ouverture); $line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite); $line->date_fin_reel = $this->db->jdate($objp->date_cloture); - // Retreive all extrafield for propal + // Retreive all extrafield for contract // fetch optionals attributes and labels $line->fetch_optionals($line->id,$extralabelsline); @@ -727,108 +802,6 @@ class Contrat extends CommonObject return -3; } - // Selectionne les lignes contrat liees a aucun produit - $sql = "SELECT d.rowid, d.fk_contrat, d.statut, d.qty, d.description, d.price_ht, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.rowid, d.remise_percent, d.subprice,"; - $sql.= " d.total_ht,"; - $sql.= " d.total_tva,"; - $sql.= " d.total_localtax1,"; - $sql.= " d.total_localtax2,"; - $sql.= " d.total_ttc,"; - $sql.= " d.info_bits, d.fk_product,"; - $sql.= " d.date_ouverture_prevue, d.date_ouverture,"; - $sql.= " d.date_fin_validite, d.date_cloture,"; - $sql.= " d.fk_user_author,"; - $sql.= " d.fk_user_ouverture,"; - $sql.= " d.fk_user_cloture,"; - $sql.= " d.fk_unit"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d"; - $sql.= " WHERE d.fk_contrat = ".$this->id; - $sql.= " AND (d.fk_product IS NULL OR d.fk_product = 0)"; // fk_product = 0 gardee pour compatibilitee - - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - - while ($i < $num) - { - $objp = $this->db->fetch_object($result); - - $line = new ContratLigne($this->db); - $line->id = $objp->rowid; - $line->fk_contrat = $objp->fk_contrat; - $line->libelle = $objp->description; - $line->desc = $objp->description; - $line->qty = $objp->qty; - $line->statut = $objp->statut; - $line->ref = ''; - $line->tva_tx = $objp->tva_tx; - $line->localtax1_tx = $objp->localtax1_tx; - $line->localtax2_tx = $objp->localtax2_tx; - $line->localtax1_type = $objp->localtax1_type; - $line->localtax2_type = $objp->localtax2_type; - $line->subprice = $objp->subprice; - $line->remise_percent = $objp->remise_percent; - $line->price_ht = $objp->price_ht; - $line->price = (isset($objp->price)?$objp->price:null); // For backward compatibility - $line->total_ht = $objp->total_ht; - $line->total_tva = $objp->total_tva; - $line->total_localtax1= $objp->total_localtax1; - $line->total_localtax2= $objp->total_localtax2; - $line->total_ttc = $objp->total_ttc; - $line->fk_product = 0; - $line->info_bits = $objp->info_bits; - - $line->fk_user_author = $objp->fk_user_author; - $line->fk_user_ouverture= $objp->fk_user_ouverture; - $line->fk_user_cloture = $objp->fk_user_cloture; - - $line->description = $objp->description; - - $line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue); - $line->date_ouverture = $this->db->jdate($objp->date_ouverture); - $line->date_fin_validite = $this->db->jdate($objp->date_fin_validite); - $line->date_cloture = $this->db->jdate($objp->date_cloture); - // For backward compatibility - $line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue); - $line->date_debut_reel = $this->db->jdate($objp->date_ouverture); - $line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite); - $line->date_fin_reel = $this->db->jdate($objp->date_cloture); - $line->fk_unit = $objp->fk_unit; - - if ($line->statut == 0) $this->nbofserviceswait++; - if ($line->statut == 4 && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++; - if ($line->statut == 4 && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++; - if ($line->statut == 5) $this->nbofservicesclosed++; - - - // Retreive all extrafield for propal - // fetch optionals attributes and labels - - $line->fetch_optionals($line->id,$extralabelsline); - - - $this->lines[$pos] = $line; - $this->lines_id_index_mapper[$line->id] = $pos; - - $total_ttc+=$objp->total_ttc; - $total_vat+=$objp->total_tva; - $total_ht+=$objp->total_ht; - - $i++; - $pos++; - } - - $this->db->free($result); - } - else - { - dol_syslog(get_class($this)."::Fetch Erreur lecture des lignes de contrat non liees aux produits"); - $this->error=$this->db->error(); - return -2; - } - $this->nbofservices=count($this->lines); $this->total_ttc = price2num($total_ttc); // TODO For the moment value is false as value is not stored in database for line linked to products $this->total_vat = price2num($total_vat); // TODO For the moment value is false as value is not stored in database for line linked to products @@ -878,7 +851,7 @@ class Contrat extends CommonObject $sql.= ",".($this->commercial_signature_id>0?$this->commercial_signature_id:"NULL"); $sql.= ",".($this->commercial_suivi_id>0?$this->commercial_suivi_id:"NULL"); $sql.= ",".($this->fk_project>0?$this->fk_project:"NULL"); - $sql.= ", ".(dol_strlen($this->ref)<=0 ? "null" : "'".$this->ref."'"); + $sql.= ", ".(dol_strlen($this->ref)<=0 ? "null" : "'".$this->db->escape($this->ref)."'"); $sql.= ", ".$conf->entity; $sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL"); $sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL"); @@ -922,8 +895,8 @@ class Contrat extends CommonObject { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); - if ($result < 0) + $result=$this->insertExtraFields(); + if ($result < 0) { $error++; } @@ -1295,6 +1268,15 @@ class Contrat extends CommonObject } } + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + // Commit or rollback if ($error) { @@ -1334,13 +1316,14 @@ class Contrat extends CommonObject * @param int $pa_ht Buying price HT * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one - * @return int <0 si erreur, >0 si ok + * @param string $rang Position + * @return int <0 if KO, >0 if OK */ - function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null) + function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null, $rang=0) { global $user, $langs, $conf, $mysoc; - dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits"); + dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang"); if ($this->statut >= 0) { @@ -1359,7 +1342,8 @@ class Contrat extends CommonObject if (empty($info_bits)) $info_bits=0; if (empty($pu_ht) || ! is_numeric($pu_ht)) $pu_ht=0; if (empty($pu_ttc)) $pu_ttc=0; - if (empty($txlocaltax1) || ! is_numeric($txlocaltax1)) $txlocaltax1=0; + if (empty($txtva) || ! is_numeric($txtva)) $txtva=0; + if (empty($txlocaltax1) || ! is_numeric($txlocaltax1)) $txlocaltax1=0; if (empty($txlocaltax2) || ! is_numeric($txlocaltax2)) $txlocaltax2=0; if ($price_base_type=='HT') @@ -1462,6 +1446,8 @@ class Contrat extends CommonObject $resql=$this->db->query($sql); if ($resql) { + $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet"); + $result=$this->update_statut($user); if ($result > 0) { @@ -1470,7 +1456,7 @@ class Contrat extends CommonObject { $contractline = new ContratLigne($this->db); $contractline->array_options=$array_options; - $contractline->id= $this->db->last_insert_id(MAIN_DB_PREFIX.$contractline->table_element); + $contractline->id=$contractlineid; $result=$contractline->insertExtraFields(); if ($result < 0) { @@ -1484,13 +1470,20 @@ class Contrat extends CommonObject $result=$this->call_trigger('LINECONTRACT_INSERT',$user); if ($result < 0) { - $this->db->rollback(); - return -1; + $error++; } // End call triggers + } + if ($error) + { + $this->db->rollback(); + return -1; + } + else + { $this->db->commit(); - return 1; + return $contractlineid; } } else @@ -1540,7 +1533,7 @@ class Contrat extends CommonObject { global $user, $conf, $langs, $mysoc; - // Nettoyage parametres + // Clean parameters $qty=trim($qty); $desc=trim($desc); $desc=trim($desc); @@ -1549,6 +1542,7 @@ class Contrat extends CommonObject $localtax1tx = price2num($localtax1tx); $localtax2tx = price2num($localtax2tx); $pa_ht=price2num($pa_ht); + if (empty($fk_fournprice)) $fk_fournprice=0; $subprice = $price; $remise = 0; @@ -1625,7 +1619,7 @@ class Contrat extends CommonObject $sql.= ", total_localtax1='".price2num($total_localtax1)."'"; $sql.= ", total_localtax2='".price2num($total_localtax2)."'"; $sql.= ", total_ttc='". price2num($total_ttc)."'"; - $sql.= ", fk_product_fournisseur_price='".$fk_fournprice."'"; + $sql.= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null"); $sql.= ", buy_price_ht='".price2num($pa_ht)."'"; if ($date_start > 0) { $sql.= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; } else { $sql.=",date_ouverture_prevue=null"; } @@ -1696,7 +1690,7 @@ class Contrat extends CommonObject * @param User $user User that delete * @return int >0 if OK, <0 if KO */ - function deleteline($idline,$user) + function deleteline($idline, User $user) { global $conf, $langs; @@ -1833,9 +1827,11 @@ class Contrat extends CommonObject $text=''; if ($mode == 4) { - $text=($this->nbofserviceswait+$this->nbofservicesopened+$this->nbofservicesexpired+$this->nbofservicesclosed); + $text =''; + $text.=($this->nbofserviceswait+$this->nbofservicesopened+$this->nbofservicesexpired+$this->nbofservicesclosed); $text.=' '.$langs->trans("Services"); $text.=':     '; + $text.=''; } $text.=($mode == 7?'
    ':''); $text.=($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.$line->LibStatut(0,3,-1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed)?'   ':'') : ''; @@ -1860,19 +1856,28 @@ class Contrat extends CommonObject /** * Return clicable name (with picto eventually) * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $maxlength Max length of ref - * @param int $notooltip 1=Disable tooltip - * @return string Chaine avec URL + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $maxlength Max length of ref + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL */ - function getNomUrl($withpicto=0,$maxlength=0,$notooltip=0) + function getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1) { global $conf, $langs, $user; $result=''; $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id; - $picto = 'contract'; + + //if ($option !== 'nolink') + //{ + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + //} + $label = ''; if ($user->rights->contrat->lire) { @@ -1907,9 +1912,11 @@ class Contrat extends CommonObject $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - $result.=$linkstart.$this->ref.$linkend; + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; + return $result; } @@ -2083,10 +2090,10 @@ class Contrat extends CommonObject if ($mode == 'inactives') { $warning_delay = $conf->contrat->services->inactifs->warning_delay; $label = $langs->trans("BoardNotActivatedServices"); - $url = DOL_URL_ROOT.'/contrat/services.php?mainmenu=commercial&leftmenu=contracts&mode=0'; + $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=0'; } else { $warning_delay = $conf->contrat->services->expires->warning_delay; - $url = DOL_URL_ROOT.'/contrat/services.php?mainmenu=commercial&leftmenu=contracts&mode=4&filter=expired'; + $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=4&filter=expired'; $label = $langs->trans("BoardRunningServices"); } @@ -2241,10 +2248,10 @@ class Contrat extends CommonObject $line->total_ht=90; $line->total_ttc=107.64; // 90 * 1.196 $line->total_tva=17.64; - $line->date_ouverture = dol_now() - 200000; - $line->date_ouverture_prevue = dol_now() - 500000; - $line->date_fin_validite = dol_now() + 500000; - $line->date_cloture = dol_now() - 100000; + $line->date_start = dol_now() - 500000; + $line->date_start_real = dol_now() - 200000; + $line->date_end = dol_now() + 500000; + $line->date_end_real = dol_now() - 100000; if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); @@ -2265,6 +2272,7 @@ class Contrat extends CommonObject return $this->fetch_lines(); } + /** * Create a document onto disk according to template module. * @@ -2457,6 +2465,12 @@ class ContratLigne extends CommonObjectLine var $product_label; var $date_commande; + + var $date_start; // date start planned + var $date_start_real; // date start real + var $date_end; // date end planned + var $date_end_real; // date end real + // For backward compatibility var $date_ouverture_prevue; // date start planned var $date_ouverture; // date start real var $date_fin_validite; // date end planned @@ -2692,10 +2706,17 @@ class ContratLigne extends CommonObjectLine $this->label = $obj->label; // deprecated. We do not use this field. Only ref and label of product, and description of contract line $this->description = $obj->description; $this->date_commande = $this->db->jdate($obj->date_commande); + + $this->date_start = $this->db->jdate($obj->date_ouverture_prevue); + $this->date_start_real = $this->db->jdate($obj->date_ouverture); + $this->date_end = $this->db->jdate($obj->date_fin_validite); + $this->date_end_real = $this->db->jdate($obj->date_cloture); + // For backward compatibility $this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue); $this->date_ouverture = $this->db->jdate($obj->date_ouverture); $this->date_fin_validite = $this->db->jdate($obj->date_fin_validite); $this->date_cloture = $this->db->jdate($obj->date_cloture); + $this->tva_tx = $obj->tva_tx; $this->vat_src_code = $obj->vat_src_code; $this->localtax1_tx = $obj->localtax1_tx; @@ -2782,6 +2803,13 @@ class ContratLigne extends CommonObjectLine if (empty($this->total_ttc)) $this->total_ttc = 0; if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; + if (empty($this->remise_percent)) $this->remise_percent = 0; + // For backward compatibility + if (empty($this->date_start)) $this->date_start=$this->date_ouverture_prevue; + if (empty($this->date_start_real)) $this->date_start=$this->date_ouverture; + if (empty($this->date_end)) $this->date_start=$this->date_fin_validite; + if (empty($this->date_end_real)) $this->date_start=$this->date_cloture; + // Check parameters // Put here code to add control on parameters values @@ -2820,7 +2848,7 @@ class ContratLigne extends CommonObjectLine // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET"; $sql.= " fk_contrat=".$this->fk_contrat.","; - $sql.= " fk_product=".($this->fk_product?"'".$this->fk_product."'":'null').","; + $sql.= " fk_product=".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":'null').","; $sql.= " statut=".$this->statut.","; $sql.= " label='".$this->db->escape($this->label)."',"; $sql.= " description='".$this->db->escape($this->description)."',"; @@ -2954,26 +2982,26 @@ class ContratLigne extends CommonObjectLine $sql.= " info_bits,"; $sql.= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht"; if ($this->date_ouverture_prevue > 0) { $sql.= ",date_ouverture_prevue"; } - if ($this->date_fin_validite > 0) { $sql.= ",date_fin_validite"; } + if ($this->date_fin_validite > 0) { $sql.= ",date_fin_validite"; } $sql.= ") VALUES ($this->fk_contrat, '', '" . $this->db->escape($this->description) . "',"; $sql.= ($this->fk_product>0 ? $this->fk_product : "null").","; - $sql.= " '".$this->qty."',"; - $sql.= " '".$this->vat_src_code."',"; - $sql.= " '".$this->tva_tx."',"; - $sql.= " '".$this->localtax1_tx."',"; - $sql.= " '".$this->localtax2_tx."',"; - $sql.= " '".$this->localtax1_type."',"; - $sql.= " '".$this->localtax2_type."',"; + $sql.= " '".$this->db->escape($this->qty)."',"; + $sql.= " '".$this->db->escape($this->vat_src_code)."',"; + $sql.= " '".$this->db->escape($this->tva_tx)."',"; + $sql.= " '".$this->db->escape($this->localtax1_tx)."',"; + $sql.= " '".$this->db->escape($this->localtax2_tx)."',"; + $sql.= " '".$this->db->escape($this->localtax1_type)."',"; + $sql.= " '".$this->db->escape($this->localtax2_type)."',"; $sql.= " ".price2num($this->remise_percent).",".price2num($this->subprice).","; $sql.= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).","; - $sql.= " '".$this->info_bits."',"; + $sql.= " '".$this->db->escape($this->info_bits)."',"; $sql.= " ".price2num($this->price_ht).",".price2num($this->remise).","; if ($this->fk_fournprice > 0) $sql.= ' '.$this->fk_fournprice.','; else $sql.= ' null,'; if ($this->pa_ht > 0) $sql.= ' '.price2num($this->pa_ht); else $sql.= ' null'; - if ($this->date_ouverture_prevue > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture_prevue)."'"; } - if ($this->date_fin_validite > 0) { $sql.= ",'".$this->db->idate($this->date_fin_validite)."'"; } + if ($this->date_ouverture > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture)."'"; } + if ($this->date_cloture > 0) { $sql.= ",'".$this->db->idate($this->date_cloture)."'"; } $sql.= ")"; dol_syslog(get_class($this)."::insert", LOG_DEBUG); @@ -3010,11 +3038,11 @@ class ContratLigne extends CommonObjectLine /** * Activate a contract line * - * @param User $user Objet User who activate contract - * @param int $date Date d'ouverture - * @param int|string $date_end Date fin prevue - * @param string $comment A comment typed by user - * @return int <0 if KO, >0 if OK + * @param User $user Objet User who activate contract + * @param int $date Date activation + * @param int|string $date_end Date planned end. Use '-1' to keep it unchanged. + * @param string $comment A comment typed by user + * @return int <0 if KO, >0 if OK */ function active_line($user, $date, $date_end = '', $comment = '') { @@ -3033,7 +3061,7 @@ class ContratLigne extends CommonObjectLine $sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = 4,"; $sql .= " date_ouverture = " . (dol_strlen($date) != 0 ? "'" . $this->db->idate($date) . "'" : "null") . ","; - $sql .= " date_fin_validite = " . (dol_strlen($date_end) != 0 ? "'" . $this->db->idate($date_end) . "'" : "null") . ","; + if ($date_end >= 0) $sql .= " date_fin_validite = " . (dol_strlen($date_end) != 0 ? "'" . $this->db->idate($date_end) . "'" : "null") . ","; $sql .= " fk_user_ouverture = " . $user->id . ","; $sql .= " date_cloture = null,"; $sql .= " commentaire = '" . $this->db->escape($comment) . "'"; diff --git a/htdocs/contrat/contact.php b/htdocs/contrat/contact.php index 8510888cf35..aeb433cf455 100644 --- a/htdocs/contrat/contact.php +++ b/htdocs/contrat/contact.php @@ -134,9 +134,9 @@ if ($id > 0 || ! empty($ref)) // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; + - $morehtmlref=''; //if (! empty($modCodeContract->code_auto)) { $morehtmlref.=$object->ref; @@ -144,7 +144,7 @@ if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); }*/ - + $morehtmlref.='
    '; // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1); @@ -196,10 +196,10 @@ if ($id > 0 || ! empty($ref)) print '
    '; print '
    '; - + print ''; - + // Ligne info remises tiers print '
    '.$langs->trans('Discount').''; if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); @@ -225,7 +225,7 @@ if ($id > 0 || ! empty($ref)) print ''; dol_fiche_end(); - + print '
    '; // Contacts lines diff --git a/htdocs/contrat/document.php b/htdocs/contrat/document.php index 132ab187777..351bdc74a46 100644 --- a/htdocs/contrat/document.php +++ b/htdocs/contrat/document.php @@ -107,7 +107,7 @@ if ($object->id) // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref=''; @@ -170,7 +170,7 @@ if ($object->id) print '
    '; print '
    '; - + print ''; print ''; print ''; @@ -179,7 +179,7 @@ if ($object->id) print ''; dol_fiche_end(); - + $modulepart = 'contract'; $permission = $user->rights->contrat->creer; $permtoedit = $user->rights->contrat->creer; diff --git a/htdocs/contrat/index.php b/htdocs/contrat/index.php index 509467cc822..e0874d41595 100644 --- a/htdocs/contrat/index.php +++ b/htdocs/contrat/index.php @@ -30,6 +30,7 @@ require_once (DOL_DOCUMENT_ROOT."/product/class/product.class.php"); $langs->load("products"); $langs->load("companies"); +$langs->load("contracts"); $sortfield=GETPOST('sortfield','alpha'); $sortorder=GETPOST('sortorder','alpha'); @@ -186,10 +187,10 @@ foreach($listofstatus as $status) $dataseries[]=array('label'=>$staticcontratligne->LibStatut($status,1,($bool?1:0)),'data'=>(isset($nb[$status.$bool])?(int) $nb[$status.$bool]:0)); if (empty($conf->use_javascript_ajax)) { - + print ''; print ''; - print ''; + print ''; print "\n"; } if ($status==4 && ! $bool) $bool=true; @@ -206,10 +207,10 @@ $listofstatus=array(0,4,4,5); $bool=false; foreach($listofstatus as $status) { if (empty($conf->use_javascript_ajax)) - { + { print ''; print ''; - print ''; + print ''; if ($status==4 && ! $bool) $bool=true; else $bool=false; print "\n"; @@ -267,7 +268,7 @@ if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire) print ''; //$tot_ttc+=$obj->total_ttc; $i++; - + } } else @@ -327,7 +328,7 @@ if ($result) while ($i < $num) { - $obj = $db->fetch_object($result); + $obj = $db->fetch_object($result); print ''; print ''; print '"; + } - //print '
     
    '; - print "\n"; - } - } + print "
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '.$staticcontratligne->LibStatut($status,0,($bool?1:0)).''.($nb[$status.$bool]?$nb[$status.$bool]:0).' '.$staticcontratligne->LibStatut($status,3,($bool?1:0)).''.($nb[$status.$bool]?$nb[$status.$bool]:0).' '.$staticcontratligne->LibStatut($status,3,($bool?1:0)).'
    '.$staticcontratligne->LibStatut($status,0,($bool?1:0)).''.($nb[$status.$bool]?$nb[$status.$bool]:0).' '.$staticcontratligne->LibStatut($status,3,($bool?1:0)).''.($nb[$status.$bool]?$nb[$status.$bool]:0).' '.$staticcontratligne->LibStatut($status,3,($bool?1:0)).'
    '; @@ -393,7 +394,7 @@ if ($resql) while ($i < min($num,$max)) { $obj = $db->fetch_object($resql); - + print '
    '; $staticcontrat->ref=($obj->ref?$obj->ref:$obj->fk_contrat); @@ -467,13 +468,13 @@ if ($resql) print ''; - print ''; + print ''; print "\n"; while ($i < $num) { $obj = $db->fetch_object($resql); - + print ''; print ''; } @@ -450,7 +465,7 @@ if (! empty($arrayfields['cd.subprice']['checked'])) // Third party if (! empty($arrayfields['s.nom']['checked'])) { - print ''; } @@ -459,7 +474,7 @@ if (! empty($arrayfields['s.nom']['checked'])) if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) { print ''; + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -525,26 +545,26 @@ $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // N print $hookmanager->resPrint; if (! empty($arrayfields['cd.datec']['checked'])) { - // Date creation - print ''; + // Date creation + print ''; } if (! empty($arrayfields['cd.tms']['checked'])) { - // Date modification - print ''; + // Date modification + print ''; } if (! empty($arrayfields['status']['checked'])) { - // Status - print ''; @@ -571,16 +591,16 @@ while ($i < min($num,$limit)) print ''; // Ref - if (! empty($arrayfields['c.ref']['checked'])) - { - print ''; - } + } // Service - if (! empty($arrayfields['p.description']['checked'])) - { - print ''; - } + } - if (! empty($arrayfields['cd.qty']['checked'])) - { - print ''; - } - if (! empty($arrayfields['cd.total_ht']['checked'])) - { - print ''; - } - if (! empty($arrayfields['cd.total_tva']['checked'])) - { - print ''; - } - if (! empty($arrayfields['cd.tva_tx']['checked'])) - { - print ''; - } - if (! empty($arrayfields['cd.subprice']['checked'])) - { - print ''; - } + if (! empty($arrayfields['cd.qty']['checked'])) + { + print ''; + } + if (! empty($arrayfields['cd.total_ht']['checked'])) + { + print ''; + } + if (! empty($arrayfields['cd.total_tva']['checked'])) + { + print ''; + } + if (! empty($arrayfields['cd.tva_tx']['checked'])) + { + print ''; + } + if (! empty($arrayfields['cd.subprice']['checked'])) + { + print ''; + } // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } + } // Start date - if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) - { + if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) + { print ''; } - if (! empty($arrayfields['cd.date_ouverture']['checked'])) - { - print ''; + if (! empty($arrayfields['cd.date_ouverture']['checked'])) + { + print ''; } // End date - if (! empty($arrayfields['cd.date_fin_validite']['checked'])) - { - print ''; - } - if (! empty($arrayfields['cd.date_cloture']['checked'])) - { - print ''; - } + print ''; + } + if (! empty($arrayfields['cd.date_cloture']['checked'])) + { + print ''; + } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); @@ -699,18 +719,18 @@ while ($i < min($num,$limit)) // Date creation if (! empty($arrayfields['cd.datec']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['cd.tms']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Status if (! empty($arrayfields['status']['checked'])) @@ -718,11 +738,11 @@ while ($i < min($num,$limit)) print ''; } @@ -730,9 +750,9 @@ while ($i < min($num,$limit)) print ''; if (! $i) $totalarray['nbfield']++; diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php new file mode 100644 index 00000000000..b2ec79af5a7 --- /dev/null +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -0,0 +1,142 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + */ + +/** + * \file htdocs/core/actions_addupdatedelete.inc.php + * \brief Code for common actions cancel / add / update / delete + */ + + +// $action or $cancel must be defined +// $object must be defined +// $permissiontoadd must be defined +// $permissiontodelete must be defined +// $backurlforlist must be defined +// $backtopage may be defined + +if ($cancel) +{ + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + $action=''; +} + +// Action to add record +if ($action == 'add' && ! empty($permissiontoadd)) +{ + foreach ($object->fields as $key => $val) + { + if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'fk_user_modif', 'import_key'))) continue; // Ignore special fields + + $value = GETPOST($key,'alpha'); + if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value=''; // This is an implicit foreign key field + if (! empty($object->fields[$key]['foreignkey']) && $value == '-1') $value=''; // This is an explicit foreign key field + + $object->$key=$value; + if ($val['notnull'] > 0 && $object->$key == '') + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv($val['label'])), null, 'errors'); + } + } + + if (! $error) + { + $result=$object->createCommon($user); + if ($result > 0) + { + // Creation OK + $urltogo=$backtopage?$backtopage:$backurlforlist; + header("Location: ".$urltogo); + exit; + } + else + { + // Creation KO + if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + $action='create'; + } + } + else + { + $action='create'; + } +} + +// Action to update record +if ($action == 'update' && ! empty($permissiontoadd)) +{ + foreach ($object->fields as $key => $val) + { + if (! GETPOSTISSET($key)) continue; // The field was not submited to be edited + if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'fk_user_modif', 'import_key'))) continue; // Ignore special fields + + $value = GETPOST($key,'alpha'); + if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value=''; // This is an implicit foreign key field + if (! empty($object->fields[$key]['foreignkey']) && $value == '-1') $value=''; // This is an explicit foreign key field + + $object->$key=$value; + if ($val['notnull'] > 0 && $object->$key == '') + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv($val['label'])), null, 'errors'); + } + } + + if (! $error) + { + $result=$object->updateCommon($user); + if ($result > 0) + { + $action='view'; + } + else + { + // Creation KO + if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + $action='edit'; + } + } + else + { + $action='edit'; + } +} + +// Action to delete +if ($action == 'confirm_delete' && ! empty($permissiontodelete)) +{ + $result=$object->deleteCommon($user); + if ($result > 0) + { + // Delete OK + setEventMessages("RecordDeleted", null, 'mesgs'); + header("Location: ".$backurlforlist); + exit; + } + else + { + if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + } +} diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php index 70876d4bf9a..dd996f83f57 100644 --- a/htdocs/core/actions_builddoc.inc.php +++ b/htdocs/core/actions_builddoc.inc.php @@ -33,8 +33,8 @@ // Build doc if ($action == 'builddoc' && $permissioncreate) { - - if (is_numeric(GETPOST('model'))) + + if (is_numeric(GETPOST('model','alpha'))) { $error=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Model")); } @@ -48,18 +48,18 @@ if ($action == 'builddoc' && $permissioncreate) dol_print_error('Object must have been loaded by a fetch'); exit; }*/ - + // Save last template used to generate document - if (GETPOST('model')) + if (GETPOST('model','alpha')) { $object->setDocModel($user, GETPOST('model','alpha')); } - + // Special case to force bank account //if (property_exists($object, 'fk_bank')) //{ - if (GETPOST('fk_bank')) { // this field may come from an external module - $object->fk_bank = GETPOST('fk_bank'); + if (GETPOST('fk_bank','int')) { // this field may come from an external module + $object->fk_bank = GETPOST('fk_bank','int'); } else if (! empty($object->fk_account)) { $object->fk_bank = $object->fk_account; } @@ -76,13 +76,13 @@ if ($action == 'builddoc' && $permissioncreate) $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } - + // To be sure vars is defined if (empty($hidedetails)) $hidedetails=0; if (empty($hidedesc)) $hidedesc=0; if (empty($hideref)) $hideref=0; if (empty($moreparams)) $moreparams=null; - + $result= $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); if ($result <= 0) { @@ -91,11 +91,13 @@ if ($action == 'builddoc' && $permissioncreate) } else { - if (empty($donotredirect)) // This is se when include is done by bulk action "Bill Orders" + if (empty($donotredirect)) // This is use when include is done by bulk action "Bill Orders" { setEventMessages($langs->trans("FileGenerated"), null); - header('Location: '.$_SERVER['REQUEST_URI'].'#builddoc'); + $redirecturl = $_SERVER['REQUEST_URI']; + $redirecturl = preg_replace('/&?action=builddoc/', '', $redirecturl); // Remove action=builddoc parameter to avoid infinite loop + header('Location: '.$redirecturl.'#builddoc'); exit; } } diff --git a/htdocs/core/actions_comments.inc.php b/htdocs/core/actions_comments.inc.php new file mode 100644 index 00000000000..ee45a035043 --- /dev/null +++ b/htdocs/core/actions_comments.inc.php @@ -0,0 +1,76 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + * + * $elementype must be defined. + */ + +/** + * \file htdocs/core/actions_comments.inc.php + * \brief Code for actions on comments pages + */ + + +require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php'; + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$comment = new Comment($db); + +/* + * Actions + */ + +if ($action == 'addcomment') +{ + $description = GETPOST('comment_description', 'none'); + if (!empty($description)) + { + $comment->description = $description; + $comment->datec = time(); + $comment->fk_element = GETPOST('id','int'); + $comment->element_type = GETPOST('comment_element_type','alpha'); + $comment->fk_user_author = $user->id; + $comment->entity = $conf->entity; + if ($comment->create($user) > 0) + { + setEventMessages($langs->trans("CommentAdded"), null, 'mesgs'); + header('Location: '.$varpage.'?id='.$id.($withproject?'&withproject=1':'')); + exit; + } + else + { + setEventMessages($comment->error, $comment->errors,'errors'); + $action=''; + } + } +} +if ($action == 'deletecomment') +{ + if ($comment->fetch($idcomment) >= 0) + { + if ($comment->delete($user) > 0) + { + setEventMessages($langs->trans("CommentDeleted"), null, 'mesgs'); + header('Location: '.$varpage.'?id='.$id.($withproject?'&withproject=1':'')); + exit; + } + else + { + setEventMessages($comment->error, $comment->errors,'errors'); + $action=''; + } + } +} \ No newline at end of file diff --git a/htdocs/core/actions_extrafields.inc.php b/htdocs/core/actions_extrafields.inc.php index aee2a39e563..6b6d40acd9c 100644 --- a/htdocs/core/actions_extrafields.inc.php +++ b/htdocs/core/actions_extrafields.inc.php @@ -160,11 +160,15 @@ if ($action == 'add') } } + // Visibility: -1=not visible by default in list, 1=visible, 0=hidden + $visibility = GETPOST('list', 'alpha'); + if ($type == 'separate') $visibility=3; + $result=$extrafields->addExtraField( GETPOST('attrname', 'alpha'), GETPOST('label', 'alpha'), $type, - GETPOST('pos', 'alpha'), + GETPOST('pos', 'int'), $extrasize, $elementtype, (GETPOST('unique', 'alpha')?1:0), @@ -173,9 +177,11 @@ if ($action == 'add') $params, (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') + $visibility, + 0, + GETPOST('computed_value','alpha'), + (GETPOST('entitycurrentorall', 'alpha')?0:''), + GETPOST('langfile', 'alpha') ); if ($result > 0) { @@ -321,6 +327,10 @@ if ($action == 'update') } } + // Visibility: -1=not visible by default in list, 1=visible, 0=hidden + $visibility = GETPOST('list', 'alpha'); + if ($type == 'separate') $visibility=3; + $result=$extrafields->update( GETPOST('attrname', 'alpha'), GETPOST('label', 'alpha'), @@ -333,10 +343,12 @@ if ($action == 'update') $params, (GETPOST('alwayseditable', 'alpha')?1:0), (GETPOST('perms', 'alpha')?GETPOST('perms', 'alpha'):''), - (GETPOST('list', 'alpha')?1:0), - (GETPOST('ishidden', 'alpha')?1:0), + $visibility, + 0, GETPOST('default_value','alpha'), - GETPOST('computed_value','alpha') + GETPOST('computed_value','alpha'), + (GETPOST('entitycurrentorall', 'alpha')?0:''), + GETPOST('langfile') ); if ($result > 0) { diff --git a/htdocs/core/actions_fetchobject.inc.php b/htdocs/core/actions_fetchobject.inc.php index 520d3c2d6da..6a2d7196d0f 100644 --- a/htdocs/core/actions_fetchobject.inc.php +++ b/htdocs/core/actions_fetchobject.inc.php @@ -28,9 +28,9 @@ // $cancel must be defined // $id or $ref must be defined (object is loaded in this file with fetch) -if (($id > 0 || (! empty($ref) && ! in_array($action, array('create','createtask')))) && empty($cancel)) +if (($id > 0 || (! empty($ref) && ! in_array($action, array('create', 'createtask', 'add')))) && (empty($cancel) || $id > 0)) { - $ret = $object->fetch($id,$ref); + $ret = $object->fetch($id, $ref); if ($ret > 0) { $object->fetch_thirdparty(); @@ -38,7 +38,8 @@ if (($id > 0 || (! empty($ref) && ! in_array($action, array('create','createtask } else { - setEventMessages($object->error, $object->errors, 'errors'); + if (empty($object->error) && ! count($object->errors)) setEventMessages('Fetch on object return an error without filling $object->error nor $object->errors', null, 'errors'); + else setEventMessages($object->error, $object->errors, 'errors'); $action=''; } } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 32d80bef672..e6e9bbea604 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2015-2017 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,6 +26,7 @@ // $objectclass and $$objectlabel must be defined // $parameters, $object, $action must be defined for the hook. +// $permtoread, $permtocreate and $permtodelete may be defined // $uploaddir may be defined (example to $conf->projet->dir_output."/";) // $toselect may be defined @@ -33,8 +34,8 @@ // Protection if (empty($objectclass) || empty($uploaddir)) { - dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined'); - exit; + dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined'); + exit; } @@ -42,367 +43,442 @@ if (empty($objectclass) || empty($uploaddir)) $maxformassaction=(empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS)?1000:$conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS); if (! empty($massaction) && count($toselect) < 1) { - $error++; - setEventMessages($langs->trans("NoRecordSelected"), null, "warnings"); + $error++; + setEventMessages($langs->trans("NoRecordSelected"), null, "warnings"); } if (! $error && count($toselect) > $maxformassaction) { - setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); - $error++; + setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); + $error++; } if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail')) // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form { - $massaction='presend'; + $massaction='presend'; } if (! $error && $massaction == 'confirm_presend') { - $resaction = ''; - $nbsent = 0; - $nbignored = 0; - $langs->load("mails"); - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + $resaction = ''; + $nbsent = 0; + $nbignored = 0; + $langs->load("mails"); + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (!$error && !isset($user->email)) - { - $error++; - setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings'); - } + $listofobjectid=array(); + $listofobjectthirdparties=array(); + $listofobjectref=array(); - if (! $error) - { - $thirdparty=new Societe($db); - $objecttmp=new $objectclass($db); - $listofobjectid=array(); - $listofobjectthirdparties=array(); - $listofobjectref=array(); - foreach($toselect as $toselectid) - { - $objecttmp=new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofobjectid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; - $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp; - } - } - //var_dump($listofobjectthirdparties);exit; + if (! $error) + { + $thirdparty=new Societe($db); + if ($objecttmp->element == 'expensereport') $thirdparty=new User($db); + + $objecttmp=new $objectclass($db); + foreach($toselect as $toselectid) + { + $objecttmp=new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $listofobjectid[$toselectid]=$toselectid; + $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; + if ($objecttmp->element == 'societe') $thirdpartyid=$objecttmp->id; + if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author; + $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; + $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp; + } + } + } + + // Check mandatory parameters + if (empty($user->email)) + { + $error++; + setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings'); + $massaction='presend'; + } + + $receiver=$_POST['receiver']; + if (! is_array($receiver)) + { + if (empty($receiver) || $receiver == '-1') $receiver=array(); + else $receiver=array($receiver); + } + if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) // if only one recipient, receiver is mandatory + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings'); + $massaction='presend'; + } + + if (! GETPOST('subject','none')) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings'); + $massaction='presend'; + } + + // Loop on each recipient/thirdparty + if (! $error) + { + foreach ($listofobjectthirdparties as $thirdpartyid) + { + $result = $thirdparty->fetch($thirdpartyid); + if ($result < 0) + { + dol_print_error($db); + exit; + } + + $sendto=''; + $sendtocc=''; + $sendtobcc=''; + $sendtoid = array(); + + // Define $sendto + $tmparray=array(); + if (trim($_POST['sendto'])) + { + // Recipients are provided into free text + $tmparray[] = trim($_POST['sendto']); + } + if (count($receiver)>0) + { + foreach($receiver as $key=>$val) + { + // Recipient was provided from combo list + if ($val == 'thirdparty') // Id of third party or user + { + $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; + } + elseif ($val && method_exists($thirdparty, 'contact_get_property')) // Id of contact + { + $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); + $sendtoid[] = $val; + } + } + } + $sendto=implode(',',$tmparray); + + // Define $sendtocc + $receivercc=$_POST['receivercc']; + if (! is_array($receivercc)) + { + if ($receivercc == '-1') $receivercc=array(); + else $receivercc=array($receivercc); + } + $tmparray=array(); + if (trim($_POST['sendtocc'])) + { + $tmparray[] = trim($_POST['sendtocc']); + } + if (count($receivercc) > 0) + { + foreach($receivercc as $key=>$val) + { + // Recipient was provided from combo list + if ($val == 'thirdparty') // Id of third party + { + $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; + } + elseif ($val) // Id du contact + { + $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); + //$sendtoid[] = $val; TODO Add also id of contact in CC ? + } + } + } + $sendtocc=implode(',',$tmparray); + + //var_dump($listofobjectref);exit; + $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array()); + $listofqualifiedid=array(); + $listofqualifiedref=array(); + $thirdpartywithoutemail=array(); + + foreach($listofobjectref[$thirdpartyid] as $objectid => $object) + { + //var_dump($thirdpartyid.' - '.$objectid.' - '.$object->statut); + if ($objectclass == 'Propal' && $object->statut == Propal::STATUS_DRAFT) + { + $langs->load("errors"); + $nbignored++; + $resaction.='
    '.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$object->ref).'

    '; + continue; // Payment done or started or canceled + } + if ($objectclass == 'Commande' && $object->statut == Commande::STATUS_DRAFT) + { + $langs->load("errors"); + $nbignored++; + $resaction.='
    '.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$object->ref).'

    '; + continue; + } + if ($objectclass == 'Facture' && $object->statut != Facture::STATUS_VALIDATED) + { + $langs->load("errors"); + $nbignored++; + $resaction.='
    '.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$object->ref).'

    '; + continue; // Payment done or started or canceled + } + + // Test recipient + if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send) + { + if ($object->element == 'expensereport') + { + $fuser = new User($db); + $fuser->fetch($object->fk_user_author); + $sendto = $fuser->email; + } + else + { + $object->fetch_thirdparty(); + $sendto = $object->thirdparty->email; + } + } + + if (empty($sendto)) + { + //print "No recipient for thirdparty ".$object->thirdparty->name; + $nbignored++; + if (empty($thirdpartywithoutemail[$object->thirdparty->id])) + { + $resaction.='
    '.$langs->trans('NoRecipientEmail',$object->thirdparty->name).'

    '; + } + dol_syslog('No recipient for thirdparty: '.$object->thirdparty->name, LOG_WARNING); + $thirdpartywithoutemail[$object->thirdparty->id]=1; + continue; + } + + if ($_POST['addmaindocfile']) + { + // TODO Use future field $object->fullpathdoc to know where is stored default file + // TODO If not defined, use $object->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc. + $filename=dol_sanitizeFileName($object->ref).'.pdf'; + $filedir=$uploaddir . '/' . dol_sanitizeFileName($object->ref); + $file = $filedir . '/' . $filename; + $mime = dol_mimetype($file); + + if (dol_is_file($file)) + { + // Create form object + $attachedfiles=array( + 'paths'=>array_merge($attachedfiles['paths'],array($file)), + 'names'=>array_merge($attachedfiles['names'],array($filename)), + 'mimes'=>array_merge($attachedfiles['mimes'],array($mime)) + ); + } + else + { + $nbignored++; + $langs->load("errors"); + $resaction.='
    '.$langs->trans('ErrorCantReadFile',$file).'

    '; + dol_syslog('Failed to read file: '.$file, LOG_WARNING); + continue; + } + } + + // Object of thirdparty qualified + $listofqualifiedid[$objectid]=$object; + $listofqualifiedref[$objectid]=$object->ref; - // Loop on each thirdparty - foreach ($listofobjectthirdparties as $thirdpartyid) - { - $result = $thirdparty->fetch($thirdpartyid); - if ($result < 0) - { - dol_print_error($db); - exit; - } + //var_dump($listofqualifiedref); + } - $sendto=''; - $sendtocc=''; - $sendtobcc=''; - $sendtoid = array(); + // Send email if there is at least one qualified record + if (count($listofqualifiedid) > 0) + { + $langs->load("commercial"); - // Define $sendto - $receiver=$_POST['receiver']; - if (! is_array($receiver)) - { - if ($receiver == '-1') $receiver=array(); - else $receiver=array($receiver); - } - $tmparray=array(); - if (trim($_POST['sendto'])) - { - // Recipients are provided into free text - $tmparray[] = trim($_POST['sendto']); - } - if (count($receiver)>0) - { - foreach($receiver as $key=>$val) - { - // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party - { - $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } - elseif ($val) // Id du contact - { - $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); - $sendtoid[] = $val; - } - } - } - $sendto=implode(',',$tmparray); + $fromtype = GETPOST('fromtype'); + if ($fromtype === 'user') { + $from = $user->getFullName($langs) .' <'.$user->email.'>'; + } + elseif ($fromtype === 'company') { + $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; + } + elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) { + $tmp=explode(',', $user->email_aliases); + $from = trim($tmp[($reg[1] - 1)]); + } + elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) { + $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); + $from = trim($tmp[($reg[1] - 1)]); + } + elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) { + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1]; + $resql = $db->query($sql); + $obj = $db->fetch_object($resql); + if ($obj) + { + $from = $obj->label.' <'.$obj->email.'>'; + } + } + else { + $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; + } - // Define $sendtocc - $receivercc=$_POST['receivercc']; - if (! is_array($receivercc)) - { - if ($receivercc == '-1') $receivercc=array(); - else $receivercc=array($receivercc); - } - $tmparray=array(); - if (trim($_POST['sendtocc'])) - { - $tmparray[] = trim($_POST['sendtocc']); - } - if (count($receivercc) > 0) - { - foreach($receivercc as $key=>$val) - { - // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party - { - $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } - elseif ($val) // Id du contact - { - $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); - //$sendtoid[] = $val; TODO Add also id of contact in CC ? - } - } - } - $sendtocc=implode(',',$tmparray); + $replyto = $from; + $subject = GETPOST('subject','none'); + $message = GETPOST('message','none'); - //var_dump($listofobjectref);exit; - $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array()); - $listofqualifiedid=array(); - $listofqualifiedref=array(); - foreach($listofobjectref[$thirdpartyid] as $objectid => $object) - { - //var_dump($thirdpartyid.' - '.$objectid.' - '.$object->statut); + $sendtobcc = GETPOST('sendtoccc'); + if ($objectclass == 'Propale') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); + if ($objectclass == 'Commande') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)); + if ($objectclass == 'Facture') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)); + if ($objectclass == 'Supplier_Proposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)); + if ($objectclass == 'CommandeFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)); + if ($objectclass == 'FactureFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)); - if ($objectclass == 'Facture' && $object->statut != Facture::STATUS_VALIDATED) - { - $langs->load("errors"); - $nbignored++; - $resaction.='
    '.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$object->ref).'

    '; - continue; // Payment done or started or canceled - } - if ($objectclass == 'Commande' && $object->statut == Commande::STATUS_DRAFT) - { - $langs->load("errors"); - $nbignored++; - $resaction.='
    '.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$object->ref).'

    '; - continue; - } + // $listofqualifiedid is array with key = object id of qualified objects for the current thirdparty + $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0); + $looparray=array(); + if (! $oneemailperrecipient) + { + $looparray = $listofqualifiedid; + } + else + { + $objectforloop=new $objectclass($db); + $objectforloop->thirdparty = $thirdparty; + $looparray[0]=$objectforloop; + } + //var_dump($looparray);exit; - // Read document - // TODO Use future field $object->fullpathdoc to know where is stored default file - // TODO If not defined, use $object->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc. - $filename=dol_sanitizeFileName($object->ref).'.pdf'; - $filedir=$uploaddir . '/' . dol_sanitizeFileName($object->ref); - $file = $filedir . '/' . $filename; - $mime = dol_mimetype($file); + foreach ($looparray as $objecttmp) // $objecttmp is a real object or an empty if we choose to send one email per thirdparty instead of per record + { + // Make substitution in email content + $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp); + $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedid)) : $objecttmp->id); + $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref); + $substitutionarray['__EMAIL__'] = $thirdparty->email; + $substitutionarray['__CHECK_READ__'] = ''; - if (dol_is_file($file)) - { - if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send) - { - $object->fetch_thirdparty(); - $sendto = $object->thirdparty->email; - } + $parameters=array('mode'=>'formemail'); + complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters); - if (empty($sendto)) - { - //print "No recipient for thirdparty ".$object->thirdparty->name; - $nbignored++; - continue; - } + $subject=make_substitutions($subject, $substitutionarray); + $message=make_substitutions($message, $substitutionarray); - if (dol_strlen($sendto)) - { - // Create form object - $attachedfiles=array( - 'paths'=>array_merge($attachedfiles['paths'],array($file)), - 'names'=>array_merge($attachedfiles['names'],array($filename)), - 'mimes'=>array_merge($attachedfiles['mimes'],array($mime)) - ); - } + $filepath = $attachedfiles['paths']; + $filename = $attachedfiles['names']; + $mimetype = $attachedfiles['mimes']; - $listofqualifiedid[$objectid]=$object; - $listofqualifiedref[$objectid]=$object->ref; - } - else - { - $nbignored++; - $langs->load("errors"); - $resaction.='
    '.$langs->trans('ErrorCantReadFile',$file).'

    '; - dol_syslog('Failed to read file: '.$file, LOG_WARNING); - continue; - } + //var_dump($filepath); - //var_dump($listofqualifiedref); - } + // Send mail (substitutionarray must be done just before this) + require_once(DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'); + $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1); + if ($mailfile->error) + { + $resaction.='
    '.$mailfile->error.'
    '; + } + else + { + $result=$mailfile->sendfile(); + if ($result) + { + $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'
    '; // Must not contain " - // Loop on each qualified objects of the thirdparty - if (count($listofqualifiedid) > 0) - { - $langs->load("commercial"); + $error=0; - $fromtype = GETPOST('fromtype'); - if ($fromtype === 'user') { - $from = $user->getFullName($langs) .' <'.$user->email.'>'; - } - elseif ($fromtype === 'company') { - $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; - } - elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) { - $tmp=explode(',', $user->email_aliases); - $from = trim($tmp[($reg[1] - 1)]); - } - elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) { - $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); - $from = trim($tmp[($reg[1] - 1)]); - } - else { - $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; - } + // Insert logs into agenda + foreach($listofqualifiedid as $objid => $object) + { + /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP'; + if ($objectclass == 'Commande') $actiontypecode='AC_COM'; + if ($objectclass == 'Facture') $actiontypecode='AC_FAC'; + if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO'; + if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD'; + if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/ - $replyto = $from; - $subject = GETPOST('subject'); - $message = GETPOST('message'); + $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; + if ($message) + { + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); + } + $actionmsg2=''; - $sendtobcc = GETPOST('sendtoccc'); - if ($objectclass == 'Propale') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); - if ($objectclass == 'Commande') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)); - if ($objectclass == 'Facture') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)); - if ($objectclass == 'Supplier_Proposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)); - if ($objectclass == 'CommandeFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)); - if ($objectclass == 'FactureFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)); + // Initialisation donnees + $object->sendtoid = 0; + $object->actionmsg = $actionmsg; // Long text + $object->actionmsg2 = $actionmsg2; // Short text + $object->fk_element = $objid; + $object->elementtype = $object->element; + $triggername = strtoupper(get_class($object)) .'_SENTBYMAIL'; + if ($triggername == 'SOCIETE_SENTBYMAIL') $triggername = 'COMPANY_SENTBYEMAIL'; + if ($triggername == 'CONTRAT_SENTBYMAIL') $triggername = 'CONTRACT_SENTBYEMAIL'; + if ($triggername == 'COMMANDE_SENTBYMAIL') $triggername = 'ORDER_SENTBYEMAIL'; + if ($triggername == 'FACTURE_SENTBYMAIL') $triggername = 'BILL_SENTBYEMAIL'; + if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL'; + if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL'; + if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL'; + if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL'; - $substitutionarray=array( - '__DOL_MAIN_URL_ROOT__'=>DOL_MAIN_URL_ROOT, - '__ID__' => join(', ',array_keys($listofqualifiedid)), - '__EMAIL__' => $thirdparty->email, - '__CHECK_READ__' => '', - '__FACREF__' => join(', ',$listofqualifiedref), // For backward compatibility - '__ORDERREF__' => join(', ',$listofqualifiedref), // For backward compatibility - '__PROPREF__' => join(', ',$listofqualifiedref), // For backward compatibility - '__REF__' => join(', ',$listofqualifiedref), - '__REFCLIENT__' => $thirdparty->name, - '__SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?dol_string_nohtmltag($user->signature):'') - /* not available on all object - /'__FIRSTNAME__'=>(is_object($object)?$object->firstname:''), - '__LASTNAME__'=>(is_object($object)?$object->lastname:''), - '__FULLNAME__'=>(is_object($object)?$object->getFullName($langs):''), - '__ADDRESS__'=>(is_object($object)?$object->address:''), - '__ZIP__'=>(is_object($object)?$object->zip:''), - '__TOWN_'=>(is_object($object)?$object->town:''), - '__COUNTRY__'=>(is_object($object)?$object->country:''), - */ - ); + if (! empty($trigger_name)) + { + // Appel des triggers + include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); + $interface=new Interfaces($db); + $result=$interface->run_triggers($trigger_name, $object, $user, $langs, $conf); + if ($result < 0) { $error++; $errors=$interface->errors; } + // Fin appel triggers - $subject=make_substitutions($subject, $substitutionarray); - $message=make_substitutions($message, $substitutionarray); + if ($error) + { + setEventMessages($db->lasterror(), $errors, 'errors'); + dol_syslog("Error in trigger ".$trigger_name.' '.$db->lasterror(), LOG_ERR); + } + } - $filepath = $attachedfiles['paths']; - $filename = $attachedfiles['names']; - $mimetype = $attachedfiles['mimes']; + $nbsent++; + } + } + else + { + $langs->load("other"); + if ($mailfile->error) + { + $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); + $resaction.='
    '.$mailfile->error.'
    '; + } + else + { + $resaction.='
    No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS
    '; + } + } + } + } + } + } - //var_dump($filepath); + $resaction.=($resaction?'
    ':$resaction); + $resaction.=''.$langs->trans("ResultOfMailSending").':
    '."\n"; + $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n
    "; + $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n
    "; + $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n
    "; - // Send mail (substitutionarray must be done just before this) - require_once(DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'); - $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1); - if ($mailfile->error) - { - $resaction.='
    '.$mailfile->error.'
    '; - } - else - { - $result=$mailfile->sendfile(); - if ($result) - { - $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'
    '; // Must not contain " + if ($nbsent) + { + $action=''; // Do not show form post if there was at least one successfull sent + //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs'); + setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs'); + setEventMessages($resaction, null, 'mesgs'); + } + else + { + //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file + setEventMessages($resaction, null, 'warnings'); + } - $error=0; - - // Insert logs into agenda - foreach($listofqualifiedid as $objid => $object) - { - /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP'; - if ($objectclass == 'Commande') $actiontypecode='AC_COM'; - if ($objectclass == 'Facture') $actiontypecode='AC_FAC'; - if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO'; - if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD'; - if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/ - - $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; - if ($message) - { - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); - $actionmsg = dol_concatdesc($actionmsg, $message); - } - $actionmsg2=''; - - // Initialisation donnees - $object->sendtoid = 0; - $object->actionmsg = $actionmsg; // Long text - $object->actionmsg2 = $actionmsg2; // Short text - $object->fk_element = $objid; - $object->elementtype = $object->element; - - // Appel des triggers - include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); - $interface=new Interfaces($db); - $result=$interface->run_triggers('BILL_SENTBYMAIL',$object,$user,$langs,$conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers - - if ($error) - { - setEventMessages($db->lasterror(), $errors, 'errors'); - dol_syslog("Error in trigger BILL_SENTBYMAIL ".$db->lasterror(), LOG_ERR); - } - $nbsent++; - } - } - else - { - $langs->load("other"); - if ($mailfile->error) - { - $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); - $resaction.='
    '.$mailfile->error.'
    '; - } - else - { - $resaction.='
    No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS
    '; - } - } - } - } - } - - $resaction.=($resaction?'
    ':$resaction); - $resaction.=''.$langs->trans("ResultOfMailSending").':
    '."\n"; - $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n
    "; - $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n
    "; - $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n
    "; - - if ($nbsent) - { - $action=''; // Do not show form post if there was at least one successfull sent - //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs'); - setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs'); - setEventMessages($resaction, null, 'mesgs'); - } - else - { - //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file - setEventMessages($resaction, null, 'warnings'); - } - } - - $action='list'; - $massaction=''; + $action='list'; + $massaction=''; + } } if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_search')) @@ -413,59 +489,59 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se exit; } - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $objecttmp=new $objectclass($db); - $listofobjectid=array(); - $listofobjectthirdparties=array(); - $listofobjectref=array(); - foreach($toselect as $toselectid) - { - $objecttmp=new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofobjectid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; - $listofobjectref[$toselectid]=$objecttmp->ref; - } - } + $objecttmp=new $objectclass($db); + $listofobjectid=array(); + $listofobjectthirdparties=array(); + $listofobjectref=array(); + foreach($toselect as $toselectid) + { + $objecttmp=new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $listofobjectid[$toselectid]=$toselectid; + $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; + $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; + $listofobjectref[$toselectid]=$objecttmp->ref; + } + } - $arrayofinclusion=array(); - foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote($tmppdf.'.pdf','/').'$'; - $listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true); + $arrayofinclusion=array(); + foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote($tmppdf.'.pdf','/').'$'; + $listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true); - // build list of files with full path - $files = array(); - foreach($listofobjectref as $basename) - { - foreach($listoffiles as $filefound) - { - if (strstr($filefound["name"],$basename)) - { - $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"]; - break; - } - } - } + // build list of files with full path + $files = array(); + foreach($listofobjectref as $basename) + { + foreach($listoffiles as $filefound) + { + if (strstr($filefound["name"],$basename)) + { + $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"]; + break; + } + } + } - // Define output language (Here it is not used because we do only merging existing PDF) - $outputlangs = $langs; - $newlang=''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->thirdparty->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } + // Define output language (Here it is not used because we do only merging existing PDF) + $outputlangs = $langs; + $newlang=''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->thirdparty->default_lang; + if (! empty($newlang)) + { + $outputlangs = new Translate("",$conf); + $outputlangs->setDefaultLang($newlang); + } - if(!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) - { - // Create output dir if not exists + if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) + { + // Create output dir if not exists dol_mkdir($diroutputmassaction); // Defined name of merged file @@ -473,7 +549,7 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se $filename=preg_replace('/\s/','_',$filename); // Save merged file - if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) + if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) { if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); @@ -481,152 +557,227 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se if ($year) $filename.='_'.$year; if ($month) $filename.='_'.$month; - if (count($files)>0) - { + if (count($files)>0) + { + $now=dol_now(); + $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf'; - $now=dol_now(); - $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf'; + $input_files = ''; + foreach($files as $f) { + $input_files.=' '.escapeshellarg($f); + } - $input_files = ''; - foreach($files as $f) { - $input_files.=' '.escapeshellarg($f); - } + $cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file); + exec($cmd); - $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file); - exec($cmd); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); + $langs->load("exports"); + setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); + } + else + { + setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors'); + } + } + else { + // Create empty PDF + $formatarray=pdf_getFormat(); + $page_largeur = $formatarray['width']; + $page_hauteur = $formatarray['height']; + $format = array($page_largeur,$page_hauteur); - $langs->load("exports"); - setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); - } - else - { - setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors'); - } + $pdf=pdf_getInstance($format); - } - else { - // Create empty PDF - $formatarray=pdf_getFormat(); - $page_largeur = $formatarray['width']; - $page_hauteur = $formatarray['height']; - $format = array($page_largeur,$page_hauteur); - - $pdf=pdf_getInstance($format); - - if (class_exists('TCPDF')) - { + if (class_exists('TCPDF')) + { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); - } - $pdf->SetFont(pdf_getPDFFont($outputlangs)); + } + $pdf->SetFont(pdf_getPDFFont($outputlangs)); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - // Add all others - foreach($files as $file) - { + // Add all others + foreach($files as $file) + { // Charge un document PDF depuis un fichier. $pagecount = $pdf->setSourceFile($file); for ($i = 1; $i <= $pagecount; $i++) { - $tplidx = $pdf->importPage($i); - $s = $pdf->getTemplatesize($tplidx); - $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); - $pdf->useTemplate($tplidx); + $tplidx = $pdf->importPage($i); + $s = $pdf->getTemplatesize($tplidx); + $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); + $pdf->useTemplate($tplidx); } - } + } - // Create output dir if not exists - dol_mkdir($diroutputmassaction); + // Create output dir if not exists + dol_mkdir($diroutputmassaction); - // Defined name of merged file - $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel))); - $filename=preg_replace('/\s/','_',$filename); + // Defined name of merged file + $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel))); + $filename=preg_replace('/\s/','_',$filename); - // Save merged file - if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) - { + // Save merged file + if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) + { if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); - } - if ($year) $filename.='_'.$year; - if ($month) $filename.='_'.$month; - if ($pagecount) - { + } + if ($year) $filename.='_'.$year; + if ($month) $filename.='_'.$month; + if ($pagecount) + { $now=dol_now(); $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf'; $pdf->Output($file,'F'); if (! empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); + @chmod($file, octdec($conf->global->MAIN_UMASK)); - $langs->load("exports"); - setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); - } - else - { + $langs->load("exports"); + setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); + } + else + { setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors'); - } - } + } + } } // Remove a file from massaction area if ($action == 'remove_file') { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $langs->load("other"); - $upload_dir = $diroutputmassaction; - $file = $upload_dir . '/' . GETPOST('file'); - $ret=dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); - $action=''; + $langs->load("other"); + $upload_dir = $diroutputmassaction; + $file = $upload_dir . '/' . GETPOST('file'); + $ret=dol_delete_file($file); + if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); + else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + $action=''; +} + +// Validate records +if (! $error && $massaction == 'validate' && $permtocreate) +{ + if ($object->element == 'invoice' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL)) + { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors'); + $error++; + } + if ($object->element == 'invoice_supplier' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) + { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors'); + $error++; + } + if (! $error) + { + $db->begin(); + + $objecttmp=new $objectclass($db); + $nbok = 0; + foreach($toselect as $toselectid) + { + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + //if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); + //else + $result = $objecttmp->validate($user); + if ($result == 0) + { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors'); + $error++; + break; + } + elseif ($result < 0) + { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + else $nbok++; + } + else + { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + } + + if (! $error) + { + if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + $db->commit(); + } + else + { + $db->rollback(); + } + //var_dump($listofobjectthirdparties);exit; + } } // Delete records if (! $error && $massaction == 'delete' && $permtodelete) { - $db->begin(); + $db->begin(); - $objecttmp=new $objectclass($db); - $nbok = 0; - foreach($toselect as $toselectid) - { - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); - else $result = $objecttmp->delete($user); - if ($result <= 0) - { - setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); - $error++; - break; - } - else $nbok++; - } - else - { - setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); - $error++; - break; - } - } + $objecttmp=new $objectclass($db); + $nbok = 0; + foreach($toselect as $toselectid) + { + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + // Refuse deletion for some status ? + /* + if ($objectclass == 'Facture' && $objecttmp->status == Facture::STATUS_DRAFT) + { + $langs->load("errors"); + $nbignored++; + $resaction.='
    '.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$object->ref).'

    '; + continue; + }*/ - if (! $error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); - $db->commit(); - } - else - { - $db->rollback(); - } - //var_dump($listofobjectthirdparties);exit; + if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); + else $result = $objecttmp->delete($user); + + if ($result <= 0) + { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + else $nbok++; + } + else + { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + } + + if (! $error) + { + if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); + else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + $db->commit(); + } + else + { + $db->rollback(); + } + //var_dump($listofobjectthirdparties);exit; } $parameters['toselect']=$toselect; diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index fca8ac511da..57b6ae80b6c 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -18,13 +18,13 @@ /** * \file htdocs/core/actions_sendmails.inc.php -* \brief Code for actions on sending mails from object page -*/ + * \brief Code for actions on sending mails from object page + */ // $mysoc must be defined // $id must be defined // $paramname must be defined -// $mode must be defined +// $mode must be defined (used to know the automatic BCC to add) // $trigger_name must be set (can be '') // $actiontypecode can be set // $object and $uobject may be defined @@ -113,13 +113,18 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $result=$object->fetch($id); $sendtosocid=0; // Thirdparty on object - if (method_exists($object,"fetch_thirdparty") && $object->element != 'societe') + if (method_exists($object,"fetch_thirdparty") && ! in_array($object->element, array('societe','member','user'))) { $result=$object->fetch_thirdparty(); if ($object->element == 'user' && $result == 0) $result=1; // Even if not found, we consider ok $thirdparty=$object->thirdparty; $sendtosocid=$thirdparty->id; } + else if ($object->element == 'member' || $object->element == 'user') + { + $thirdparty=$object; + if ($thirdparty->id > 0) $sendtosocid=$thirdparty->id; + } else if ($object->element == 'societe') { $thirdparty=$object; @@ -253,12 +258,22 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); $from = trim($tmp[($reg[1] - 1)]); } + elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) { + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1]; + $resql = $db->query($sql); + $obj = $db->fetch_object($resql); + if ($obj) + { + $from = $obj->label.' <'.$obj->email.'>'; + } + } else { $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; } $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>'; - $message = $_POST['message']; + $message = GETPOST('message','none'); + $subject = GETPOST('subject','none'); // Make a change into HTML code to allow to include images from medias directory with an external reabable URL. // @@ -266,19 +281,18 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO // $message=preg_replace('/()/', '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $message); - $sendtobcc = GETPOST('sendtoccc'); - if ($mode == 'emailfromproposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); - if ($mode == 'emailfromorder') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)); - if ($mode == 'emailfrominvoice') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)); - if ($mode == 'emailfromsupplierproposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)); - if ($mode == 'emailfromsupplierorder') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)); - if ($mode == 'emailfromsupplierinvoice') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)); + $sendtobcc= GETPOST('sendtoccc'); + // Autocomplete the $sendtobcc + // $autocopy can be MAIN_MAIL_AUTOCOPY_PROPOSAL_TO, MAIN_MAIL_AUTOCOPY_ORDER_TO, MAIN_MAIL_AUTOCOPY_INVOICE_TO, MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO... + if (! empty($autocopy)) + { + $sendtobcc .= (empty($conf->global->$autocopy) ? '' : (($sendtobcc?", ":"").$conf->global->$autocopy)); + } $deliveryreceipt = $_POST['deliveryreceipt']; if ($action == 'send' || $action == 'relance') { - if (dol_strlen($_POST['subject'])) $subject = $_POST['subject']; $actionmsg2=$langs->transnoentities('MailSentBy').' '.CMailFile::getValidAddress($from,4,0,1).' '.$langs->transnoentities('To').' '.CMailFile::getValidAddress($sendto,4,0,1); if ($message) { @@ -344,30 +358,27 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO } } + // Make substitution in email content + $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $object); + $substitutionarray['__EMAIL__'] = $sendto; + $substitutionarray['__CHECK_READ__'] = (is_object($object) && is_object($object->thirdparty))?'':''; - $substitutionarray=array( - '__DOL_MAIN_URL_ROOT__'=>DOL_MAIN_URL_ROOT, - '__ID__' => (is_object($object)?$object->id:''), - '__EMAIL__' => $sendto, - '__CHECK_READ__' => (is_object($object) && is_object($object->thirdparty))?'':'', - '__REF__' => (is_object($object)?$object->ref:''), - '__SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:'') - /* not available on all object - /'__FIRSTNAME__'=>(is_object($object)?$object->firstname:''), - '__LASTNAME__'=>(is_object($object)?$object->lastname:''), - '__FULLNAME__'=>(is_object($object)?$object->getFullName($langs):''), - '__ADDRESS__'=>(is_object($object)?$object->address:''), - '__ZIP__'=>(is_object($object)?$object->zip:''), - '__TOWN_'=>(is_object($object)?$object->town:''), - '__COUNTRY__'=>(is_object($object)?$object->country:''), - */ - ); + $parameters=array('mode'=>'formemail'); + complete_substitutions_array($substitutionarray, $langs, $object, $parameters); $subject=make_substitutions($subject, $substitutionarray); $message=make_substitutions($message, $substitutionarray); + if (method_exists($object, 'makeSubstitution')) + { + $subject = $object->makeSubstitution($subject); + $message = $object->makeSubstitution($message); + } + // Send mail (substitutionarray must be done just before this) - $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid); + if (empty($sendcontext)) $sendcontext = 'standard'; + $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid,'', $sendcontext); + if ($mailfile->error) { setEventMessage($mailfile->error, 'errors'); @@ -413,6 +424,9 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $object->trackid = $trackid; $object->fk_element = $object->id; $object->elementtype = $object->element; + if (is_array($attachedfiles) && count($attachedfiles)>0) { + $object->attachedfiles = $attachedfiles; + } // Call of triggers if (! empty($trigger_name)) @@ -420,7 +434,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; $interface=new Interfaces($db); $result=$interface->run_triggers($trigger_name,$object,$user,$langs,$conf); - if ($result < 0) { + if ($result < 0) { $error++; $errors=$interface->errors; } } @@ -476,7 +490,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO else { $langs->load("other"); - setEventMessages($langs->trans('ErrorFailedToReadEntity',$object->element), null, 'errors'); + setEventMessages($langs->trans('ErrorFailedToReadObject',$object->element), null, 'errors'); dol_syslog('Failed to read data of object id='.$object->id.' element='.$object->element); $action = 'presend'; } diff --git a/htdocs/core/actions_setmoduleoptions.inc.php b/htdocs/core/actions_setmoduleoptions.inc.php index b8ae96cb920..eadce1dc74c 100644 --- a/htdocs/core/actions_setmoduleoptions.inc.php +++ b/htdocs/core/actions_setmoduleoptions.inc.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2014-2017 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,15 +17,43 @@ */ /** - * \file htdocs/core/actions_setnotes.inc.php + * \file htdocs/core/actions_setmoduleoptions.inc.php * \brief Code for actions on setting notes of object page */ // $action must be defined -// $_FILES may be defined +// $arrayofparameters must be set for action 'update' +// $nomessageinupdate can be set to 1 // $nomessageinsetmoduleoptions can be set to 1 +if ($action == 'update' && is_array($arrayofparameters)) +{ + $db->begin(); + + $ok=True; + foreach($arrayofparameters as $key => $val) + { + $result=dolibarr_set_const($db,$key,GETPOST($key, 'alpha'),'chaine',0,'',$conf->entity); + if ($result < 0) + { + $ok=False; + break; + } + } + + if (! $error) + { + $db->commit(); + if (empty($nomessageinupdate)) setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } + else + { + $db->rollback(); + if (empty($nomessageinupdate)) setEventMessages($langs->trans("SetupNotSaved"), null, 'errors'); + } +} + // Define constants for submodules that contains parameters (forms with param1, param2, ... and value1, value2, ...) if ($action == 'setModuleOptions') { diff --git a/htdocs/core/actions_setnotes.inc.php b/htdocs/core/actions_setnotes.inc.php index 3fa76891124..50b35392644 100644 --- a/htdocs/core/actions_setnotes.inc.php +++ b/htdocs/core/actions_setnotes.inc.php @@ -28,18 +28,18 @@ // $id must be defined (object is loaded in this file with fetch) // Set public note -if ($action == 'setnote_public' && ! empty($permissionnote) && ! GETPOST('cancel')) +if ($action == 'setnote_public' && ! empty($permissionnote) && ! GETPOST('cancel','alpha')) { if (empty($action) || ! is_object($object) || empty($id)) dol_print_error('','Include of actions_setnotes.inc.php was done but required variable was not set before'); if (empty($object->id)) $object->fetch($id); // Fetch may not be already done - $result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public'); + $result=$object->update_note(dol_html_entity_decode(GETPOST('note_public', 'none'), ENT_QUOTES),'_public'); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } // Set public note -else if ($action == 'setnote_private' && ! empty($permissionnote) && ! GETPOST('cancel')) +else if ($action == 'setnote_private' && ! empty($permissionnote) && ! GETPOST('cancel','alpha')) { if (empty($action) || ! is_object($object) || empty($id)) dol_print_error('','Include of actions_setnotes.inc.php was done but required variable was not set before'); if (empty($object->id)) $object->fetch($id); // Fetch may not be already done - $result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private'); + $result=$object->update_note(dol_html_entity_decode(GETPOST('note_private', 'none'), ENT_QUOTES),'_private'); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index cee16f923f5..ddcf8eb62d8 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -32,7 +32,6 @@ if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); - if (! isset($mode) || $mode != 'noajax') // For ajax call { require_once '../../main.inc.php'; @@ -40,11 +39,12 @@ if (! isset($mode) || $mode != 'noajax') // For ajax call require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; - $action=GETPOST('action','aZ09'); - $file=urldecode(GETPOST('file')); - $section=GETPOST("section"); - $module=GETPOST("module"); - $urlsource=GETPOST("urlsource"); + $action=GETPOST('action','aZ09'); + $file=urldecode(GETPOST('file','alpha')); + $section=GETPOST("section",'alpha'); + $module=GETPOST("module",'alpha'); + $urlsource=GETPOST("urlsource",'alpha'); + $search_doc_ref=GETPOST('search_doc_ref','alpha'); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); @@ -56,7 +56,9 @@ if (! isset($mode) || $mode != 'noajax') // For ajax call if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="name"; - $upload_dir = dirname(str_replace("../","/", $conf->ecm->dir_output.'/'.$file)); + $rootdirfordoc = $conf->ecm->dir_output; + + $upload_dir = dirname(str_replace("../", "/", $rootdirfordoc.'/'.$file)); $ecmdir = new EcmDirectory($db); $result=$ecmdir->fetch($section); @@ -68,7 +70,9 @@ if (! isset($mode) || $mode != 'noajax') // For ajax call } else // For no ajax call { - $ecmdir = new EcmDirectory($db); + $rootdirfordoc = $conf->ecm->dir_output; + + $ecmdir = new EcmDirectory($db); $relativepath=''; if ($section > 0) { @@ -80,14 +84,12 @@ else // For no ajax call } } $relativepath=$ecmdir->getRelativePath(); - $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; + $upload_dir = $rootdirfordoc.'/'.$relativepath; } if (empty($url)) $url=DOL_URL_ROOT.'/ecm/index.php'; // Load traductions files -$langs->load("ecm"); -$langs->load("companies"); -$langs->load("other"); +$langs->loadLangs(array("ecm","companies","other")); // Security check if ($user->societe_id > 0) $socid = $user->societe_id; @@ -95,8 +97,7 @@ if ($user->societe_id > 0) $socid = $user->societe_id; //print 'xxx'.$upload_dir; // Security: -// On interdit les remontees de repertoire ainsi que les pipe dans -// les noms de fichiers. +// On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers. if (preg_match('/\.\./',$upload_dir) || preg_match('/[<>|]/',$upload_dir)) { dol_syslog("Refused to deliver file ".$upload_dir); @@ -105,6 +106,16 @@ if (preg_match('/\.\./',$upload_dir) || preg_match('/[<>|]/',$upload_dir)) exit; } +// Check permissions +if ($modulepart == 'ecm') +{ + if (! $user->rights->ecm->read) accessforbidden(); +} +if ($modulepart == 'medias') +{ + // Always allowed +} + /* * Action @@ -153,8 +164,8 @@ if ($type == 'directory') $excludefiles = array('^SPECIMEN\.pdf$','^\.','(\.meta|_preview.*\.png)$','^temp$','^payments$','^CVS$','^thumbs$'); $sorting = (strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC); - // Right area. If module is defined, we are in automatic ecm. - $automodules = array('company', 'invoice', 'invoice_supplier', 'propal', 'order', 'order_supplier', 'contract', 'product', 'tax', 'project', 'fichinter', 'user', 'expensereport'); + // Right area. If module is defined here, we are in automatic ecm. + $automodules = array('company', 'invoice', 'invoice_supplier', 'propal', 'supplier_proposal', 'order', 'order_supplier', 'contract', 'product', 'tax', 'project', 'fichinter', 'user', 'expensereport'); // TODO change for multicompany sharing // Auto area for suppliers invoices @@ -163,8 +174,10 @@ if ($type == 'directory') else if ($module == 'invoice') $upload_dir = $conf->facture->dir_output; // Auto area for suppliers invoices else if ($module == 'invoice_supplier') $upload_dir = $conf->fournisseur->facture->dir_output; - // Auto area for customers orders + // Auto area for customers proposal else if ($module == 'propal') $upload_dir = $conf->propal->dir_output; + // Auto area for suppliers proposal + else if ($module == 'supplier_proposal') $upload_dir = $conf->supplier_proposal->dir_output; // Auto area for customers orders else if ($module == 'order') $upload_dir = $conf->commande->dir_output; // Auto area for suppliers orders @@ -188,35 +201,70 @@ if ($type == 'directory') if (in_array($module, $automodules)) { $param.='&module='.$module; + if (isset($search_doc_ref) && $search_doc_ref != '') $param.='&search_doc_ref='.$search_doc_ref; + $textifempty=($section?$langs->trans("NoFileFound"):($showonrightsize=='featurenotyetavailable'?$langs->trans("FeatureNotYetAvailable"):$langs->trans("NoFileFound"))); if ($module == 'company') $excludefiles[]='^contact$'; // The subdir 'contact' contains files of contacts with no id of thirdparty. - $filearray=dol_dir_list($upload_dir,"files",1,'', $excludefiles, $sortfield, $sorting,1); - $formfile->list_of_autoecmfiles($upload_dir,$filearray,$module,$param,1,'',$user->rights->ecm->upload,1,$textifempty,$maxlengthname,$url); + $filter=preg_quote($search_doc_ref, '/'); + $filearray=dol_dir_list($upload_dir, "files", 1, $filter, $excludefiles, $sortfield, $sorting,1); + + $perm=$user->rights->ecm->upload; + + $formfile->list_of_autoecmfiles($upload_dir,$filearray,$module,$param,1,'',$perm,1,$textifempty,$maxlengthname,$url,1); } // Manual list else { - $relativepath=$ecmdir->getRelativePath(); - $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; + if ($module == 'medias') + { + $relativepath=GETPOST('file','alpha'); + if ($relativepath && $relativepath!= '/') $relativepath.='/'; + $upload_dir = $dolibarr_main_data_root.'/'.$module.'/'.$relativepath; + } + else + { + $relativepath=$ecmdir->getRelativePath(); + $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; + } // If $section defined with value 0 - if ($section === '0' || empty($section)) + if (($section === '0' || empty($section)) && ($module != 'medias')) { $filearray=array(); } - else $filearray=dol_dir_list($upload_dir,"files",0,'',array('^\.','(\.meta|_preview.*\.png)$','^temp$','^CVS$'),$sortfield, $sorting,1); + else + { + $filearray=dol_dir_list($upload_dir,"files",0,'',array('^\.','(\.meta|_preview.*\.png)$','^temp$','^CVS$'),$sortfield, $sorting,1); + } if ($section) { $param.='§ion='.$section; + if (isset($search_doc_ref) && $search_doc_ref != '') $param.='&search_doc_ref='.$search_doc_ref; + $textifempty = $langs->trans('NoFileFound'); } - else if ($section === '0') $textifempty='
    '.$langs->trans("DirNotSynchronizedSyncFirst").'

    '; + else if ($section === '0') + { + if ($module == 'ecm') $textifempty='
    '.$langs->trans("DirNotSynchronizedSyncFirst").'

    '; + else $textifempty = $langs->trans('NoFileFound'); + } else $textifempty=($showonrightsize=='featurenotyetavailable'?$langs->trans("FeatureNotYetAvailable"):$langs->trans("ECMSelectASection")); - $formfile->list_of_documents($filearray,'','ecm',$param,1,$relativepath,$user->rights->ecm->upload,1,$textifempty,$maxlengthname,'',$url); + if ($module == 'medias') + { + $modulepart='medias'; + $perm=($user->rights->websites->creer || $user->rights->emailing->creer); + } + else + { + $modulepart='ecm'; + $perm=$user->rights->ecm->upload; + } + + $formfile->list_of_documents($filearray,'',$modulepart,$param,1,$relativepath,$perm,1,$textifempty,$maxlengthname,'',$url); } } diff --git a/htdocs/core/ajax/ajaxdirtree.php b/htdocs/core/ajax/ajaxdirtree.php index 14b05c75905..9d0908953c6 100644 --- a/htdocs/core/ajax/ajaxdirtree.php +++ b/htdocs/core/ajax/ajaxdirtree.php @@ -23,35 +23,46 @@ // This script is called with a POST method. -// Directory to scan (full path) is inside POST['dir']. +// Directory to scan (full path) is inside POST['dir'] and encode by js escape() if ajax is used or encoded by urlencode if mode=noajax if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -$res=@include '../../main.inc.php'; -include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; -include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -include_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; -include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; -include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; +if (! isset($mode) || $mode != 'noajax') // For ajax call +{ + $res=@include '../../main.inc.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; -$openeddir = GETPOST('openeddir'); -$modulepart= GETPOST('modulepart'); -$selecteddir = jsUnEscape(GETPOST('dir')); // relative path. We must decode using same encoding function used by javascript: escape() -if ($selecteddir != '/') $selecteddir = preg_replace('/\/$/','',$selecteddir); // We removed last '/' except if it is '/' + $openeddir = GETPOST('openeddir'); + $modulepart= GETPOST('modulepart'); + $selecteddir = jsUnEscape(GETPOST('dir')); // relative path. We must decode using same encoding function used by javascript: escape() + if ($selecteddir != '/') $selecteddir = preg_replace('/\/$/','',$selecteddir); // We removed last '/' except if it is '/' +} +else // For no ajax call +{ + $openeddir = GETPOST('openeddir'); + $modulepart= GETPOST('modulepart'); + $selecteddir = GETPOST('dir'); + if ($selecteddir != '/') $selecteddir = preg_replace('/\/$/','',$selecteddir); // We removed last '/' except if it is '/' + if (empty($url)) $url=DOL_URL_ROOT.'/ecm/index.php'; +} $langs->load("ecm"); -// Define selecteddir (fullpath). +// Define fullpathselecteddir. +$fullpathselecteddir=''; if ($modulepart == 'ecm') $fullpathselecteddir=$conf->ecm->dir_output.'/'.($selecteddir != '/' ? $selecteddir : ''); +if ($modulepart == 'medias') $fullpathselecteddir=$dolibarr_main_data_root.'/medias/'.($selecteddir != '/' ? $selecteddir : ''); // Security: -// On interdit les remontees de repertoire ainsi que les pipe dans -// les noms de fichiers. +// On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers. if (preg_match('/\.\./',$fullpathselecteddir) || preg_match('/[<>|]/',$fullpathselecteddir)) { dol_syslog("Refused to deliver file ".$original_file); @@ -63,16 +74,22 @@ if (preg_match('/\.\./',$fullpathselecteddir) || preg_match('/[<>|]/',$fullpaths // Check permissions if ($modulepart == 'ecm') { - if (! $user->rights->ecm->read) accessforbidden(); + if (! $user->rights->ecm->read) accessforbidden(); +} +if ($modulepart == 'medias') +{ + // Always allowed } - /* * View */ -top_httphead(); +if (! isset($mode) || $mode != 'noajax') +{ + top_httphead(); +} //print ''."\n"; $userstatic=new User($db); @@ -93,139 +110,323 @@ foreach($sqltree as $keycursor => $val) } } - -if (file_exists($fullpathselecteddir)) +if (! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) { - $files = @scandir($fullpathselecteddir); - if ($files) - { - natcasesort($files); - if ( count($files) > 2 ) /* The 2 accounts for . and .. */ - { - echo "
      \n"; + if (file_exists($fullpathselecteddir)) + { + $files = @scandir($fullpathselecteddir); - // All dirs - foreach( $files as $file ) // $file can be '.', '..', or 'My dir' or 'My file' - { - if ($file == 'temp') continue; + if ($files) + { + natcasesort($files); + if (count($files) > 2) /* The 2 accounts for . and .. */ + { + echo '
    '.$langs->trans("NotActivatedServices").' '.$num.'
    '.$langs->trans("NotActivatedServices").' '.$num.'
    '; @@ -547,13 +548,13 @@ if ($resql) print ''; - print ''; + print ''; print "\n"; while ($i < $num) { $obj = $db->fetch_object($resql); - + print ''; print ''; - print ''; + print ''; + } + if (! empty($arrayfields['c.ref_customer']['checked'])) + { + print ''; + } + if (! empty($arrayfields['c.ref_supplier']['checked'])) + { + print ''; + } + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + } + if (! empty($arrayfields['s.email']['checked'])) + { + print ''; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['sale_representative']['checked'])) + { + // Sales representatives + print ''; + } + // Date + if (! empty($arrayfields['c.date_contrat']['checked'])) + { + print ''; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['c.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['c.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date lower end date + if (! empty($arrayfields['lower_planned_end_date']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['status']['checked'])) + { + print ''; + print ''; + print ''; + print ''; + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print "\n"; + $i++; + } + $db->free($resql); + + print '
    '.$langs->trans("ListOfExpiredServices").' '.$num.'
    '.$langs->trans("ListOfExpiredServices").' '.$num.'
    '; diff --git a/htdocs/contrat/info.php b/htdocs/contrat/info.php index 95ab0b9ca25..7f5d0c103fa 100644 --- a/htdocs/contrat/info.php +++ b/htdocs/contrat/info.php @@ -62,7 +62,7 @@ dol_fiche_head($head, 'info', $langs->trans("Contract"), -1, 'contract'); // Contract card -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; $morehtmlref=''; diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index 221a4233f5a..38bfef6ebe2 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -29,8 +29,9 @@ */ require ("../main.inc.php"); -require_once (DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php"); +require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -46,12 +47,14 @@ $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); $search_name=GETPOST('search_name'); +$search_email=GETPOST('search_email'); $search_town=GETPOST('search_town','alpha'); $search_zip=GETPOST('search_zip','alpha'); $search_state=trim(GETPOST("search_state")); $search_country=GETPOST("search_country",'int'); $search_type_thirdparty=GETPOST("search_type_thirdparty",'int'); $search_contract=GETPOST('search_contract'); +$search_ref_customer=GETPOST('search_ref_customer','alpha'); $search_ref_supplier=GETPOST('search_ref_supplier','alpha'); $sall=GETPOST('sall', 'alphanohtml'); $search_status=GETPOST('search_status'); @@ -59,6 +62,9 @@ $socid=GETPOST('socid'); $search_user=GETPOST('search_user','int'); $search_sale=GETPOST('search_sale','int'); $search_product_category=GETPOST('search_product_category','int'); +$search_dfmonth=GETPOST('search_dfmonth','int'); +$search_dfyear=GETPOST('search_dfyear','int'); +$search_op2df=GETPOST('search_op2df'); $day=GETPOST("day","int"); $year=GETPOST("year","int"); $month=GETPOST("month","int"); @@ -81,6 +87,8 @@ $id=GETPOST('id','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'contrat', $id); +$diroutputmassaction=$conf->contrat->dir_output . '/temp/massgeneration/'.$user->id; + $staticcontrat=new Contrat($db); $staticcontratligne=new ContratLigne($db); @@ -98,37 +106,39 @@ $extralabels = $extrafields->fetch_name_optionals_label('contrat'); $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'c.ref'=>'Ref', - 'c.ref_customer'=>'RefCustomer', - 'c.ref_supplier'=>'RefSupplier', - 's.nom'=>"ThirdParty", - 'cd.description'=>'Description', - 'c.note_public'=>'NotePublic', + 'c.ref'=>'Ref', + 'c.ref_customer'=>'RefCustomer', + 'c.ref_supplier'=>'RefSupplier', + 's.nom'=>"ThirdParty", + 'cd.description'=>'Description', + 'c.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["c.note_private"]="NotePrivate"; $arrayfields=array( - 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'c.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 'c.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>0), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'sale_representative'=>array('label'=>$langs->trans("SalesRepresentative"), 'checked'=>1), - 'c.date_contrat'=>array('label'=>$langs->trans("DateContract"), 'checked'=>1), - 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'c.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 'c.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.email'=>array('label'=>$langs->trans("ThirdPartyEmail"), 'checked'=>0), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>0), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'sale_representative'=>array('label'=>$langs->trans("SalesRepresentative"), 'checked'=>1), + 'c.date_contrat'=>array('label'=>$langs->trans("DateContract"), 'checked'=>1), + 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'lower_planned_end_date'=>array('label'=>$langs->trans("LowerDateEndPlannedShort"), 'checked'=>1, 'position'=>900), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } } @@ -136,8 +146,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Action */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -151,17 +161,22 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $day=''; $month=''; $year=''; - $search_name=""; + $search_dfmonth=''; + $search_dfyear=''; + $search_op2df=''; + $search_name=""; + $search_email=""; $search_town=''; $search_zip=""; $search_state=""; $search_type=''; $search_country=''; $search_contract=""; + $search_ref_customer=""; $search_ref_supplier=""; - $search_user=''; - $search_sale=''; - $search_product_category=''; + $search_user=''; + $search_sale=''; + $search_product_category=''; $sall=""; $search_status=""; $toselect=''; @@ -170,12 +185,12 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', if (empty($reshook)) { - $objectclass='Contrat'; - $objectlabel='Contracts'; - $permtoread = $user->rights->contrat->lire; - $permtodelete = $user->rights->contrat->supprimer; - $uploaddir = $conf->contrat->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + $objectclass='Contrat'; + $objectlabel='Contracts'; + $permtoread = $user->rights->contrat->lire; + $permtodelete = $user->rights->contrat->supprimer; + $uploaddir = $conf->contrat->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -184,7 +199,8 @@ if (empty($reshook)) */ $now=dol_now(); -$form=new Form($db); +$form = new Form($db); +$formfile = new FormFile($db); $formother = new FormOther($db); $socstatic = new Societe($db); $contracttmp = new Contrat($db); @@ -193,9 +209,10 @@ llxHeader('', $langs->trans("Contracts")); $sql = 'SELECT'; $sql.= " c.rowid, c.ref, c.datec as date_creation, c.tms as date_update, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public,"; -$sql.= ' s.rowid as socid, s.nom as name, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; +$sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; $sql.= " typent.code as typent_code,"; $sql.= " state.code_departement as state_code, state.nom as state_name,"; +$sql.= " MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") as lower_planned_end_date,"; $sql.= ' SUM('.$db->ifsql("cd.statut=0",1,0).') as nb_initial,'; $sql.= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NULL OR cd.date_fin_validite >= '".$db->idate($now)."')",1,0).') as nb_running,'; $sql.= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AND cd.date_fin_validite < '".$db->idate($now)."')",1,0).') as nb_expired,'; @@ -218,8 +235,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= " WHERE c.fk_soc = s.rowid "; $sql.= ' AND c.entity IN ('.getEntity('contract').')'; @@ -228,19 +245,21 @@ if ($socid) $sql.= " AND s.rowid = ".$db->escape($socid); if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(c.date_contrat, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(c.date_contrat, '%m') = '".$month."'"; } else if ($year > 0) { $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($search_name) $sql .= natural_search('s.nom', $search_name); +if ($search_email) $sql .= natural_search('s.email', $search_name); if ($search_contract) $sql .= natural_search(array('c.rowid', 'c.ref'), $search_contract); +if (!empty($search_ref_customer)) $sql .= natural_search(array('c.ref_customer'), $search_ref_customer); if (!empty($search_ref_supplier)) $sql .= natural_search(array('c.ref_supplier'), $search_ref_supplier); if ($search_sale > 0) { @@ -251,26 +270,32 @@ if ($search_user > 0) $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.elemen // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; +if ($search_dfyear > 0) +{ +// $sql.= " AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") ".$search_op2df."= '".$db->idate(($search_op2df == "<" ? dol_get_last_day($search_dfyear,$search_dfmonth,false) : dol_get_first_day($search_dfyear,$search_dfmonth,false)))."'"; +} + $sql.= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public,"; -$sql.= ' s.rowid, s.nom, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; +$sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; $sql.= " typent.code,"; $sql.= " state.code_departement, state.nom"; +//$sql.= " MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").")"; // Add fields from extrafields foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); // Add where from hooks @@ -278,20 +303,25 @@ $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; +if ($search_dfyear > 0) +{ + $sql.= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") ".$search_op2df."= '".$db->idate(($search_op2df == "<" ? dol_get_last_day($search_dfyear,$search_dfmonth,false) : dol_get_first_day($search_dfyear,$search_dfmonth,false)))."'"; +} + $sql.= $db->order($sortfield,$sortorder); $totalnboflines=0; $result=$db->query($sql); if ($result) { - $totalnboflines = $db->num_rows($result); + $totalnboflines = $db->num_rows($result); } $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit + 1, $offset); @@ -299,10 +329,10 @@ $sql.= $db->plimit($limit + 1, $offset); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; + $num = $db->num_rows($resql); + $i = 0; - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected=is_array($toselect)?$toselect:array(); if ($socid > 0) { @@ -311,35 +341,42 @@ if ($resql) if (empty($search_name)) $search_name = $soc->name; } - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sall != '') $param.='&sall='.$sall; - if ($search_contract != '') $param.='&search_contract='.$search_contract; - if ($search_name != '') $param.='&search_name='.$search_name; - if ($search_ref_supplier != '') $param.='&search_ref_supplier='.$search_ref_supplier; - if ($search_sale != '') $param.='&search_sale=' .$search_sale; - if ($show_files) $param.='&show_files=' .$show_files; - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($sall != '') $param.='&sall='.urlencode($sall); + if ($search_contract != '') $param.='&search_contract='.urlencode($search_contract); + if ($search_name != '') $param.='&search_name='.urlencode($search_name); + if ($search_email != '') $param.='&search_email='.urlencode($search_email); + if ($search_ref_customer != '') $param.='&search_ref_customer='.urlencode($search_ref_customer); + if ($search_ref_supplier != '') $param.='&search_ref_supplier='.urlencode($search_ref_supplier); + if ($search_op2df != '') $param.='&search_op2df='.urlencode($search_op2df); + if ($search_dfyear != '') $param.='&search_dfyear='.urlencode($search_dfyear); + if ($search_dfmonth != '') $param.='&search_dfmonth='.urlencode($search_dfmonth); + if ($search_sale != '') $param.='&search_sale=' .urlencode($search_sale); + if ($search_user != '') $param.='&search_user=' .urlencode($search_user); + if ($search_product_category != '') $param.='&search_product_category=' .urlencode($search_product_category); + if ($show_files) $param.='&show_files=' .urlencode($show_files); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } - // List of mass actions available - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), - ); - if ($user->rights->contrat->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + // List of mass actions available + $arrayofmassactions = array( + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), + ); + if ($user->rights->contrat->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + if ($massaction == 'presend') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - print '
    '; - if ($optioncss != '') print ''; + print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; @@ -347,31 +384,41 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'title_commercial.png', 0, '', '', $limit); + print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'title_commercial.png', 0, '', '', $limit); + + if ($massaction == 'presend') + { + $topicmail="SendContractRef"; + $modelmail="contract"; + $objecttmp=new Contrat($db); + $trackid='con'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; + } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } - $moreforfilter=''; + $moreforfilter=''; - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; - $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user,0,1,'maxwidth200'); - $moreforfilter.='
    '; - } + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) + { + $langs->load("commercial"); + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; + $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user,0,1,'maxwidth200'); + $moreforfilter.='
    '; + } // If the user can view other users if ($user->rights->user->user->lire) { $moreforfilter.='
    '; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='
    '; } // If the user can view categories of products @@ -385,372 +432,440 @@ if ($resql) $moreforfilter.=''; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; else $moreforfilter = $hookmanager->resPrint; - if (! empty($moreforfilter)) - { - print '
    '; - print $moreforfilter; - print '
    '; - } + if (! empty($moreforfilter)) + { + print '
    '; + print $moreforfilter; + print '
    '; + } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $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"; + print '
    '; + print '
    '."\n"; - print ''; - if (! empty($arrayfields['c.ref']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.ref_customer']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.ref_supplier']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) print ''; - // Zip - if (! empty($arrayfields['s.zip']['checked'])) print ''; - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print ''; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - } - // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - } - if (! empty($arrayfields['sale_representative']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.date_contrat']['checked'])) - { - // Date contract - print ''; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['c.datec']['checked'])) - { - print ''; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print ''; - } - // Status - if (! empty($arrayfields['status']['checked'])) - { - print ''; - } - print ''; - print "\n"; + print ''; + if (! empty($arrayfields['c.ref']['checked'])) + { + print ''; + } + if (! empty($arrayfields['c.ref_customer']['checked'])) + { + print ''; + } + if (! empty($arrayfields['c.ref_supplier']['checked'])) + { + print ''; + } + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + } + if (! empty($arrayfields['s.email']['checked'])) + { + print ''; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) print ''; + // Zip + if (! empty($arrayfields['s.zip']['checked'])) print ''; + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print ''; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + } + // Company type + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + } + if (! empty($arrayfields['sale_representative']['checked'])) + { + print ''; + } + if (! empty($arrayfields['c.date_contrat']['checked'])) + { + // Date contract + print ''; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['c.datec']['checked'])) + { + print ''; + } + // Date modification + if (! empty($arrayfields['c.tms']['checked'])) + { + print ''; + } + // First end date + if (! empty($arrayfields['lower_planned_end_date']['checked'])) + { + print ''; + } + // Status + if (! empty($arrayfields['status']['checked'])) + { + print ''; + } + print ''; + print "\n"; - print ''; - if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom","","$param",'',$sortfield,$sortorder); + print ''; + if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email","","$param",'',$sortfield,$sortorder); if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat","","$param",'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat","","$param",'align="center"',$sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'],$_SERVER["PHP_SELF"],"c.date_creation","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'],$_SERVER["PHP_SELF"],"c.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['status']['checked'])) - { - print_liste_field_titre($staticcontratligne->LibStatut(0,3), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(4,3,0), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(4,3,1), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(5,3), '', '', '', '', 'width="16"'); - } + if (! empty($arrayfields['lower_planned_end_date']['checked'])) print_liste_field_titre($arrayfields['lower_planned_end_date']['label'],$_SERVER["PHP_SELF"],"lower_planned_end_date","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['status']['checked'])) + { + print_liste_field_titre($staticcontratligne->LibStatut(0,3), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(4,3,0), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(4,3,1), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(5,3), '', '', '', '', 'width="16"'); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; + print "\n"; - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); - $contracttmp->ref=$obj->ref; - $contracttmp->id=$obj->rowid; - $contracttmp->ref_customer=$obj->ref_customer; - $contracttmp->ref_supplier=$obj->ref_supplier; + $contracttmp->ref=$obj->ref; + $contracttmp->id=$obj->rowid; + $contracttmp->ref_customer=$obj->ref_customer; + $contracttmp->ref_supplier=$obj->ref_supplier; - print ''; - if (! empty($arrayfields['c.ref']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.ref_customer']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.ref_supplier']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['sale_representative']['checked'])) - { - // Sales representatives - print ''; - } - // Date - if (! empty($arrayfields['c.date_contrat']['checked'])) - { - print ''; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['c.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['status']['checked'])) - { - print ''; - print ''; - print ''; - print ''; - } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + if ($obj->socid > 0) + { + $result=$socstatic->fetch($obj->socid); + } - print "\n"; - $i++; - } - $db->free($resql); + print ''; + if (! empty($arrayfields['c.ref']['checked'])) + { + print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; - //print $langs->trans('Month').': '; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - //print ' '.$langs->trans('Year').': '; - $syear = $year; - $formother->select_year($syear,'year',1, 20, 5); - 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 ''; - $searchpicto=$form->showFilterButtons(); - print $searchpicto; - print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; + //print $langs->trans('Month').': '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + //print ' '.$langs->trans('Year').': '; + $syear = $year; + $formother->select_year($syear,'year',1, 20, 5); + 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 ''; + $arrayofoperators=array('<'=>'<','>'=>'>'); + print $form->selectarray('search_op2df',$arrayofoperators,$search_op2df,0); + print '
    '; + print $formother->select_month($search_dfmonth, 'search_dfmonth', 1); + print ' '; + $formother->select_year($search_dfyear, 'search_dfyear', 1, 20, 5); + print '
    '; + $searchpicto=$form->showFilterButtons(); + print $searchpicto; + print '
    '; - print $contracttmp->getNomUrl(1); - if ($obj->nb_late) print img_warning($langs->trans("Late")); - if (!empty($obj->note_private) || !empty($obj->note_public)) - { - print ' '; - print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; - print ''; - } - print ''.$obj->ref_customer.''.$obj->ref_supplier.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''; - print $obj->town; - print ''; - print $obj->zip; - print '".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; - if ($obj->socid > 0) - { - $result=$socstatic->fetch($obj->socid); - $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); - if ($listsalesrepresentatives < 0) dol_print_error($db); - $nbofsalesrepresentative=count($listsalesrepresentatives); - if ($nbofsalesrepresentative > 3) // We print only number - { - print ''; - print $nbofsalesrepresentative; - print ''; - } - else if ($nbofsalesrepresentative > 0) - { - $userstatic=new User($db); - $j=0; - foreach($listsalesrepresentatives as $val) - { - $userstatic->id=$val['id']; - $userstatic->lastname=$val['lastname']; - $userstatic->firstname=$val['firstname']; - print '
    '.$userstatic->getNomUrl(1); - $j++; - if ($j < $nbofsalesrepresentative) print ', '; - print '
    '; - } - } - //else print $langs->trans("NoSalesRepresentativeAffected"); - } - else - { - print ' '; - } - print '
    '.dol_print_date($db->jdate($obj->date_contrat), 'day').''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.($obj->nb_initial>0?$obj->nb_initial:'').''.($obj->nb_running>0?$obj->nb_running:'').''.($obj->nb_expired>0?$obj->nb_expired:'').''.($obj->nb_closed>0 ?$obj->nb_closed:'').''; - 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 $contracttmp->getNomUrl(1); + if ($obj->nb_late) print img_warning($langs->trans("Late")); + if (!empty($obj->note_private) || !empty($obj->note_public)) + { + print ' '; + print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; + print ''; + } - print '
    '; - print '
    '; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->contrat->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($contracttmp->element, $filename, $filedir); + print '
    '.$obj->ref_customer.''.$obj->ref_supplier.''; + //print ''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''; + if ($obj->socid > 0) + { + print $socstatic->getNomUrl(1, ''); + } + print ''.$obj->email.''; + print $obj->town; + print ''; + print $obj->zip; + print '".$obj->state_name."'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; + if ($obj->socid > 0) + { + $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); + if ($listsalesrepresentatives < 0) dol_print_error($db); + $nbofsalesrepresentative=count($listsalesrepresentatives); + if ($nbofsalesrepresentative > 3) // We print only number + { + print ''; + print $nbofsalesrepresentative; + print ''; + } + else if ($nbofsalesrepresentative > 0) + { + $userstatic=new User($db); + $j=0; + foreach($listsalesrepresentatives as $val) + { + $userstatic->id=$val['id']; + $userstatic->lastname=$val['lastname']; + $userstatic->firstname=$val['firstname']; + print '
    '.$userstatic->getNomUrl(1); + $j++; + if ($j < $nbofsalesrepresentative) print ', '; + print '
    '; + } + } + //else print $langs->trans("NoSalesRepresentativeAffected"); + } + else + { + print ' '; + } + print '
    '.dol_print_date($db->jdate($obj->date_contrat), 'day').''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day'); + print ''.($obj->nb_initial>0?$obj->nb_initial:'').''.($obj->nb_running>0?$obj->nb_running:'').''.($obj->nb_expired>0?$obj->nb_expired:'').''.($obj->nb_closed>0 ?$obj->nb_closed:'').''; + 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 ''; + + print ''; + + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + /* + * Show list of available documents + */ + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); + + $filedir=$diroutputmassaction; + $genallowed=$user->rights->contrat->lire; + $delallowed=$user->rights->contrat->lire; + + print $formfile->showdocuments('massfilesarea_contract','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '
    '.$langs->trans("ShowTempMassFilesArea").''; + } } else { - dol_print_error($db); + dol_print_error($db); } diff --git a/htdocs/contrat/note.php b/htdocs/contrat/note.php index 7d4927d19b8..ff0df34de67 100644 --- a/htdocs/contrat/note.php +++ b/htdocs/contrat/note.php @@ -74,7 +74,7 @@ if ($id > 0 || ! empty($ref)) // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref=''; @@ -139,7 +139,7 @@ if ($id > 0 || ! empty($ref)) print ''; - + // Ligne info remises tiers print ''; print "
    '.$langs->trans('Discount').''; if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); @@ -161,9 +161,9 @@ if ($id > 0 || ! empty($ref)) print '
    "; - + print ''; - + //print '
    '; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; diff --git a/htdocs/contrat/services.php b/htdocs/contrat/services_list.php similarity index 69% rename from htdocs/contrat/services.php rename to htdocs/contrat/services_list.php index 2662f6f33f4..c25311b84da 100644 --- a/htdocs/contrat/services.php +++ b/htdocs/contrat/services_list.php @@ -19,7 +19,7 @@ */ /** - * \file htdocs/contrat/services.php + * \file htdocs/contrat/services_list.php * \ingroup contrat * \brief Page to list services in contracts */ @@ -92,20 +92,20 @@ $result = restrictedArea($user, 'contrat',$contratid); if ($search_status != '') { - $tmp=explode('&', $search_status); - $mode=$tmp[0]; - if (empty($tmp[1])) $filter=''; - else - { - if ($tmp[1] == 'filter=notexpired') $filter='notexpired'; - if ($tmp[1] == 'filter=expired') $filter='expired'; - } + $tmp=explode('&', $search_status); + $mode=$tmp[0]; + if (empty($tmp[1])) $filter=''; + else + { + if ($tmp[1] == 'filter=notexpired') $filter='notexpired'; + if ($tmp[1] == 'filter=expired') $filter='expired'; + } } else { - $search_status = $mode; - if ($filter == 'expired') $search_status.='&filter=expired'; - if ($filter == 'notexpired') $search_status.='&filter=notexpired'; + $search_status = $mode; + if ($filter == 'expired') $search_status.='&filter=expired'; + if ($filter == 'notexpired') $search_status.='&filter=notexpired'; } $staticcontrat=new Contrat($db); @@ -113,29 +113,29 @@ $staticcontratligne=new ContratLigne($db); $companystatic=new Societe($db); $arrayfields=array( - 'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80), - 'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80), + 'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80), + 'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80), 'cd.qty'=>array('label'=>$langs->trans("Qty"), 'checked'=>0, 'position'=>100), 'cd.total_ht'=>array('label'=>$langs->trans("TotalHT"), 'checked'=>0, 'position'=>100), 'cd.total_tva'=>array('label'=>$langs->trans("TotalVAT"), 'checked'=>0, 'position'=>100), 'cd.tva_tx'=>array('label'=>$langs->trans("VAT"), 'checked'=>0, 'position'=>100), 'cd.subprice'=>array('label'=>$langs->trans("PriceUHT"), 'checked'=>0, 'position'=>100), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>100), - 'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0")), - 'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0)), - 'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5)), - 'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5)), - 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1), - //'cd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>100), + 'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0")), + 'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0)), + 'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5)), + 'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5)), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1), + //'cd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } } @@ -145,8 +145,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -154,37 +154,37 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers + { $search_product_category=0; - $search_name=""; - $search_contract=""; - $search_service=""; - $search_status=-1; - $opouvertureprevuemonth=""; - $opouvertureprevueday=""; - $opouvertureprevueyear=""; - $filter_opouvertureprevue=""; - $op1month=""; - $op1day=""; - $op1year=""; - $filter_op1=""; - $op2month=""; - $op2day=""; - $op2year=""; - $filter_op2=""; - $opcloturemonth=""; - $opclotureday=""; - $opclotureyear=""; - $filter_opcloture=""; - $mode=''; - $filter=''; - $toselect=''; - $search_array_options=array(); - } + $search_name=""; + $search_contract=""; + $search_service=""; + $search_status=-1; + $opouvertureprevuemonth=""; + $opouvertureprevueday=""; + $opouvertureprevueyear=""; + $filter_opouvertureprevue=""; + $op1month=""; + $op1day=""; + $op1year=""; + $filter_op1=""; + $op2month=""; + $op2day=""; + $op2year=""; + $filter_op2=""; + $opcloturemonth=""; + $opclotureday=""; + $opclotureyear=""; + $filter_opcloture=""; + $mode=''; + $filter=''; + $toselect=''; + $search_array_options=array(); + } } @@ -246,24 +246,38 @@ if (! empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $fi if (! empty($filter_op1) && $filter_op1 != -1 && $filter_date1 != '') $sql.= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1)."'"; if (! empty($filter_op2) && $filter_op2 != -1 && $filter_date2 != '') $sql.= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2)."'"; if (! empty($filter_opcloture) && $filter_opcloture != -1 && $filter_datecloture != '') $sql.= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture)."'"; +// Add where from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode_search=0; + if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); + } +} $sql .= $db->order($sortfield,$sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql .= $db->plimit($limit + 1, $offset); //print $sql; -dol_syslog("contrat/services.php", LOG_DEBUG); +dol_syslog("contrat/services_list.php", LOG_DEBUG); $resql=$db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -280,7 +294,7 @@ if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && llxHeader(null, $langs->trans("Services")); $param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($search_contract) $param.='&search_contract='.urlencode($search_contract); if ($search_name) $param.='&search_name='.urlencode($search_name); @@ -299,15 +313,15 @@ if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->contrat->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); //if ($massaction == 'presend') $arrayofmassactions=array(); @@ -321,6 +335,7 @@ print ''; print ''; print ''; print ''; +print ''; $title=$langs->trans("ListOfServices"); if ($mode == "0") $title=$langs->trans("ListOfInactiveServices"); // Must use == "0" @@ -331,8 +346,8 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } $morefilter = ''; @@ -340,12 +355,12 @@ $morefilter = ''; // If the user can view categories of products if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { - include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='
    '; + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); + $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); + $moreforfilter.='
    '; } $parameters=array(); @@ -356,9 +371,9 @@ else $moreforfilter = $hookmanager->resPrint; if (! empty($moreforfilter)) { - print '
    '; - print $moreforfilter; - print '
    '; + print '
    '; + print $moreforfilter; + print '
    '; } $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; @@ -384,16 +399,16 @@ if (! empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -417,7 +432,7 @@ if (! empty($arrayfields['c.ref']['checked'])) // Service label if (! empty($arrayfields['p.description']['checked'])) { - print '
    '; + print ''; print ''; print ''; + print ''; print ''; print ''; - $arrayofoperators=array('<'=>'<','>'=>'>'); + $arrayofoperators=array('<'=>'<','>'=>'>'); print $form->selectarray('filter_opouvertureprevue',$arrayofoperators,$filter_opouvertureprevue,1); print ' '; $filter_dateouvertureprevue=dol_mktime(0,0,0,$opouvertureprevuemonth,$opouvertureprevueday,$opouvertureprevueyear); @@ -469,7 +484,7 @@ if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) if (! empty($arrayfields['cd.date_ouverture']['checked'])) { print ''; - $arrayofoperators=array('<'=>'<','>'=>'>'); + $arrayofoperators=array('<'=>'<','>'=>'>'); print $form->selectarray('filter_op1',$arrayofoperators,$filter_op1,1); print ' '; $filter_date1=dol_mktime(0,0,0,$op1month,$op1day,$op1year); @@ -488,36 +503,41 @@ if (! empty($arrayfields['cd.date_fin_validite']['checked'])) } if (! empty($arrayfields['cd.date_cloture']['checked'])) { - print ''; - $arrayofoperators=array('<'=>'<','>'=>'>'); - print $form->selectarray('filter_opcloture',$arrayofoperators,$filter_opcloture,1); - print ' '; - $filter_date_cloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear); - print $form->select_date($filter_date_cloture,'opcloture',0,0,1,'',1,0,1); - print ''; + $arrayofoperators=array('<'=>'<','>'=>'>'); + print $form->selectarray('filter_opcloture',$arrayofoperators,$filter_opcloture,1); + print ' '; + $filter_date_cloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear); + print $form->select_date($filter_date_cloture,'opcloture',0,0,1,'',1,0,1); + 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 ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + { + $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 ''; + } + else + { + // for the type as 'checkbox', 'chkbxlst', 'sellist' we should use code instead of id (example: I declare a 'chkbxlst' to have a link with dictionnairy, I have to extend it with the 'code' instead 'rowid') + echo $extrafields->showInputField($key, $search_array_options['search_options_'.$key], '', '', 'search_'); + } + print ''; - print ''; + print ''; - print ''; + print ''; + // Status + print ''; $arrayofstatus=array( - '0'=>$langs->trans("ServiceStatusInitial"), - '4'=>$langs->trans("ServiceStatusRunning"), - '4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"), - '4&filter=expired'=>$langs->trans("ServiceStatusLate"), - '5'=>$langs->trans("ServiceStatusClosed") + '0'=>$langs->trans("ServiceStatusInitial"), + '4'=>$langs->trans("ServiceStatusRunning"), + '4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"), + '4&filter=expired'=>$langs->trans("ServiceStatusLate"), + '5'=>$langs->trans("ServiceStatusClosed") ); print $form->selectarray('search_status', $arrayofstatus, (strstr($search_status, ',')?-1:$search_status), 1, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone'); print '
    '; + if (! empty($arrayfields['c.ref']['checked'])) + { + print ''; print $contractstatic->getNomUrl(1,16); print ''; + if (! empty($arrayfields['p.description']['checked'])) + { + print ''; if ($obj->pid) { $productstatic->id=$obj->pid; @@ -588,8 +608,8 @@ while ($i < min($num,$limit)) $productstatic->ref=$obj->pref; $productstatic->entity=$obj->pentity; print $productstatic->getNomUrl(1,'',24); - print $obj->label?' - '.dol_trunc($obj->label,16):''; - if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '
    '.dol_nl2br($obj->description); + print $obj->label?' - '.dol_trunc($obj->label,16):''; + if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '
    '.dol_nl2br($obj->description); } else { @@ -597,54 +617,54 @@ while ($i < min($num,$limit)) if ($obj->type == 1) print img_object($obj->description,'service').' '.dol_trunc($obj->description,24); } print '
    '; - print $obj->qty; - print ''; - print price($obj->total_ht); - print ''; - print price($obj->total_tva); - print ''; - print price2num($obj->tva_tx).'%'; - print ''; - print price($obj->subprice); - print ''; + print $obj->qty; + print ''; + print price($obj->total_ht); + print ''; + print price($obj->total_tva); + print ''; + print price2num($obj->tva_tx).'%'; + print ''; + print price($obj->subprice); + print ''; + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; $companystatic->id=$obj->socid; $companystatic->name=$obj->name; $companystatic->client=1; print $companystatic->getNomUrl(1,'customer',28); print ''; print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue)):' '); if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) @@ -652,45 +672,45 @@ while ($i < min($num,$limit)) else print '    '; print ''.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture)):' ').''.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture)):' ').''.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite)):' '); + if (! empty($arrayfields['cd.date_fin_validite']['checked'])) + { + print ''.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite)):' '); if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) { - $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; - $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); - print img_warning($textlate); + $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; + $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); + print img_warning($textlate); } else print '    '; - print ''.dol_print_date($db->jdate($obj->date_cloture)).''.dol_print_date($db->jdate($obj->date_cloture)).''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; if ($obj->cstatut == 0) // If contract is draft, we say line is also draft { - print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)); + print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)); } else { - print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0); + print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0); } 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 ''; + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; } print '
    '; + print '
    '; - /*print '
    ';*/ + print '
    '; - print dol_escape_htmltag($file); - print '
    '; - // Nb of docs - print ''; - print ''; + /*print '';*/ - // Edit link - print ''; + // Nb of docs + print ''; + print ''; - // Add link - //print ''; - //print ''; + // Edit link + print ''; - // Info - print '"; + // Add link + //print ''; + //print ''; - print "
    '; - print (isset($val['cachenbofdoc']) && $val['cachenbofdoc'] >= 0)?$val['cachenbofdoc']:' '; - print ''; - if ($nbofsubdir > 0 && $nboffilesinsubdir > 0) print '+'.$nboffilesinsubdir.' '; - print ''; + print dol_escape_htmltag($file); + print ''.img_view($langs->trans("Edit").' - '.$langs->trans("View"), 0, 'class="valignmiddle"').''; + print (isset($val['cachenbofdoc']) && $val['cachenbofdoc'] >= 0)?$val['cachenbofdoc']:' '; + print ''; + if ($nbofsubdir > 0 && $nboffilesinsubdir > 0) print '+'.$nboffilesinsubdir.' '; + print ''.img_edit_add().' '.img_view($langs->trans("Edit").' - '.$langs->trans("View"), 0, 'class="valignmiddle"').''; - $userstatic->id=isset($val['fk_user_c'])?$val['fk_user_c']:0; - $userstatic->lastname=isset($val['login_c'])?$val['login_c']:0; - $htmltooltip=''.$langs->trans("ECMSection").': '.$val['label'].'
    '; - $htmltooltip=''.$langs->trans("Type").': '.$langs->trans("ECMSectionManual").'
    '; - $htmltooltip.=''.$langs->trans("ECMCreationUser").': '.$userstatic->getNomUrl(1, '', false, 1).'
    '; - $htmltooltip.=''.$langs->trans("ECMCreationDate").': '.(isset($val['date_c'])?dol_print_date($val['date_c'],"dayhour"):$langs->trans("NeedRefresh")).'
    '; - $htmltooltip.=''.$langs->trans("Description").': '.$val['description'].'
    '; - $htmltooltip.=''.$langs->trans("ECMNbOfFilesInDir").': '.((isset($val['cachenbofdoc']) && $val['cachenbofdoc'] >= 0)?$val['cachenbofdoc']:$langs->trans("NeedRefresh")).'
    '; - if ($nboffilesinsubdir > 0) $htmltooltip.=''.$langs->trans("ECMNbOfFilesInSubDir").': '.$nboffilesinsubdir; - else $htmltooltip.=''.$langs->trans("ECMNbOfSubDir").': '.($nbofsubdir >= 0 ? $nbofsubdir : $langs->trans("NeedRefresh")).'
    '; - print $form->textwithpicto('',$htmltooltip,1,"info"); - print "
    '.img_edit_add().' 
    \n"; - print ''; + // Info + if ($modulepart == 'ecm') + { + print '
    '; + $userstatic->id=isset($val['fk_user_c'])?$val['fk_user_c']:0; + $userstatic->lastname=isset($val['login_c'])?$val['login_c']:0; + $htmltooltip=''.$langs->trans("ECMSection").': '.$val['label'].'
    '; + $htmltooltip=''.$langs->trans("Type").': '.$langs->trans("ECMSectionManual").'
    '; + $htmltooltip.=''.$langs->trans("ECMCreationUser").': '.$userstatic->getNomUrl(1, '', false, 1).'
    '; + $htmltooltip.=''.$langs->trans("ECMCreationDate").': '.(isset($val['date_c'])?dol_print_date($val['date_c'],"dayhour"):$langs->trans("NeedRefresh")).'
    '; + $htmltooltip.=''.$langs->trans("Description").': '.$val['description'].'
    '; + $htmltooltip.=''.$langs->trans("ECMNbOfFilesInDir").': '.((isset($val['cachenbofdoc']) && $val['cachenbofdoc'] >= 0)?$val['cachenbofdoc']:$langs->trans("NeedRefresh")).'
    '; + if ($nboffilesinsubdir > 0) $htmltooltip.=''.$langs->trans("ECMNbOfFilesInSubDir").': '.$nboffilesinsubdir; + else $htmltooltip.=''.$langs->trans("ECMNbOfSubDir").': '.($nbofsubdir >= 0 ? $nbofsubdir : $langs->trans("NeedRefresh")).'
    '; + print $form->textwithpicto('',$htmltooltip,1,"info"); + print "
    \n"; + print '
    '; - // Enable jquery handlers on new generated HTML objects - print ''; + //print '
     
    '; + print "\n"; + } + } - echo "\n"; + // Enable jquery handlers on new generated HTML objects + print "\n\n"; + print ''; + + echo "\n"; + + } + } + else print "PermissionDenied"; + } + + // This ajax service is called only when a directory $selecteddir is opened but not when closed. + //print ''; } -// This ajax service is called only when a directory $selecteddir is opened but not when closed. -//print ''; -if (is_object($db)) $db->close(); +if (empty($conf->use_javascript_ajax) || ! empty($conf->global->MAIN_ECM_DISABLE_JS)) +{ + print '
      '; + + // Load full tree from database. We will use it to define nbofsubdir and nboffilesinsubdir + if (empty($sqltree)) $sqltree=$ecmdirstatic->get_full_arbo(0); // Slow + + // ----- This section will show a tree from a fulltree array ----- + // $section must also be defined + // ---------------------------------------------------------------- + + // Define fullpathselected ( _x_y_z ) of $section parameter (!! not into ajaxdirtree) + $fullpathselected=''; + foreach($sqltree as $key => $val) + { + //print $val['id']."-".$section."
      "; + if ($val['id'] == $section) + { + $fullpathselected=$val['fullpath']; + break; + } + } + //print "fullpathselected=".$fullpathselected."
      "; + + // Update expandedsectionarray in session + $expandedsectionarray=array(); + if (isset($_SESSION['dol_ecmexpandedsectionarray'])) $expandedsectionarray=explode(',',$_SESSION['dol_ecmexpandedsectionarray']); + + if ($section && GETPOST('sectionexpand') == 'true') + { + // We add all sections that are parent of opened section + $pathtosection=explode('_',$fullpathselected); + foreach($pathtosection as $idcursor) + { + if ($idcursor && ! in_array($idcursor,$expandedsectionarray)) // Not already in array + { + $expandedsectionarray[]=$idcursor; + } + } + $_SESSION['dol_ecmexpandedsectionarray']=join(',',$expandedsectionarray); + } + if ($section && GETPOST('sectionexpand') == 'false') + { + // We removed all expanded sections that are child of the closed section + $oldexpandedsectionarray=$expandedsectionarray; + $expandedsectionarray=array(); // Reset + foreach($oldexpandedsectionarray as $sectioncursor) + { + // TODO is_in_subtree(fulltree,sectionparent,sectionchild) does nox exists. Enable or remove this... + //if ($sectioncursor && ! is_in_subtree($sqltree,$section,$sectioncursor)) $expandedsectionarray[]=$sectioncursor; + } + $_SESSION['dol_ecmexpandedsectionarray']=join(',',$expandedsectionarray); + } + //print $_SESSION['dol_ecmexpandedsectionarray'].'
      '; + + $nbofentries=0; + $oldvallevel=0; + $var=true; + foreach($sqltree as $key => $val) + { + $var=false; + + $ecmdirstatic->id=$val['id']; + $ecmdirstatic->ref=$val['label']; + + // Refresh cache + if (preg_match('/refresh/i',$action)) + { + $result=$ecmdirstatic->fetch($val['id']); + $ecmdirstatic->ref=$ecmdirstatic->label; + + $result=$ecmdirstatic->refreshcachenboffile(0); + $val['cachenbofdoc']=$result; + } + + //$fullpathparent=preg_replace('/(_[^_]+)$/i','',$val['fullpath']); + + // Define showline + $showline=0; + + // If directory is son of expanded directory, we show line + if (in_array($val['id_mere'],$expandedsectionarray)) $showline=4; + // If directory is brother of selected directory, we show line + elseif ($val['id'] != $section && $val['id_mere'] == $ecmdirstatic->motherof[$section]) $showline=3; + // If directory is parent of selected directory or is selected directory, we show line + elseif (preg_match('/'.$val['fullpath'].'_/i',$fullpathselected.'_')) $showline=2; + // If we are level one we show line + elseif ($val['level'] < 2) $showline=1; + + if ($showline) + { + if (in_array($val['id'],$expandedsectionarray)) $option='indexexpanded'; + else $option='indexnotexpanded'; + //print $option; + + print '\n"; + } + + $oldvallevel=$val['level']; + $nbofentries++; + } + + // If nothing to show + if ($nbofentries == 0) + { + print '\n"; + } + + print '
    '; +} + + +// Close db if mode is not noajax +if ((! isset($mode) || $mode != 'noajax') && is_object($db)) $db->close(); diff --git a/htdocs/core/ajax/bankconciliate.php b/htdocs/core/ajax/bankconciliate.php index 65620c5429c..e5bfb674e8f 100644 --- a/htdocs/core/ajax/bankconciliate.php +++ b/htdocs/core/ajax/bankconciliate.php @@ -71,3 +71,27 @@ if (($user->rights->banque->modifier || $user->rights->banque->consolidate) && $ exit; } +if (($user->rights->banque->modifier || $user->rights->banque->consolidate) && $action == 'donext') +{ + // Increase date + $al = new AccountLine($db); + $al->dateo_next(GETPOST('rowid','int')); + $al->fetch(GETPOST('rowid','int')); + + print ''.dol_print_date($db->jdate($al->dateo),"day").''; + + exit; +} + +if (($user->rights->banque->modifier || $user->rights->banque->consolidate) && $action == 'doprev') +{ + // Decrease date + $al =new AccountLine($db); + $al->dateo_previous(GETPOST('rowid','int')); + $al->fetch(GETPOST('rowid','int')); + + print ''.dol_print_date($db->jdate($al->dateo),"day").''; + + exit; +} + diff --git a/htdocs/core/ajax/getaccountcurrency.php b/htdocs/core/ajax/getaccountcurrency.php new file mode 100644 index 00000000000..40e52672c0e --- /dev/null +++ b/htdocs/core/ajax/getaccountcurrency.php @@ -0,0 +1,60 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/ajax/vatrates.php + * \brief File to load vat rates combobox + */ + +if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal +if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); +if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); + +require '../../main.inc.php'; + +$id = GETPOST('id','int'); + +/* + * View + */ + +top_httphead(); + +//print ''."\n"; + +// Load original field value +if (! empty($id)) +{ + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + $account=new Account($db); + $result = $account->fetch($id); + if ($result<0) { + $return['value'] = ''; + $return['num'] = $result; + $return['error'] = $account->errors[0]; + } else { + $return['value'] = $account->currency_code; + $return['num'] = $result; + $return['error'] = ''; + } + + echo json_encode($return); +} + diff --git a/htdocs/core/ajax/selectobject.php b/htdocs/core/ajax/selectobject.php new file mode 100644 index 00000000000..0c52c490512 --- /dev/null +++ b/htdocs/core/ajax/selectobject.php @@ -0,0 +1,86 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/ajax/selectobject.php + * \brief File to return Ajax response on a selection list request + */ + +if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal +if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); +if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); +if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); +if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); +if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); + +require '../../main.inc.php'; + +$objectdesc=GETPOST('objectdesc', 'alpha'); +$htmlname=GETPOST('htmlname', 'aZ09'); +$sqlfilter=GETPOST('sqlfilter', 'alpha'); +$outjson=(GETPOST('outjson', 'int') ? GETPOST('outjson', 'int') : 0); +$action=GETPOST('action', 'alpha'); +$id=GETPOST('id', 'int'); + + +/* + * View + */ + +//print ''."\n"; + +dol_syslog(join(',', $_GET)); +//print_r($_GET); + + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; +$form = new Form($db); + +//$langs->load("companies"); + +top_httphead(); + +if (empty($htmlname)) return; + + +$InfoFieldList = explode(":", $objectdesc); +$classname=$InfoFieldList[0]; +$classpath=$InfoFieldList[1]; +if (! empty($classpath)) +{ + dol_include_once($classpath); + if ($classname && class_exists($classname)) + { + $objecttmp = new $classname($db); + } +} +if (! is_object($objecttmp)) +{ + dol_syslog('Error bad param objectdesc', LOG_WARNING); + print 'Error bad param objectdesc'; +} + +// When used from jQuery, the search term is added as GET param "term". +$searchkey=(($id && GETPOST($id, 'alpha'))?GETPOST($id, 'alpha'):(($htmlname && GETPOST($htmlname, 'alpha'))?GETPOST($htmlname, 'alpha'):'')); + +// TODO Add a security test to avoid to get content of all tables + +$arrayresult=$form->selectForFormsList($objecttmp, $htmlname, '', 0, $searchkey, '', '', '', 0, 1); + +$db->close(); + +if ($outjson) print json_encode($arrayresult); diff --git a/htdocs/core/ajax/selectsearchbox.php b/htdocs/core/ajax/selectsearchbox.php index 2d92bc8f938..0861ef160b6 100644 --- a/htdocs/core/ajax/selectsearchbox.php +++ b/htdocs/core/ajax/selectsearchbox.php @@ -49,92 +49,92 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; //global $hookmanager; $hookmanager->initHooks(array('searchform')); -$search_boxvalue=GETPOST('q'); +$search_boxvalue=GETPOST('q', 'none'); $arrayresult=array(); // Define $searchform if ((( ! empty($conf->societe->enabled) && (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))) || ! empty($conf->fournisseur->enabled)) && empty($conf->global->MAIN_SEARCHFORM_SOCIETE_DISABLED) && $user->rights->societe->lire) { - $arrayresult['searchintothirdparty']=array('img'=>'object_company', 'label'=>$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'text'=>img_picto('','object_company').' '.$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/societe/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintothirdparty']=array('position'=>10, 'shortcut'=>'T', 'img'=>'object_company', 'label'=>$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'text'=>img_picto('','object_company').' '.$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/societe/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->societe->enabled) && empty($conf->global->MAIN_SEARCHFORM_CONTACT_DISABLED) && $user->rights->societe->lire) { - $arrayresult['searchintocontact']=array('img'=>'object_contact', 'label'=>$langs->trans("SearchIntoContacts", $search_boxvalue), 'text'=>img_picto('','object_contact').' '.$langs->trans("SearchIntoContacts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contact/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintocontact']=array('position'=>15, 'shortcut'=>'A', 'img'=>'object_contact', 'label'=>$langs->trans("SearchIntoContacts", $search_boxvalue), 'text'=>img_picto('','object_contact').' '.$langs->trans("SearchIntoContacts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contact/list.php?sall='.urlencode($search_boxvalue)); +} + +if (! empty($conf->adherent->enabled) && empty($conf->global->MAIN_SEARCHFORM_ADHERENT_DISABLED) && $user->rights->adherent->lire) +{ + $arrayresult['searchintomember']=array('position'=>20, 'shortcut'=>'M', 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoMembers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoMembers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/adherents/list.php?sall='.urlencode($search_boxvalue)); } if (((! empty($conf->product->enabled) && $user->rights->produit->lire) || (! empty($conf->service->enabled) && $user->rights->service->lire)) && empty($conf->global->MAIN_SEARCHFORM_PRODUITSERVICE_DISABLED)) { - $arrayresult['searchintoproduct']=array('img'=>'object_product', 'label'=>$langs->trans("SearchIntoProductsOrServices", $search_boxvalue),'text'=>img_picto('','object_product').' '.$langs->trans("SearchIntoProductsOrServices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/product/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoproduct']=array('position'=>30, 'shortcut'=>'P', 'img'=>'object_product', 'label'=>$langs->trans("SearchIntoProductsOrServices", $search_boxvalue),'text'=>img_picto('','object_product').' '.$langs->trans("SearchIntoProductsOrServices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/product/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->projet->enabled) && empty($conf->global->MAIN_SEARCHFORM_PROJECT_DISABLED) && $user->rights->projet->lire) { - $arrayresult['searchintoprojects']=array('img'=>'object_projectpub', 'label'=>$langs->trans("SearchIntoProjects", $search_boxvalue), 'text'=>img_picto('','object_projectpub').' '.$langs->trans("SearchIntoProjects", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/list.php?search_all='.urlencode($search_boxvalue)); + $arrayresult['searchintoprojects']=array('position'=>40, 'shortcut'=>'Q', 'img'=>'object_projectpub', 'label'=>$langs->trans("SearchIntoProjects", $search_boxvalue), 'text'=>img_picto('','object_projectpub').' '.$langs->trans("SearchIntoProjects", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/list.php?search_all='.urlencode($search_boxvalue)); } if (! empty($conf->projet->enabled) && empty($conf->global->MAIN_SEARCHFORM_TASK_DISABLED) && $user->rights->projet->lire) { - $arrayresult['searchintotasks']=array('img'=>'object_task', 'label'=>$langs->trans("SearchIntoTasks", $search_boxvalue), 'text'=>img_picto('','object_task').' '.$langs->trans("SearchIntoTasks", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/tasks/list.php?search_all='.urlencode($search_boxvalue)); -} - -if (! empty($conf->adherent->enabled) && empty($conf->global->MAIN_SEARCHFORM_ADHERENT_DISABLED) && $user->rights->adherent->lire) -{ - $arrayresult['searchintomember']=array('img'=>'object_user', 'label'=>$langs->trans("SearchIntoMembers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoMembers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/adherents/list.php?sall='.urlencode($search_boxvalue)); -} - -if (! empty($conf->user->enabled) && empty($conf->global->MAIN_SEARCHFORM_USER_DISABLED) && $user->rights->user->user->lire) -{ - $arrayresult['searchintouser']=array('img'=>'object_user', 'label'=>$langs->trans("SearchIntoUsers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoUsers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/user/index.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintotasks']=array('position'=>45, 'img'=>'object_task', 'label'=>$langs->trans("SearchIntoTasks", $search_boxvalue), 'text'=>img_picto('','object_task').' '.$langs->trans("SearchIntoTasks", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/tasks/list.php?search_all='.urlencode($search_boxvalue)); } if (! empty($conf->propal->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_PROPAL_DISABLED) && $user->rights->propal->lire) { - $arrayresult['searchintopropal']=array('img'=>'object_propal', 'label'=>$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/comm/propal/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintopropal']=array('position'=>60, 'img'=>'object_propal', 'label'=>$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/comm/propal/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->commande->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_ORDER_DISABLED) && $user->rights->commande->lire) { - $arrayresult['searchintoorder']=array('img'=>'object_order', 'label'=>$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/commande/list.php?sall='.urlencode($search_boxvalue)); -} -if (! empty($conf->facture->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_INVOICE_DISABLED) && $user->rights->facture->lire) -{ - $arrayresult['searchintoinvoice']=array('img'=>'object_bill', 'label'=>$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/compta/facture/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoorder']=array('position'=>70, 'img'=>'object_order', 'label'=>$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/commande/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->expedition->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_SHIPMENT_DISABLED) && $user->rights->expedition->lire) { - $arrayresult['searchintoshipment']=array('img'=>'object_sending', 'label'=>$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'text'=>img_picto('','object_sending').' '.$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expedition/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoshipment']=array('position'=>80, 'img'=>'object_sending', 'label'=>$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'text'=>img_picto('','object_sending').' '.$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expedition/list.php?sall='.urlencode($search_boxvalue)); +} +if (! empty($conf->facture->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_INVOICE_DISABLED) && $user->rights->facture->lire) +{ + $arrayresult['searchintoinvoice']=array('position'=>90, 'img'=>'object_bill', 'label'=>$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/compta/facture/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->supplier_proposal->enabled) && empty($conf->global->MAIN_SEARCHFORM_SUPPLIER_PROPAL_DISABLED) && $user->rights->supplier_proposal->lire) { - $arrayresult['searchintosupplierpropal']=array('img'=>'object_propal', 'label'=>$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/supplier_proposal/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintosupplierpropal']=array('position'=>100, 'img'=>'object_propal', 'label'=>$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/supplier_proposal/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_SEARCHFORM_SUPPLIER_ORDER_DISABLED) && $user->rights->fournisseur->commande->lire) { - $arrayresult['searchintosupplierorder']=array('img'=>'object_order', 'label'=>$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/commande/list.php?search_all='.urlencode($search_boxvalue)); + $arrayresult['searchintosupplierorder']=array('position'=>110, 'img'=>'object_order', 'label'=>$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/commande/list.php?search_all='.urlencode($search_boxvalue)); } if (! empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_SEARCHFORM_SUPPLIER_INVOICE_DISABLED) && $user->rights->fournisseur->facture->lire) { - $arrayresult['searchintosupplierinvoice']=array('img'=>'object_bill', 'label'=>$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/facture/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintosupplierinvoice']=array('position'=>120, 'img'=>'object_bill', 'label'=>$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/facture/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->contrat->enabled) && empty($conf->global->MAIN_SEARCHFORM_CONTRACT_DISABLED) && $user->rights->contrat->lire) { - $arrayresult['searchintocontract']=array('img'=>'object_contract', 'label'=>$langs->trans("SearchIntoContracts", $search_boxvalue), 'text'=>img_picto('','object_contract').' '.$langs->trans("SearchIntoContracts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contrat/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintocontract']=array('position'=>130, 'img'=>'object_contract', 'label'=>$langs->trans("SearchIntoContracts", $search_boxvalue), 'text'=>img_picto('','object_contract').' '.$langs->trans("SearchIntoContracts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contrat/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->ficheinter->enabled) && empty($conf->global->MAIN_SEARCHFORM_FICHINTER_DISABLED) && $user->rights->ficheinter->lire) { - $arrayresult['searchintointervention']=array('img'=>'object_intervention', 'label'=>$langs->trans("SearchIntoInterventions", $search_boxvalue), 'text'=>img_picto('','object_intervention').' '.$langs->trans("SearchIntoInterventions", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fichinter/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintointervention']=array('position'=>140, 'img'=>'object_intervention', 'label'=>$langs->trans("SearchIntoInterventions", $search_boxvalue), 'text'=>img_picto('','object_intervention').' '.$langs->trans("SearchIntoInterventions", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fichinter/list.php?sall='.urlencode($search_boxvalue)); } + // HR +if (! empty($conf->user->enabled) && empty($conf->global->MAIN_SEARCHFORM_USER_DISABLED) && $user->rights->user->user->lire) +{ + $arrayresult['searchintouser']=array('position'=>200, 'shortcut'=>'U', 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoUsers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoUsers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/user/index.php?sall='.urlencode($search_boxvalue)); +} if (! empty($conf->expensereport->enabled) && empty($conf->global->MAIN_SEARCHFORM_EXPENSEREPORT_DISABLED) && $user->rights->expensereport->lire) { - $arrayresult['searchintoexpensereport']=array('img'=>'object_trip', 'label'=>$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'text'=>img_picto('','object_trip').' '.$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoexpensereport']=array('position'=>210, 'img'=>'object_trip', 'label'=>$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'text'=>img_picto('','object_trip').' '.$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); } if (! empty($conf->holiday->enabled) && empty($conf->global->MAIN_SEARCHFORM_HOLIDAY_DISABLED) && $user->rights->holiday->read) { - $arrayresult['searchintoleaves']=array('img'=>'object_holiday', 'label'=>$langs->trans("SearchIntoLeaves", $search_boxvalue), 'text'=>img_picto('','object_holiday').' '.$langs->trans("SearchIntoLeaves", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/holiday/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoleaves']=array('position'=>220, 'img'=>'object_holiday', 'label'=>$langs->trans("SearchIntoLeaves", $search_boxvalue), 'text'=>img_picto('','object_holiday').' '.$langs->trans("SearchIntoLeaves", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/holiday/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); } @@ -147,7 +147,7 @@ if (! empty($conf->hrm->enabled) && ! empty($conf->global->MAIN_SEARCHFORM_EMPLO */ // Execute hook addSearchEntry -$parameters=array('search_boxvalue'=>$search_boxvalue); +$parameters=array('search_boxvalue'=>$search_boxvalue, 'arrayresult'=>$arrayresult); $reshook=$hookmanager->executeHooks('addSearchEntry',$parameters); if (empty($reshook)) { @@ -155,6 +155,8 @@ if (empty($reshook)) } else $arrayresult=$hookmanager->resArray; +// Sort on position +$arrayresult = dol_sort_array($arrayresult, 'position'); // Print output if called by ajax or do nothing (var $arrayresult will be used) if called by an include if (! isset($usedbyinclude) || empty($usedbyinclude)) diff --git a/htdocs/core/boxes/box_activity.php b/htdocs/core/boxes/box_activity.php index 71a9a4e3125..d3059daba53 100644 --- a/htdocs/core/boxes/box_activity.php +++ b/htdocs/core/boxes/box_activity.php @@ -435,7 +435,7 @@ class box_activity extends ModeleBoxes } // Add the sum in the bottom of the boxes - $this->info_box_contents[$line][0] = array('tr' => 'class="liste_total"'); + $this->info_box_contents[$line][0] = array('tr' => 'class="liste_total_wrap"'); $this->info_box_contents[$line][1] = array('td' => 'align="left" class="liste_total" ', 'text' => $langs->trans("Total")." ".$textHead); $this->info_box_contents[$line][2] = array('td' => 'align="right" class="liste_total" ', 'text' => $totalnb); $this->info_box_contents[$line][3] = array('td' => 'align="right" class="liste_total" ', 'text' => ''); diff --git a/htdocs/core/boxes/box_ficheinter.php b/htdocs/core/boxes/box_ficheinter.php index f62745437a6..c96fb37afe7 100644 --- a/htdocs/core/boxes/box_ficheinter.php +++ b/htdocs/core/boxes/box_ficheinter.php @@ -1,7 +1,7 @@ - * Copyright (C) 2013 Juanjo Menent - * Copyright (C) 2015 Frederic France +/* Copyright (C) 2013 Florian Henry + * Copyright (C) 2013 Juanjo Menent + * Copyright (C) 2015 Frederic France * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -75,7 +75,7 @@ class box_ficheinter extends ModeleBoxes $this->info_box_head = array('text' => $langs->trans("BoxTitleLastFicheInter",$max)); - if ($user->rights->ficheinter->lire) + if (! empty($user->rights->ficheinter->lire)) { $sql = "SELECT f.rowid, f.ref, f.fk_soc, f.fk_statut,"; $sql.= " f.datec,"; diff --git a/htdocs/core/boxes/box_graph_invoices_permonth.php b/htdocs/core/boxes/box_graph_invoices_permonth.php index 639db28637d..677fcc17ad2 100644 --- a/htdocs/core/boxes/box_graph_invoices_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_permonth.php @@ -111,7 +111,7 @@ class box_graph_invoices_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php index ca26f1392a8..d1a6d2d5436 100644 --- a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php @@ -110,7 +110,7 @@ class box_graph_invoices_supplier_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_orders_permonth.php b/htdocs/core/boxes/box_graph_orders_permonth.php index d192805782e..179501e9bf0 100644 --- a/htdocs/core/boxes/box_graph_orders_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_permonth.php @@ -113,7 +113,7 @@ class box_graph_orders_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php index 18b85b2ae80..4979ea6f993 100644 --- a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php @@ -112,7 +112,7 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_propales_permonth.php b/htdocs/core/boxes/box_graph_propales_permonth.php index a0a15cae59a..868ddf60268 100644 --- a/htdocs/core/boxes/box_graph_propales_permonth.php +++ b/htdocs/core/boxes/box_graph_propales_permonth.php @@ -111,7 +111,7 @@ class box_graph_propales_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/modules_boxes.php b/htdocs/core/boxes/modules_boxes.php index 9c496964942..fe919b1fcba 100644 --- a/htdocs/core/boxes/modules_boxes.php +++ b/htdocs/core/boxes/modules_boxes.php @@ -269,7 +269,8 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" $out.= img_picto($langs->trans("MoveBox",$this->box_id),'grip_title','class="boxhandle hideonsmartphone cursormove"'); $out.= img_picto($langs->trans("CloseBox",$this->box_id),'close_title','class="boxclose cursorpointer" rel="x:y" id="imgclose'.$this->box_id.'"'); $label=$head['text']; - if (! empty($head['graph'])) $label.=' ('.$langs->trans("Graph").')'; + //if (! empty($head['graph'])) $label.=' ('.$langs->trans("Graph").')'; + if (! empty($head['graph'])) $label.=' '; $out.= ''; $out.= '
    '; } @@ -286,7 +287,7 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" if (isset($contents[$i])) { // TR - if (isset($contents[$i][0]['tr'])) $out.= ''; + if (isset($contents[$i][0]['tr'])) $out.= ''; else $out.= ''; // Loop on each TD diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 8313894f68c..39487cf6fea 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -116,14 +116,15 @@ class CMailFile $this->sendcontext = $sendcontext; + // Define this->sendmode $this->sendmode = ''; - if ($this->sendcontext == 'emailing') $this->sendmode = $conf->global->EMAILING_MAIL_SENDMODE; + if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') + { + $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING; + } if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE; if (empty($this->sendmode)) $this->sendmode='mail'; - $this->sendsetup = array(); - - // We define end of line (RFC 821). $this->eol="\r\n"; // We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n). @@ -145,7 +146,7 @@ class CMailFile $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contains special chars) dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG); - dol_syslog("CMailFile::CMailfile: subject=$subject, deliveryreceipt=$deliveryreceipt, msgishtml=$msgishtml", LOG_DEBUG); + dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG); if (empty($subject)) { @@ -274,7 +275,8 @@ class CMailFile // comme des injections mail par les serveurs de messagerie. $this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers); - $this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol; + //$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol; + $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol; $this->message.= $text_body . $files_encoded; $this->message.= "--" . $this->mixed_boundary . "--" . $this->eol; } @@ -497,9 +499,7 @@ class CMailFile { require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; $hookmanager = new HookManager($db); - $hookmanager->initHooks(array( - 'maildao' - )); + $hookmanager->initHooks(array('maildao')); $reshook = $hookmanager->executeHooks('doactions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (! empty($reshook)) { @@ -542,6 +542,22 @@ class CMailFile return false; } + $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER'; + $keyforsmtpport ='MAIN_MAIL_SMTP_PORT'; + $keyforsmtpid ='MAIN_MAIL_SMTPS_ID'; + $keyforsmtppw ='MAIN_MAIL_SMTPS_PW'; + $keyfortls ='MAIN_MAIL_EMAIL_TLS'; + $keyforstarttls ='MAIN_MAIL_EMAIL_STARTTLS'; + if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') + { + $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING'; + $keyforsmtpport ='MAIN_MAIL_SMTP_PORT_EMAILING'; + $keyforsmtpid ='MAIN_MAIL_SMTPS_ID_EMAILING'; + $keyforsmtppw ='MAIN_MAIL_SMTPS_PW_EMAILING'; + $keyfortls ='MAIN_MAIL_EMAIL_TLS_EMAILING'; + $keyforstarttls ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING'; + } + // Action according to choosed sending method if ($this->sendmode == 'mail') { @@ -558,9 +574,9 @@ class CMailFile @ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2)); } - // Forcage parametres - if (! empty($conf->global->MAIN_MAIL_SMTP_SERVER)) ini_set('SMTP',$conf->global->MAIN_MAIL_SMTP_SERVER); - if (! empty($conf->global->MAIN_MAIL_SMTP_PORT)) ini_set('smtp_port',$conf->global->MAIN_MAIL_SMTP_PORT); + // Force parameters + if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver); + if (! empty($conf->global->$keyforsmtpport)) ini_set('smtp_port',$conf->global->$keyforsmtpport); $dest=$this->getValidAddress($this->addr_to,2); if (! $dest) @@ -620,9 +636,9 @@ class CMailFile @ini_restore('sendmail_from'); } - // Forcage parametres - if (! empty($conf->global->MAIN_MAIL_SMTP_SERVER)) ini_restore('SMTP'); - if (! empty($conf->global->MAIN_MAIL_SMTP_PORT)) ini_restore('smtp_port'); + // Restore parameters + if (! empty($conf->global->$keyforsmtpserver)) ini_restore('SMTP'); + if (! empty($conf->global->$keyforsmtpport)) ini_restore('smtp_port'); } else if ($this->sendmode == 'smtps') { @@ -632,28 +648,30 @@ class CMailFile $this->smtps->setTransportType(0); // Only this method is coded in SMTPs library // Clean parameters - if (empty($conf->global->MAIN_MAIL_SMTP_SERVER)) $conf->global->MAIN_MAIL_SMTP_SERVER=ini_get('SMTP'); - if (empty($conf->global->MAIN_MAIL_SMTP_PORT)) $conf->global->MAIN_MAIL_SMTP_PORT=ini_get('smtp_port'); - - // TODO Manage alternative parameters + if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP'); + if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport=ini_get('smtp_port'); // If we use SSL/TLS - $server=$conf->global->MAIN_MAIL_SMTP_SERVER; - if (! empty($conf->global->MAIN_MAIL_EMAIL_TLS) && function_exists('openssl_open')) $server='ssl://'.$server; - $port=$conf->global->MAIN_MAIL_SMTP_PORT; + $server=$conf->global->$keyforsmtpserver; + $secure=''; + if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl'; + if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls'; + $server=($secure?$secure.'://':'').$server; + + $port=$conf->global->$keyforsmtpport; $this->smtps->setHost($server); $this->smtps->setPort($port); // 25, 465...; $loginid=''; $loginpass=''; - if (! empty($conf->global->MAIN_MAIL_SMTPS_ID)) + if (! empty($conf->global->$keyforsmtpid)) { - $loginid = $conf->global->MAIN_MAIL_SMTPS_ID; + $loginid = $conf->global->$keyforsmtpid; $this->smtps->setID($loginid); } - if (! empty($conf->global->MAIN_MAIL_SMTPS_PW)) + if (! empty($conf->global->$keyforsmtppw)) { - $loginpass = $conf->global->MAIN_MAIL_SMTPS_PW; + $loginpass = $conf->global->$keyforsmtppw; $this->smtps->setPW($loginpass); } @@ -661,14 +679,14 @@ class CMailFile $from=$this->smtps->getFrom('org'); if (! $from) { - $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->MAIN_MAIL_SMTP_PORT."
    Sender address '$from' invalid"; + $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
    Sender address '$from' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res=false; } $dest=$this->smtps->getTo(); if (! $dest) { - $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->MAIN_MAIL_SMTP_PORT."
    Recipient address '$dest' invalid"; + $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
    Recipient address '$dest' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res=false; } @@ -694,26 +712,24 @@ class CMailFile } else if ($this->sendmode == 'swiftmailer') { - // Use Swift Mailer library // ------------------------------------------ require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; - // Forcage parametres - if (empty($conf->global->MAIN_MAIL_SMTP_SERVER)) $conf->global->MAIN_MAIL_SMTP_SERVER=ini_get('SMTP'); - if (empty($conf->global->MAIN_MAIL_SMTP_PORT)) $conf->global->MAIN_MAIL_SMTP_PORT=ini_get('smtp_port'); + // Clean parameters + if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP'); + if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport=ini_get('smtp_port'); // If we use SSL/TLS - $server=$conf->global->MAIN_MAIL_SMTP_SERVER; + $server=$conf->global->$keyforsmtpserver; $secure=''; - //var_dump(stream_get_transports()); - if (! empty($conf->global->MAIN_MAIL_EMAIL_TLS) && function_exists('openssl_open')) $secure='ssl'; - if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $secure='tls'; + if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl'; + if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls'; - $this->transport = Swift_SmtpTransport::newInstance($server, $conf->global->MAIN_MAIL_SMTP_PORT, $secure); + $this->transport = Swift_SmtpTransport::newInstance($server, $conf->global->$keyforsmtpport, $secure); - if (! empty($conf->global->MAIN_MAIL_SMTPS_ID)) $this->transport->setUsername($conf->global->MAIN_MAIL_SMTPS_ID); - if (! empty($conf->global->MAIN_MAIL_SMTPS_PW)) $this->transport->setPassword($conf->global->MAIN_MAIL_SMTPS_PW); + if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid); + if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw); //$smtps->_msgReplyTo = 'reply@web.com'; // Create the Mailer using your created Transport @@ -946,8 +962,8 @@ class CMailFile //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol; - $out.= "Content-Type: multipart/mixed; boundary=\"".$this->mixed_boundary."\"".$this->eol2; - $out.= "Content-Transfer-Encoding: 8bit".$this->eol2; + $out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2; + $out.= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received. dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out); return $out; @@ -999,23 +1015,23 @@ class CMailFile if ($this->atleastoneimage) { - $out.= "Content-Type: multipart/alternative; boundary=\"".$this->alternative_boundary."\"".$this->eol; + $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; $out.= $this->eol; $out.= "--" . $this->alternative_boundary . $this->eol; } // Make RFC821 Compliant, replace bare linefeeds - $strContent = preg_replace("/(?global->MAIN_FIX_FOR_BUGGED_MTA)) { - $strContent = preg_replace("/\r\n/si", "\n", $strContent); + $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars } $strContentAltText = ''; if ($this->msgishtml) { $strContentAltText = html_entity_decode(strip_tags($strContent)); - $strContentAltText = rtrim(wordwrap($strContentAltText, 75, "\r\n")); + $strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n")); // Check if html header already in message, if not complete the message $strContent = $this->checkIfHTML($strContent); @@ -1023,31 +1039,35 @@ class CMailFile // Make RFC2045 Compliant, split lines //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content - $strContent = rtrim(wordwrap($strContent)); // TODO Using this method creates unexpected line break on text/plain content. + // TODO Encode main content into base64 and use the chunk_split, or quoted-printable + $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n")); // TODO Using this method creates unexpected line break on text/plain content. if ($this->msgishtml) { if ($this->atleastoneimage) { $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message $out.= "--" . $this->alternative_boundary . $this->eol; - $out.= "Content-Type: multipart/related; boundary=\"".$this->related_boundary."\"".$this->eol; + $out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol; $out.= $this->eol; $out.= "--" . $this->related_boundary . $this->eol; } if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part { - $out.= "Content-Type: multipart/alternative; boundary=\"".$this->alternative_boundary."\"".$this->eol; + $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; $out.= $this->eol; $out.= "--" . $this->alternative_boundary . $this->eol; $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out.= $this->eol.$strContentAltText.$this->eol; $out.= "--" . $this->alternative_boundary . $this->eol; } $out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; // TODO Use base64 $out.= $this->eol.$strContent.$this->eol; if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part @@ -1058,6 +1078,7 @@ class CMailFile else { $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out.= $this->eol.$strContent.$this->eol; } @@ -1164,13 +1185,30 @@ class CMailFile function check_server_port($host,$port) { global $conf; + $_retVal=0; $timeout=5; // Timeout in seconds if (function_exists('fsockopen')) { + $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER'; + $keyforsmtpport ='MAIN_MAIL_SMTP_PORT'; + $keyforsmtpid ='MAIN_MAIL_SMTPS_ID'; + $keyforsmtppw ='MAIN_MAIL_SMTPS_PW'; + $keyfortls ='MAIN_MAIL_EMAIL_TLS'; + $keyforstarttls ='MAIN_MAIL_EMAIL_STARTTLS'; + if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') + { + $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING'; + $keyforsmtpport ='MAIN_MAIL_SMTP_PORT_EMAILING'; + $keyforsmtpid ='MAIN_MAIL_SMTPS_ID_EMAILING'; + $keyforsmtppw ='MAIN_MAIL_SMTPS_PW_EMAILING'; + $keyfortls ='MAIN_MAIL_EMAIL_TLS_EMAILING'; + $keyforstarttls ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING'; + } + // If we use SSL/TLS - if (! empty($conf->global->MAIN_MAIL_EMAIL_TLS) && function_exists('openssl_open')) $host='ssl://'.$host; + if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host; // tls smtp start with no encryption //if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host; diff --git a/htdocs/core/class/antivir.class.php b/htdocs/core/class/antivir.class.php index 357f184eea8..b5f4f0e5539 100644 --- a/htdocs/core/class/antivir.class.php +++ b/htdocs/core/class/antivir.class.php @@ -63,9 +63,9 @@ class AntiVir if (preg_match('/\.virus$/i', $file)) { $this->errors='File has an extension saying file is a virus'; - return -97; + return -97; } - + $fullcommand=$this->getCliCommand($file); //$fullcommand='"c:\Program Files (x86)\ClamWin\bin\clamscan.exe" --database="C:\Program Files (x86)\ClamWin\lib" "c:\temp\aaa.txt"'; $fullcommand.=' 2>&1'; // This is to get error output diff --git a/htdocs/core/class/ccountry.class.php b/htdocs/core/class/ccountry.class.php index d0e6dfe190a..7964510c91c 100644 --- a/htdocs/core/class/ccountry.class.php +++ b/htdocs/core/class/ccountry.class.php @@ -88,11 +88,11 @@ class Ccountry // extends CommonObject $sql.= "label,"; $sql.= "active"; $sql.= ") VALUES ("; - $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->rowid."'").","; + $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").","; $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; $sql.= " ".(! isset($this->code_iso)?'NULL':"'".$this->db->escape($this->code_iso)."'").","; $sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").","; - $sql.= " ".(! isset($this->active)?'NULL':"'".$this->active."'").""; + $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'").""; $sql.= ")"; $this->db->begin(); diff --git a/htdocs/core/class/comment.class.php b/htdocs/core/class/comment.class.php new file mode 100644 index 00000000000..a21057662f2 --- /dev/null +++ b/htdocs/core/class/comment.class.php @@ -0,0 +1,324 @@ +db = $db; + } + + + /** + * Create into database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + function create($user, $notrigger=0) + { + global $conf, $langs; + + $error=0; + + // Insert request + $sql = "INSERT INTO ".MAIN_DB_PREFIX."comment ("; + $sql.= "description"; + $sql.= ", datec"; + $sql.= ", fk_element"; + $sql.= ", element_type"; + $sql.= ", fk_user_author"; + $sql.= ", entity"; + $sql.= ", import_key"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->escape($this->description)."'"; + $sql.= ", ".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null'); + $sql.= ", '".(isset($this->fk_element)?$this->fk_element:"null")."'"; + $sql.= ", '".$this->db->escape($this->element_type)."'"; + $sql.= ", '".(isset($this->fk_user_author)?$this->fk_user_author:"null")."'"; + $sql.= ", ".(!empty($this->entity)?$this->entity:'1'); + $sql.= ", ".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null"); + $sql.= ")"; + + //var_dump($this->db); + //echo $sql; + + $this->db->begin(); + + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_comment"); + + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_COMMENT_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id Id object + * @param int $ref ref object + * @return int <0 if KO, 0 if not found, >0 if OK + */ + function fetch($id, $ref='') + { + global $langs; + + $sql = "SELECT"; + $sql.= " c.rowid,"; + $sql.= " c.description,"; + $sql.= " c.datec,"; + $sql.= " c.tms,"; + $sql.= " c.fk_element,"; + $sql.= " c.element_type,"; + $sql.= " c.fk_user_author,"; + $sql.= " c.entity,"; + $sql.= " c.import_key"; + $sql.= " FROM ".MAIN_DB_PREFIX."comment as c"; + $sql.= " WHERE c.rowid = ".$id; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $num_rows = $this->db->num_rows($resql); + + if ($num_rows) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->description = $obj->description; + $this->element_type = $obj->element_type; + $this->datec = $this->db->jdate($obj->datec); + $this->tms = $obj->tms; + $this->fk_user_author = $obj->fk_user_author; + $this->fk_element = $obj->fk_element; + $this->entity = $obj->entity; + $this->import_key = $obj->import_key; + } + + $this->db->free($resql); + + if ($num_rows) return 1; + else return 0; + } + else + { + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <=0 if KO, >0 if OK + */ + function update(User $user, $notrigger=0) + { + global $conf, $langs; + $error=0; + + // Clean parameters + if (isset($this->fk_element)) $this->fk_project=(int) trim($this->fk_element); + if (isset($this->fk_user_author)) $this->fk_user_author=(int) trim($this->fk_user_author); + if (isset($this->description)) $this->description=trim($this->description); + + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_comment SET"; + $sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").","; + $sql.= " datec=".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null').","; + $sql.= " fk_element=".(isset($this->fk_element)?$this->fk_element:"null").","; + $sql.= " element_type='".$this->db->escape($this->element_type)."',"; + $sql.= " fk_user_author=".(isset($this->fk_user_author)?$this->fk_user_author:"null").","; + $sql.= " entity=".(!empty($this->entity)?$this->entity:'1').","; + $sql.= " import_key=".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null"); + $sql.= " WHERE rowid=".$this->id; + + $this->db->begin(); + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_COMMENT_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return 1; + } + } + + + /** + * Delete task from database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function delete($user, $notrigger=0) + { + global $conf, $langs; + require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + $error=0; + + $this->db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."comment"; + $sql.= " WHERE rowid=".$this->id; + + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_COMMENT_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + }else{ + $this->db->commit(); + return 1; + } + } + + + /** + * Load comments linked with current task + * + * @param string $element_type Element type + * @param int $fk_element Id of element + * @return array Comment array + */ + public static function fetchAllFor($element_type, $fk_element) + { + global $db,$conf; + $TComments = array(); + if(!empty($element_type) && !empty($fk_element)) { + $sql = "SELECT"; + $sql.= " c.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."comment as c"; + $sql.= " WHERE c.fk_element = ".$fk_element; + $sql.= " AND c.element_type = '".$db->escape($element_type)."'"; + $sql.= " AND c.entity = ".$conf->entity; + $sql.= " ORDER BY c.tms DESC"; + + dol_syslog("Comment::fetchAllFor", LOG_DEBUG); + $resql=$db->query($sql); + if ($resql) + { + $num_rows = $db->num_rows($resql); + if ($num_rows > 0) + { + while($obj = $db->fetch_object($resql)) + { + $comment = new self($db); + $comment->fetch($obj->rowid); + $TComments[] = $comment; + } + } + $db->free($resql); + } + } + return $TComments; + } +} \ No newline at end of file diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index 535200ab95a..666011b3f4a 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -418,6 +418,21 @@ abstract class CommonDocGenerator $resarray[$array_key.'_total_discount_ht'] = ''; } + // Fetch project information if there is a project assigned to this object + if ($object->element != "project" && ! empty($object->fk_project) && $object->fk_project > 0) + { + if (! is_object($object->project)) + { + $object->fetch_projet(); + } + + $resarray[$array_key.'_project_ref'] = $object->project->ref; + $resarray[$array_key.'_project_title'] = $object->project->title; + $resarray[$array_key.'_project_description'] = $object->project->description; + $resarray[$array_key.'_project_date_start'] = dol_print_date($object->project->date_start, 'day'); + $resarray[$array_key.'_project_date_end'] = dol_print_date($object->project->date_end, 'day'); + } + // Add vat by rates if (is_array($object->lines) && count($object->lines)>0) { @@ -495,6 +510,13 @@ abstract class CommonDocGenerator 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), ); + + // Units + if ($conf->global->PRODUCT_USE_UNITS) + { + $resarray['line_unit']=$outputlangs->trans($line->getLabelOfUnit('long')); + $resarray['line_unit_short']=$outputlangs->trans($line->getLabelOfUnit('short')); + } // Retrieve extrafields $extrafieldkey=$line->element; diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 6bbde52cb58..2f6d72fb64e 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -450,8 +450,9 @@ abstract class CommonInvoice extends CommonObject $sqltemp = 'SELECT c.type_cdr,c.nbjour,c.decalage'; $sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c'; - if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement; - else $sqltemp.= " WHERE c.code='".$this->db->escape($cond_reglement)."'"; + $sqltemp.= " WHERE c.entity IN (" . getEntity('c_payment_term').")"; + if (is_numeric($cond_reglement)) $sqltemp.= " AND c.rowid=".$cond_reglement; + else $sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'"; dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG); $resqltemp=$this->db->query($sqltemp); diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index a97b553aed4..7f73630f7f6 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -12,6 +12,7 @@ * Copyright (C) 2015 Alexandre Spangaro * Copyright (C) 2016 Bahfir abbes * Copyright (C) 2017 ATM Consulting + * Copyright (C) 2017 Nicolas ZABOURI * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -39,24 +40,24 @@ */ abstract class CommonObject { - /** - * @var DoliDb Database handler (result of a new DoliDB) - */ + /** + * @var DoliDb Database handler (result of a new DoliDB) + */ public $db; /** * @var int The object identifier */ public $id; - /** - * @var string Error string - * @deprecated Use instead the array of error strings - * @see errors - */ - public $error; /** - * @var string[] Array of error strings - */ - public $errors=array(); + * @var string Error string + * @deprecated Use instead the array of error strings + * @see errors + */ + public $error; + /** + * @var string[] Array of error strings + */ + public $errors=array(); /** * @var string */ @@ -69,45 +70,45 @@ abstract class CommonObject * @var */ public $table_element_line; - /** - * @var string Key value used to track if data is coming from import wizard - */ - public $import_key; - /** - * @var mixed Contains data to manage extrafields - */ - public $array_options=array(); - /** - * @var int[] Array of linked objects ids. Loaded by ->fetchObjectLinked - */ - public $linkedObjectsIds; - /** - * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked - */ - public $linkedObjects; - /** - * @var Object To store a cloned copy of object before to edit it and keep track of old properties - */ - public $oldcopy; + /** + * @var string Key value used to track if data is coming from import wizard + */ + public $import_key; + /** + * @var mixed Contains data to manage extrafields + */ + public $array_options=array(); + /** + * @var int[] Array of linked objects ids. Loaded by ->fetchObjectLinked + */ + public $linkedObjectsIds; + /** + * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked + */ + public $linkedObjects; + /** + * @var Object To store a cloned copy of object before to edit it and keep track of old properties + */ + public $oldcopy; - /** - * @var string Column name of the ref field. - */ - protected $table_ref_field = ''; + /** + * @var string Column name of the ref field. + */ + protected $table_ref_field = ''; - // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them. + // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them. - /** - * @var string[] Can be used to pass information when only object is provided to method - */ - public $context=array(); + /** + * @var array Can be used to pass information when only object is provided to method + */ + public $context=array(); - /** - * @var string Contains canvas name if record is an alternative canvas record - */ - public $canvas; + /** + * @var string Contains canvas name if record is an alternative canvas record + */ + public $canvas; /** * @var Project The related project @@ -309,6 +310,12 @@ abstract class CommonObject */ public $lines; + /** + * @var mixed Contains comments + * @see fetchComments() + */ + public $comments=array(); + /** * @var int * @see setIncoterms() @@ -325,14 +332,13 @@ abstract class CommonObject */ public $location_incoterms; - public $name; - public $lastname; - public $firstname; - public $civility_id; + public $name; + public $lastname; + public $firstname; + public $civility_id; - // No constructor as it is an abstract class - + // No constructor as it is an abstract class /** * Check an object id/ref exists @@ -383,84 +389,84 @@ abstract class CommonObject return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):''); } - /** - * Return full name (civility+' '+name+' '+lastname) - * - * @param Translate $langs Language object for translation of civility - * @param int $option 0=No option, 1=Add civility - * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname - * @param int $maxlen Maximum length - * @return string String with full name - */ - function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0) - { - //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."
    \n"; - $lastname=$this->lastname; - $firstname=$this->firstname; - if (empty($lastname)) $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:(isset($this->societe)?$this->societe:(isset($this->company)?$this->company:''))))); + /** + * Return full name (civility+' '+name+' '+lastname) + * + * @param Translate $langs Language object for translation of civility + * @param int $option 0=No option, 1=Add civility + * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname + * @param int $maxlen Maximum length + * @return string String with full name + */ + function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0) + { + //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."
    \n"; + $lastname=$this->lastname; + $firstname=$this->firstname; + if (empty($lastname)) $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:(isset($this->societe)?$this->societe:(isset($this->company)?$this->company:''))))); - $ret=''; - if ($option && $this->civility_id) - { - if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' '; - else $ret.=$this->civility_id.' '; - } + $ret=''; + if ($option && $this->civility_id) + { + if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' '; + else $ret.=$this->civility_id.' '; + } - $ret.=dolGetFirstLastname($firstname, $lastname, $nameorder); + $ret.=dolGetFirstLastname($firstname, $lastname, $nameorder); - return dol_trunc($ret,$maxlen); - } + return dol_trunc($ret,$maxlen); + } - /** - * Return full address of contact - * - * @param int $withcountry 1=Add country into address string - * @param string $sep Separator to use to build string - * @return string Full address string - */ - function getFullAddress($withcountry=0,$sep="\n") - { - if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) - { - require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; - $tmparray=getCountry($this->country_id,'all'); - $this->country_code=$tmparray['code']; - $this->country =$tmparray['label']; - } + /** + * Return full address of contact + * + * @param int $withcountry 1=Add country into address string + * @param string $sep Separator to use to build string + * @return string Full address string + */ + function getFullAddress($withcountry=0,$sep="\n") + { + if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) + { + require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; + $tmparray=getCountry($this->country_id,'all'); + $this->country_code=$tmparray['code']; + $this->country =$tmparray['label']; + } - return dol_format_address($this, $withcountry, $sep); - } + return dol_format_address($this, $withcountry, $sep); + } - /** - * Return full address for banner - * - * @param string $htmlkey HTML id to make banner content unique - * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member) - * @return string Full address string - */ - function getBannerAddress($htmlkey, $object) - { - global $conf, $langs; + /** + * Return full address for banner + * + * @param string $htmlkey HTML id to make banner content unique + * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member) + * @return string Full address string + */ + function getBannerAddress($htmlkey, $object) + { + global $conf, $langs; - $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS + $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS - $contactid=0; - $thirdpartyid=0; - if ($this->element == 'societe') - { - $thirdpartyid=$this->id; - } - if ($this->element == 'contact') - { - $contactid=$this->id; + $contactid=0; + $thirdpartyid=0; + if ($this->element == 'societe') + { + $thirdpartyid=$this->id; + } + if ($this->element == 'contact') + { + $contactid=$this->id; $thirdpartyid=$object->fk_soc; - } - if ($this->element == 'user') - { - $contactid=$this->contact_id; + } + if ($this->element == 'user') + { + $contactid=$this->contact_id; $thirdpartyid=$object->fk_soc; - } + } $out=''; @@ -488,7 +494,7 @@ abstract class CommonObject } if (! empty($this->phone) || ! empty($this->phone_pro) || ! empty($this->phone_mobile) || ! empty($this->phone_perso) || ! empty($this->fax) || ! empty($this->office_phone) || ! empty($this->user_mobile) || ! empty($this->office_fax)) $out.=($outdone?'
    ':''); - if (! empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone + if (! empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone $out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','phone',$langs->trans("PhonePro")); $outdone++; } if (! empty($this->phone_pro)) { @@ -503,7 +509,7 @@ abstract class CommonObject if (! empty($this->fax)) { $out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX',' ','fax',$langs->trans("Fax")); $outdone++; } - if (! empty($this->office_phone)) { + if (! empty($this->office_phone)) { $out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','phone',$langs->trans("PhonePro")); $outdone++; } if (! empty($this->user_mobile)) { @@ -520,7 +526,7 @@ abstract class CommonObject $out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1); $outdone++; } - if (! empty($this->url)) + if (! empty($this->url)) { $out.=dol_print_url($this->url,'_goout',0,1); $outdone++; @@ -535,1021 +541,1106 @@ abstract class CommonObject $out.=''; return $out; - } + } - /** - * Add a link between element $this->element and a contact - * - * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link - * @param int $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL - * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) - * @param int $notrigger Disable all triggers - * @return int <0 if KO, >0 if OK - */ - function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0) - { - global $user,$langs; + /** + * Return the link of last main doc file for direct public download. + * + * @param string $modulepart Module related to document + * @param int $initsharekey Init the share key if it was not yet defined + * @return string Link or empty string if there is no download link + */ + function getLastMainDocLink($modulepart, $initsharekey=0) + { + global $user, $dolibarr_main_url_root; - - dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger"); - - // Check parameters - if ($fk_socpeople <= 0) - { - $langs->load("errors"); - $this->error=$langs->trans("ErrorWrongValueForParameterX","1"); - dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); - return -1; - } - if (! $type_contact) - { - $langs->load("errors"); - $this->error=$langs->trans("ErrorWrongValueForParameterX","2"); - dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); - return -2; - } - - $id_type_contact=0; - if (is_numeric($type_contact)) - { - $id_type_contact=$type_contact; - } - else - { - // On recherche id type_contact - $sql = "SELECT tc.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; - $sql.= " AND tc.source='".$source."'"; - $sql.= " AND tc.code='".$type_contact."' AND tc.active=1"; - //print $sql; - $resql=$this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) $id_type_contact=$obj->rowid; - } - } - - if ($id_type_contact == 0) - { - $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT'; - dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT"); - return -3; - } - - $datecreate = dol_now(); - - // Socpeople must have already been added by some a trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error - $TListeContacts=$this->liste_contact(-1, $source); - $already_added=false; - if(!empty($TListeContacts)) { - foreach($TListeContacts as $array_contact) { - if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) { - $already_added=true; - break; - } - } - } - - if(!$already_added) { - - $this->db->begin(); - - // Insertion dans la base - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact"; - $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) "; - $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ; - $sql.= "'".$this->db->idate($datecreate)."'"; - $sql.= ", 4, ". $id_type_contact; - $sql.= ")"; - - $resql=$this->db->query($sql); - if ($resql) - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - } - - $this->db->commit(); - return 1; - } - else - { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $this->error=$this->db->errno(); - $this->db->rollback(); - echo 'err rollback'; - return -2; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -1; - } - } - } else return 0; - } - - /** - * Copy contact from one element to current - * - * @param CommonObject $objFrom Source element - * @param string $source Nature of contact ('internal' or 'external') - * @return int >0 if OK, <0 if KO - */ - function copy_linked_contact($objFrom, $source='internal') - { - $contacts = $objFrom->liste_contact(-1, $source); - foreach($contacts as $contact) - { - if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) - { - $this->error=$this->db->lasterror(); - return -1; - } - } - return 1; - } - - /** - * Update a link to contact line - * - * @param int $rowid Id of line contact-element - * @param int $statut New status of link - * @param int $type_contact_id Id of contact type (not modified if 0) - * @param int $fk_socpeople Id of soc_people to update (not modified if 0) - * @return int <0 if KO, >= 0 if OK - */ - function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0) - { - // Insertion dans la base - $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; - $sql.= " statut = ".$statut; - if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'"; - if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'"; - $sql.= " where rowid = ".$rowid; - $resql=$this->db->query($sql); - if ($resql) - { - return 0; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * Delete a link to contact line - * - * @param int $rowid Id of contact link line to delete - * @param int $notrigger Disable all triggers - * @return int >0 if OK, <0 if KO - */ - function delete_contact($rowid, $notrigger=0) - { - global $user; - - - $this->db->begin(); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql.= " WHERE rowid =".$rowid; - - dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG); - if ($this->db->query($sql)) - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); - if ($result < 0) { $this->db->rollback(); return -1; } - } - - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } - - /** - * Delete all links between an object $this and all its contacts - * - * @param string $source '' or 'internal' or 'external' - * @param string $code Type of contact (code or id) - * @return int >0 if OK, <0 if KO - */ - function delete_linked_contact($source='',$code='') - { - $temp = array(); - $typeContact = $this->liste_type_contact($source,'',0,0,$code); - - foreach($typeContact as $key => $value) - { - array_push($temp,$key); - } - $listId = implode(",", $temp); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql.= " WHERE element_id = ".$this->id; - if ($listId) - $sql.= " AND fk_c_type_contact IN (".$listId.")"; - - dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; - } - else + if (empty($this->last_main_doc)) { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * Get array of all contacts for an object - * - * @param int $statut Status of links to get (-1=all) - * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user) - * @param int $list 0:Return array contains all properties, 1:Return array contains just id - * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...) - * @return array Array of contacts - */ - function liste_contact($statut=-1,$source='external',$list=0,$code='') - { - global $langs; - - $tab=array(); - - $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user - if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo"; - if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact"; - $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email"; - $sql.= ", tc.source, tc.element, tc.code, tc.libelle"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; - $sql.= ", ".MAIN_DB_PREFIX."element_contact ec"; - if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid"; - if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid"; - $sql.= " WHERE ec.element_id =".$this->id; - $sql.= " AND ec.fk_c_type_contact=tc.rowid"; - $sql.= " AND tc.element='".$this->db->escape($this->element)."'"; - if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'"; - if ($source == 'internal') $sql.= " AND tc.source = 'internal'"; - if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'"; - $sql.= " AND tc.active=1"; - if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'"; - $sql.=" ORDER BY t.lastname ASC"; - - dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - if (! $list) - { - $transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code; - $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); - $tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id, - 'nom'=>$obj->lastname, // For backward compatibility - 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact, - 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact); - } - else - { - $tab[$i]=$obj->id; - } - - $i++; - } - - return $tab; - } - else - { - $this->error=$this->db->lasterror(); - dol_print_error($this->db); - return -1; - } - } - - - /** - * Update status of a contact linked to object - * - * @param int $rowid Id of link between object and contact - * @return int <0 if KO, >=0 if OK - */ - function swapContactStatus($rowid) - { - $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,"; - $sql.= " tc.code, tc.libelle"; - //$sql.= ", s.fk_soc"; - $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)"; - //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid"; // Si contact de type external, alors il est lie a une societe - $sql.= " WHERE ec.rowid =".$rowid; - $sql.= " AND ec.fk_c_type_contact=tc.rowid"; - $sql.= " AND tc.element = '".$this->db->escape($this->element)."'"; - - dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $newstatut = ($obj->statut == 4) ? 5 : 4; - $result = $this->update_contact($rowid, $newstatut); - $this->db->free($resql); - return $result; - } - else - { - $this->error=$this->db->error(); - dol_print_error($this->db); - return -1; - } - - } - - /** - * Return array with list of possible values for type of contacts - * - * @param string $source 'internal', 'external' or 'all' - * @param string $order Sort order by : 'position', 'code', 'rowid'... - * @param int $option 0=Return array id->label, 1=Return array code->label - * @param int $activeonly 0=all status of contact, 1=only the active - * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE') - * @return array Array list of type of contacts (id->label if option=0, code->label if option=1) - */ - function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='') - { - global $langs; - - if (empty($order)) $order='position'; - if ($order == 'position') $order.=',code'; - - $tab = array(); - $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; - if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types - if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'"; - if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'"; - $sql.= $this->db->order($order,'ASC'); - - //print "sql=".$sql; - $resql=$this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - $transkey="TypeContact_".$this->element."_".$source."_".$obj->code; - $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); - if (empty($option)) $tab[$obj->rowid]=$libelle_type; - else $tab[$obj->code]=$libelle_type; - $i++; - } - return $tab; - } - else - { - $this->error=$this->db->lasterror(); - //dol_print_error($this->db); - return null; - } - } - - /** - * Return id of contacts for a source and a contact code. - * Example: contact client de facturation ('external', 'BILLING') - * Example: contact client de livraison ('external', 'SHIPPING') - * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL') - * - * @param string $source 'external' or 'internal' - * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ... - * @param int $status limited to a certain status - * @return array List of id for such contacts - */ - function getIdContact($source,$code,$status=0) - { - global $conf; - - $result=array(); - $i=0; - //cas particulier pour les expeditions - if($this->element=='shipping' && $this->origin_id != 0) { - $id=$this->origin_id; - $element='commande'; - } else { - $id=$this->id; - $element=$this->element; - } - - $sql = "SELECT ec.fk_socpeople"; - $sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,"; - if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,"; - if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,"; - $sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE ec.element_id = ".$id; - $sql.= " AND ec.fk_socpeople = c.rowid"; - if ($source == 'internal') $sql.= " AND c.entity IN (0,".$conf->entity.")"; - if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")"; - $sql.= " AND ec.fk_c_type_contact = tc.rowid"; - $sql.= " AND tc.element = '".$element."'"; - $sql.= " AND tc.source = '".$source."'"; - $sql.= " AND tc.code = '".$code."'"; - $sql.= " AND tc.active = 1"; - if ($status) $sql.= " AND ec.statut = ".$status; - - dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - $result[$i]=$obj->fk_socpeople; - $i++; - } - } - else - { - $this->error=$this->db->error(); - return null; - } - - return $result; - } - - /** - * Load object contact with id=$this->contactid into $this->contact - * - * @param int $contactid Id du contact. Use this->contactid if empty. - * @return int <0 if KO, >0 if OK - */ - function fetch_contact($contactid=null) - { - if (empty($contactid)) $contactid=$this->contactid; - - if (empty($contactid)) return 0; - - require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - $contact = new Contact($this->db); - $result=$contact->fetch($contactid); - $this->contact = $contact; - return $result; - } - - /** - * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty - * - * @param int $force_thirdparty_id Force thirdparty id - * @return int <0 if KO, >0 if OK - */ - function fetch_thirdparty($force_thirdparty_id=0) - { - global $conf; - - if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) - return 0; - - require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; - - $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty); - if ($force_thirdparty_id) - $idtofetch = $force_thirdparty_id; - - if ($idtofetch) { - $thirdparty = new Societe($this->db); - $result = $thirdparty->fetch($idtofetch); - $this->thirdparty = $thirdparty; - - // Use first price level if level not defined for third party - if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) { - $this->thirdparty->price_level = 1; - } - - return $result; - } else - return -1; - } - - - /** - * Looks for an object with ref matching the wildcard provided - * It does only work when $this->table_ref_field is set - * - * @param string $ref Wildcard - * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO - */ - public function fetchOneLike($ref) - { - if (!$this->table_ref_field) { - return 0; - } - - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1'; - - $query = $this->db->query($sql); - - if (!$this->db->num_rows($query)) { - return 0; - } - - $result = $this->db->fetch_object($query); - - return $this->fetch($result->rowid); - } - - /** - * Load data for barcode into properties ->barcode_type* - * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but - * if it is not defined, ->element must be defined to know default barcode type. - * - * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded) - */ - function fetch_barcode() - { - global $conf; - - dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type); - - $idtype=$this->barcode_type; - if (empty($idtype) && $idtype != '0') // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined - { - if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; - else if ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY; - else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING); - } - - if ($idtype > 0) - { - if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) // If data not already loaded - { - $sql = "SELECT rowid, code, libelle as label, coder"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; - $sql.= " WHERE rowid = ".$idtype; - dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $this->barcode_type = $obj->rowid; - $this->barcode_type_code = $obj->code; - $this->barcode_type_label = $obj->label; - $this->barcode_type_coder = $obj->coder; - return 1; - } - else - { - dol_print_error($this->db); - return -1; - } - } - } - return 0; - } - - /** - * Charge le projet d'id $this->fk_project dans this->projet - * - * @return int <0 if KO, >=0 if OK - */ - function fetch_projet() - { - include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - - if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility - if (empty($this->fk_project)) return 0; - - $project = new Project($this->db); - $result = $project->fetch($this->fk_project); - - $this->projet = $project; // deprecated - $this->project = $project; - return $result; - } - - /** - * Charge le user d'id userid dans this->user - * - * @param int $userid Id du contact - * @return int <0 if KO, >0 if OK - */ - function fetch_user($userid) - { - $user = new User($this->db); - $result=$user->fetch($userid); - $this->user = $user; - return $result; - } - - /** - * Read linked origin object - * - * @return void - */ - function fetch_origin() - { - if ($this->origin == 'shipping') $this->origin = 'expedition'; - if ($this->origin == 'delivery') $this->origin = 'livraison'; - - $origin = $this->origin; - - $classname = ucfirst($origin); - $this->$origin = new $classname($this->db); - $this->$origin->fetch($this->origin_id); - } - - /** - * Load object from specific field - * - * @param string $table Table element or element line - * @param string $field Field selected - * @param string $key Import key - * @return int <0 if KO, >0 if OK - */ - function fetchObjectFrom($table,$field,$key) - { - global $conf; - - $result=false; - - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$field." = '".$key."'"; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - $result = $this->fetch($row[0]); - } - - return $result; - } - - /** - * Getter generic. Load value from a specific field - * - * @param string $table Table of element or element line - * @param int $id Element id - * @param string $field Field selected - * @return int <0 if KO, >0 if OK - */ - function getValueFrom($table, $id, $field) - { - $result=false; - if (!empty($id) && !empty($field) && !empty($table)) { - $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE rowid = ".$id; - - dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - $result = $row[0]; - } + return ''; // No known last doc } - return $result; - } - /** - * Setter generic. Update a specific field into database. - * Warning: Trigger is run only if param trigkey is provided. - * - * @param string $field Field to update - * @param mixed $value New value - * @param string $table To force other table element or element line (should not be used) - * @param int $id To force other object id (should not be used) - * @param string $format Data format ('text', 'date'). 'text' is used if not defined - * @param string $id_field To force rowid field name. 'rowid' is used if not defined - * @param User|string $fuser Update the user of last update field with this user. If not provided, current user is used except if value is 'none' - * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY') - * @return int <0 if KO, >0 if OK - */ - function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='') - { - global $user,$langs,$conf; + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile=new EcmFiles($this->db); + $result = $ecmfile->fetch(0, '', $this->last_main_doc); + if ($result < 0) + { + $this->error = $ecmfile->error; + $this->errors = $ecmfile->errors; + return -1; + } - if (empty($table)) $table=$this->table_element; - if (empty($id)) $id=$this->id; + if (empty($ecmfile->id)) + { + // Add entry into index + if ($initsharekey) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first + /* + $ecmfile->filepath = $rel_dir; + $ecmfile->filename = $filename; + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $ecmfile->share = getRandomPassword(true); + $result = $ecmfile->create($user); + if ($result < 0) + { + $this->error = $ecmfile->error; + $this->errors = $ecmfile->errors; + } + */ + } + else return ''; + } + elseif (empty($ecmfile->share)) + { + // Add entry into index + if ($initsharekey) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $ecmfile->share = getRandomPassword(true); + $ecmfile->update($user); + } + else return ''; + } + + // Define $urlwithroot + $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); + $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 + + $forcedownload=1; + $rellink='/document.php?modulepart='.$modulepart; + if ($forcedownload) $rellink.='&attachment=1'; + if (! empty($ecmfile->entity)) $rellink.='&entity='.$ecmfile->entity; + //$rellink.='&file='.urlencode($filepath); // No need of name of file for public link, we will use the hash + $fulllink=$urlwithroot.$rellink; + //if (! empty($object->ref)) $fulllink.='&hashn='.$object->ref; // Hash of file path + //elseif (! empty($object->label)) $fulllink.='&hashc='.$object->label; // Hash of file content + if (! empty($ecmfile->share)) $fulllink.='&hashp='.$ecmfile->share; // Hash for public share + + // Here $ecmfile->share is defined + return $fulllink; + } + + + /** + * Add a link between element $this->element and a contact + * + * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link + * @param int $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL + * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) + * @param int $notrigger Disable all triggers + * @return int <0 if KO, >0 if OK + */ + function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0) + { + global $user,$langs; + + + dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger"); + + // Check parameters + if ($fk_socpeople <= 0) + { + $langs->load("errors"); + $this->error=$langs->trans("ErrorWrongValueForParameterX","1"); + dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); + return -1; + } + if (! $type_contact) + { + $langs->load("errors"); + $this->error=$langs->trans("ErrorWrongValueForParameterX","2"); + dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); + return -2; + } + + $id_type_contact=0; + if (is_numeric($type_contact)) + { + $id_type_contact=$type_contact; + } + else + { + // On recherche id type_contact + $sql = "SELECT tc.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; + $sql.= " AND tc.source='".$this->db->escape($source)."'"; + $sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1"; + //print $sql; + $resql=$this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) $id_type_contact=$obj->rowid; + } + } + + if ($id_type_contact == 0) + { + $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT'; + dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT"); + return -3; + } + + $datecreate = dol_now(); + + // Socpeople must have already been added by some a trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error + $TListeContacts=$this->liste_contact(-1, $source); + $already_added=false; + if(!empty($TListeContacts)) { + foreach($TListeContacts as $array_contact) { + if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) { + $already_added=true; + break; + } + } + } + + if(!$already_added) { + + $this->db->begin(); + + // Insertion dans la base + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact"; + $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) "; + $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ; + $sql.= "'".$this->db->idate($datecreate)."'"; + $sql.= ", 4, ". $id_type_contact; + $sql.= ")"; + + $resql=$this->db->query($sql); + if ($resql) + { + if (! $notrigger) + { + $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + } + + $this->db->commit(); + return 1; + } + else + { + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $this->error=$this->db->errno(); + $this->db->rollback(); + echo 'err rollback'; + return -2; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -1; + } + } + } else return 0; + } + + /** + * Copy contact from one element to current + * + * @param CommonObject $objFrom Source element + * @param string $source Nature of contact ('internal' or 'external') + * @return int >0 if OK, <0 if KO + */ + function copy_linked_contact($objFrom, $source='internal') + { + $contacts = $objFrom->liste_contact(-1, $source); + foreach($contacts as $contact) + { + if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) + { + $this->error=$this->db->lasterror(); + return -1; + } + } + return 1; + } + + /** + * Update a link to contact line + * + * @param int $rowid Id of line contact-element + * @param int $statut New status of link + * @param int $type_contact_id Id of contact type (not modified if 0) + * @param int $fk_socpeople Id of soc_people to update (not modified if 0) + * @return int <0 if KO, >= 0 if OK + */ + function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0) + { + // Insertion dans la base + $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; + $sql.= " statut = ".$statut; + if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'"; + if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'"; + $sql.= " where rowid = ".$rowid; + $resql=$this->db->query($sql); + if ($resql) + { + return 0; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * Delete a link to contact line + * + * @param int $rowid Id of contact link line to delete + * @param int $notrigger Disable all triggers + * @return int >0 if OK, <0 if KO + */ + function delete_contact($rowid, $notrigger=0) + { + global $user; + + + $this->db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; + $sql.= " WHERE rowid =".$rowid; + + dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG); + if ($this->db->query($sql)) + { + if (! $notrigger) + { + $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); + if ($result < 0) { $this->db->rollback(); return -1; } + } + + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } + + /** + * Delete all links between an object $this and all its contacts + * + * @param string $source '' or 'internal' or 'external' + * @param string $code Type of contact (code or id) + * @return int >0 if OK, <0 if KO + */ + function delete_linked_contact($source='',$code='') + { + $temp = array(); + $typeContact = $this->liste_type_contact($source,'',0,0,$code); + + foreach($typeContact as $key => $value) + { + array_push($temp,$key); + } + $listId = implode(",", $temp); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; + $sql.= " WHERE element_id = ".$this->id; + if ($listId) + $sql.= " AND fk_c_type_contact IN (".$listId.")"; + + dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG); + if ($this->db->query($sql)) + { + return 1; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * Get array of all contacts for an object + * + * @param int $statut Status of links to get (-1=all) + * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user) + * @param int $list 0:Return array contains all properties, 1:Return array contains just id + * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...) + * @return array Array of contacts + */ + function liste_contact($statut=-1,$source='external',$list=0,$code='') + { + global $langs; + + $tab=array(); + + $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user + if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo"; + if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact"; + $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email"; + $sql.= ", tc.source, tc.element, tc.code, tc.libelle"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; + $sql.= ", ".MAIN_DB_PREFIX."element_contact ec"; + if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid"; + if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid"; + $sql.= " WHERE ec.element_id =".$this->id; + $sql.= " AND ec.fk_c_type_contact=tc.rowid"; + $sql.= " AND tc.element='".$this->db->escape($this->element)."'"; + if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'"; + if ($source == 'internal') $sql.= " AND tc.source = 'internal'"; + if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'"; + $sql.= " AND tc.active=1"; + if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'"; + $sql.=" ORDER BY t.lastname ASC"; + + dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $num=$this->db->num_rows($resql); + $i=0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + + if (! $list) + { + $transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code; + $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); + $tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id, + 'nom'=>$obj->lastname, // For backward compatibility + 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact, + 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact); + } + else + { + $tab[$i]=$obj->id; + } + + $i++; + } + + return $tab; + } + else + { + $this->error=$this->db->lasterror(); + dol_print_error($this->db); + return -1; + } + } + + + /** + * Update status of a contact linked to object + * + * @param int $rowid Id of link between object and contact + * @return int <0 if KO, >=0 if OK + */ + function swapContactStatus($rowid) + { + $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,"; + $sql.= " tc.code, tc.libelle"; + //$sql.= ", s.fk_soc"; + $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)"; + //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid"; // Si contact de type external, alors il est lie a une societe + $sql.= " WHERE ec.rowid =".$rowid; + $sql.= " AND ec.fk_c_type_contact=tc.rowid"; + $sql.= " AND tc.element = '".$this->db->escape($this->element)."'"; + + dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $newstatut = ($obj->statut == 4) ? 5 : 4; + $result = $this->update_contact($rowid, $newstatut); + $this->db->free($resql); + return $result; + } + else + { + $this->error=$this->db->error(); + dol_print_error($this->db); + return -1; + } + + } + + /** + * Return array with list of possible values for type of contacts + * + * @param string $source 'internal', 'external' or 'all' + * @param string $order Sort order by : 'position', 'code', 'rowid'... + * @param int $option 0=Return array id->label, 1=Return array code->label + * @param int $activeonly 0=all status of contact, 1=only the active + * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE') + * @return array Array list of type of contacts (id->label if option=0, code->label if option=1) + */ + function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='') + { + global $langs; + + if (empty($order)) $order='position'; + if ($order == 'position') $order.=',code'; + + $tab = array(); + $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; + if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types + if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'"; + if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'"; + $sql.= $this->db->order($order,'ASC'); + + //print "sql=".$sql; + $resql=$this->db->query($sql); + if ($resql) + { + $num=$this->db->num_rows($resql); + $i=0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + + $transkey="TypeContact_".$this->element."_".$source."_".$obj->code; + $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); + if (empty($option)) $tab[$obj->rowid]=$libelle_type; + else $tab[$obj->code]=$libelle_type; + $i++; + } + return $tab; + } + else + { + $this->error=$this->db->lasterror(); + //dol_print_error($this->db); + return null; + } + } + + /** + * Return id of contacts for a source and a contact code. + * Example: contact client de facturation ('external', 'BILLING') + * Example: contact client de livraison ('external', 'SHIPPING') + * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL') + * + * @param string $source 'external' or 'internal' + * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ... + * @param int $status limited to a certain status + * @return array List of id for such contacts + */ + function getIdContact($source,$code,$status=0) + { + global $conf; + + $result=array(); + $i=0; + //cas particulier pour les expeditions + if($this->element=='shipping' && $this->origin_id != 0) { + $id=$this->origin_id; + $element='commande'; + } else { + $id=$this->id; + $element=$this->element; + } + + $sql = "SELECT ec.fk_socpeople"; + $sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,"; + if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,"; + if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,"; + $sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.= " WHERE ec.element_id = ".$id; + $sql.= " AND ec.fk_socpeople = c.rowid"; + if ($source == 'internal') $sql.= " AND c.entity IN (0,".$conf->entity.")"; + if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")"; + $sql.= " AND ec.fk_c_type_contact = tc.rowid"; + $sql.= " AND tc.element = '".$element."'"; + $sql.= " AND tc.source = '".$source."'"; + $sql.= " AND tc.code = '".$code."'"; + $sql.= " AND tc.active = 1"; + if ($status) $sql.= " AND ec.statut = ".$status; + + dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + while ($obj = $this->db->fetch_object($resql)) + { + $result[$i]=$obj->fk_socpeople; + $i++; + } + } + else + { + $this->error=$this->db->error(); + return null; + } + + return $result; + } + + /** + * Load object contact with id=$this->contactid into $this->contact + * + * @param int $contactid Id du contact. Use this->contactid if empty. + * @return int <0 if KO, >0 if OK + */ + function fetch_contact($contactid=null) + { + if (empty($contactid)) $contactid=$this->contactid; + + if (empty($contactid)) return 0; + + require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; + $contact = new Contact($this->db); + $result=$contact->fetch($contactid); + $this->contact = $contact; + return $result; + } + + /** + * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty + * + * @param int $force_thirdparty_id Force thirdparty id + * @return int <0 if KO, >0 if OK + */ + function fetch_thirdparty($force_thirdparty_id=0) + { + global $conf; + + if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) + return 0; + + require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; + + $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty); + if ($force_thirdparty_id) + $idtofetch = $force_thirdparty_id; + + if ($idtofetch) { + $thirdparty = new Societe($this->db); + $result = $thirdparty->fetch($idtofetch); + $this->thirdparty = $thirdparty; + + // Use first price level if level not defined for third party + if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) { + $this->thirdparty->price_level = 1; + } + + return $result; + } else + return -1; + } + + + /** + * Looks for an object with ref matching the wildcard provided + * It does only work when $this->table_ref_field is set + * + * @param string $ref Wildcard + * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO + */ + public function fetchOneLike($ref) + { + if (!$this->table_ref_field) { + return 0; + } + + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1'; + + $query = $this->db->query($sql); + + if (!$this->db->num_rows($query)) { + return 0; + } + + $result = $this->db->fetch_object($query); + + return $this->fetch($result->rowid); + } + + /** + * Load data for barcode into properties ->barcode_type* + * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but + * if it is not defined, ->element must be defined to know default barcode type. + * + * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded) + */ + function fetch_barcode() + { + global $conf; + + dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type); + + $idtype=$this->barcode_type; + if (empty($idtype) && $idtype != '0') // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined + { + if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + else if ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY; + else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING); + } + + if ($idtype > 0) + { + if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) // If data not already loaded + { + $sql = "SELECT rowid, code, libelle as label, coder"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; + $sql.= " WHERE rowid = ".$idtype; + dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $this->barcode_type = $obj->rowid; + $this->barcode_type_code = $obj->code; + $this->barcode_type_label = $obj->label; + $this->barcode_type_coder = $obj->coder; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + } + return 0; + } + + /** + * Charge le projet d'id $this->fk_project dans this->projet + * + * @return int <0 if KO, >=0 if OK + */ + function fetch_projet() + { + include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + + if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility + if (empty($this->fk_project)) return 0; + + $project = new Project($this->db); + $result = $project->fetch($this->fk_project); + + $this->projet = $project; // deprecated + $this->project = $project; + return $result; + } + + /** + * Charge le user d'id userid dans this->user + * + * @param int $userid Id du contact + * @return int <0 if KO, >0 if OK + */ + function fetch_user($userid) + { + $user = new User($this->db); + $result=$user->fetch($userid); + $this->user = $user; + return $result; + } + + /** + * Read linked origin object + * + * @return void + */ + function fetch_origin() + { + if ($this->origin == 'shipping') $this->origin = 'expedition'; + if ($this->origin == 'delivery') $this->origin = 'livraison'; + + $origin = $this->origin; + + $classname = ucfirst($origin); + $this->$origin = new $classname($this->db); + $this->$origin->fetch($this->origin_id); + } + + /** + * Load object from specific field + * + * @param string $table Table element or element line + * @param string $field Field selected + * @param string $key Import key + * @return int <0 if KO, >0 if OK + */ + function fetchObjectFrom($table,$field,$key) + { + global $conf; + + $result=false; + + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table; + $sql.= " WHERE ".$field." = '".$key."'"; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + $result = $this->fetch($row[0]); + } + + return $result; + } + + /** + * Getter generic. Load value from a specific field + * + * @param string $table Table of element or element line + * @param int $id Element id + * @param string $field Field selected + * @return int <0 if KO, >0 if OK + */ + function getValueFrom($table, $id, $field) + { + $result=false; + if (!empty($id) && !empty($field) && !empty($table)) { + $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table; + $sql.= " WHERE rowid = ".$id; + + dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + $result = $row[0]; + } + } + return $result; + } + + /** + * Setter generic. Update a specific field into database. + * Warning: Trigger is run only if param trigkey is provided. + * + * @param string $field Field to update + * @param mixed $value New value + * @param string $table To force other table element or element line (should not be used) + * @param int $id To force other object id (should not be used) + * @param string $format Data format ('text', 'date'). 'text' is used if not defined + * @param string $id_field To force rowid field name. 'rowid' is used if not defined + * @param User|string $fuser Update the user of last update field with this user. If not provided, current user is used except if value is 'none' + * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY') + * @return int <0 if KO, >0 if OK + */ + function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='') + { + global $user,$langs,$conf; + + if (empty($table)) $table=$this->table_element; + if (empty($id)) $id=$this->id; if (empty($format)) $format='text'; if (empty($id_field)) $id_field='rowid'; $error=0; - $this->db->begin(); + $this->db->begin(); - // Special case - if ($table == 'product' && $field == 'note_private') $field='note'; + // Special case + if ($table == 'product' && $field == 'note_private') $field='note'; - $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; - if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'"; - else if ($format == 'int') $sql.= $field." = ".$this->db->escape($value); - else if ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); - if (! empty($fuser) && is_object($fuser)) $sql.=", fk_user_modif = ".$fuser->id; - elseif (empty($fuser) || $fuser != 'none') $sql.=", fk_user_modif = ".$user->id; - $sql.= " WHERE ".$id_field." = ".$id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; + if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'"; + else if ($format == 'int') $sql.= $field." = ".$this->db->escape($value); + else if ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); + if (! empty($fuser) && is_object($fuser)) $sql.=", fk_user_modif = ".$fuser->id; + elseif (empty($fuser) || $fuser != 'none') $sql.=", fk_user_modif = ".$user->id; + $sql.= " WHERE ".$id_field." = ".$id; - dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($trigkey) - { - $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors - if ($result < 0) $error++; - } + dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($trigkey) + { + $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors + if ($result < 0) $error++; + } - if (! $error) - { - if (property_exists($this, $field)) $this->$field = $value; - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -2; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } - - /** - * Load properties id_previous and id_next - * - * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')" - * @param int $fieldid Name of field to use for the select MAX and MIN - * @param int $nodbprefix Do not include DB prefix to forge table name - * @return int <0 if KO, >0 if OK - */ - function load_previous_next_ref($filter, $fieldid, $nodbprefix=0) - { - global $user; - - if (! $this->table_element) - { - dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined"); - return -1; - } - - // this->ismultientitymanaged contains - // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - $alias = 's'; - if ($this->element == 'societe') $alias = 'te'; - - $sql = "SELECT MAX(te.".$fieldid.")"; - $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && empty($user->rights->societe->client->voir))) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; - $sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; - if (! empty($filter)) - { - if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility - $sql.=$filter; - } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; - - //print $filter.' '.$sql."
    "; - $result = $this->db->query($sql); - if (! $result) - { - $this->error=$this->db->lasterror(); - return -1; - } - $row = $this->db->fetch_row($result); - $this->ref_previous = $row[0]; - - - $sql = "SELECT MIN(te.".$fieldid.")"; - $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; - $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; - if (! empty($filter)) - { - if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility - $sql.=$filter; - } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; - // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null - - //print $sql."
    "; - $result = $this->db->query($sql); - if (! $result) - { - $this->error=$this->db->lasterror(); - return -2; - } - $row = $this->db->fetch_row($result); - $this->ref_next = $row[0]; - - return 1; - } - - - /** - * Return list of id of contacts of project - * - * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe) - * @return array Array of id of contacts (if source=external or internal) - * Array of id of third parties with at least one contact on project (if source=thirdparty) - */ - function getListContactId($source='external') - { - $contactAlreadySelected = array(); - $tab = $this->liste_contact(-1,$source); - $num=count($tab); - $i = 0; - while ($i < $num) - { - if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; - else $contactAlreadySelected[$i] = $tab[$i]['id']; - $i++; - } - return $contactAlreadySelected; - } - - - /** - * Link element with a project - * - * @param int $projectid Project id to link element to - * @return int <0 if KO, >0 if OK - */ - function setProject($projectid) - { - if (! $this->table_element) - { - dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - if ($this->table_element == 'actioncomm') - { - if ($projectid) $sql.= ' SET fk_project = '.$projectid; - else $sql.= ' SET fk_project = NULL'; - $sql.= ' WHERE id = '.$this->id; - } - else - { - if ($projectid) $sql.= ' SET fk_projet = '.$projectid; - else $sql.= ' SET fk_projet = NULL'; - $sql.= ' WHERE rowid = '.$this->id; - } - - dol_syslog(get_class($this)."::setProject", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->fk_project = $projectid; - return 1; - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Change the payments methods - * - * @param int $id Id of new payment method - * @return int >0 if OK, <0 if KO - */ - function setPaymentMethods($id) - { - dol_syslog(get_class($this).'::setPaymentMethods('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - // TODO uniformize field name - $fieldname = 'fk_mode_reglement'; - if ($this->element == 'societe') $fieldname = 'mode_reglement'; - if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$id; - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->mode_reglement_id = $id; - // for supplier - if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id; - return 1; - } - else - { - dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } + if (! $error) + { + if (property_exists($this, $field)) $this->$field = $value; + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -2; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } /** - * Change the multicurrency code - * - * @param string $code multicurrency code - * @return int >0 if OK, <0 if KO - */ - function setMulticurrencyCode($code) - { - dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - $fieldname = 'multicurrency_code'; + * Load properties id_previous and id_next by comparing $fieldid with $this->ref + * + * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')" + * @param string $fieldid Name of field to use for the select MAX and MIN + * @param int $nodbprefix Do not include DB prefix to forge table name + * @return int <0 if KO, >0 if OK + */ + function load_previous_next_ref($filter, $fieldid, $nodbprefix=0) + { + global $user; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'"; - $sql .= ' WHERE rowid='.$this->id; + if (! $this->table_element) + { + dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined"); + return -1; + } + if ($fieldid == 'none') return 1; - if ($this->db->query($sql)) - { - $this->multicurrency_code = $code; + // this->ismultientitymanaged contains + // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + $alias = 's'; + if ($this->element == 'societe') $alias = 'te'; + + $sql = "SELECT MAX(te.".$fieldid.")"; + $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; + $sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; + if (! empty($filter)) + { + if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility + $sql.=$filter; + } + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; + + //print 'filter = '.$filter.' -> '.$sql."
    "; + $result = $this->db->query($sql); + if (! $result) + { + $this->error=$this->db->lasterror(); + return -1; + } + $row = $this->db->fetch_row($result); + $this->ref_previous = $row[0]; + + + $sql = "SELECT MIN(te.".$fieldid.")"; + $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; + $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; + if (! empty($filter)) + { + if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility + $sql.=$filter; + } + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; + // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null + + //print $sql."
    "; + $result = $this->db->query($sql); + if (! $result) + { + $this->error=$this->db->lasterror(); + return -2; + } + $row = $this->db->fetch_row($result); + $this->ref_next = $row[0]; + + return 1; + } + + + /** + * Return list of id of contacts of project + * + * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe) + * @return array Array of id of contacts (if source=external or internal) + * Array of id of third parties with at least one contact on project (if source=thirdparty) + */ + function getListContactId($source='external') + { + $contactAlreadySelected = array(); + $tab = $this->liste_contact(-1,$source); + $num=count($tab); + $i = 0; + while ($i < $num) + { + if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; + else $contactAlreadySelected[$i] = $tab[$i]['id']; + $i++; + } + return $contactAlreadySelected; + } + + + /** + * Link element with a project + * + * @param int $projectid Project id to link element to + * @return int <0 if KO, >0 if OK + */ + function setProject($projectid) + { + if (! $this->table_element) + { + dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + if ($this->table_element == 'actioncomm') + { + if ($projectid) $sql.= ' SET fk_project = '.$projectid; + else $sql.= ' SET fk_project = NULL'; + $sql.= ' WHERE id = '.$this->id; + } + else + { + if ($projectid) $sql.= ' SET fk_projet = '.$projectid; + else $sql.= ' SET fk_projet = NULL'; + $sql.= ' WHERE rowid = '.$this->id; + } + + dol_syslog(get_class($this)."::setProject", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->fk_project = $projectid; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Change the payments methods + * + * @param int $id Id of new payment method + * @return int >0 if OK, <0 if KO + */ + function setPaymentMethods($id) + { + dol_syslog(get_class($this).'::setPaymentMethods('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + // TODO uniformize field name + $fieldname = 'fk_mode_reglement'; + if ($this->element == 'societe') $fieldname = 'mode_reglement'; + if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier'; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.$id; + $sql .= ' WHERE rowid='.$this->id; + + if ($this->db->query($sql)) + { + $this->mode_reglement_id = $id; + // for supplier + if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id; + return 1; + } + else + { + dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible'); + $this->error='Status of the object is incompatible '.$this->statut; + return -2; + } + } + + /** + * Change the multicurrency code + * + * @param string $code multicurrency code + * @return int >0 if OK, <0 if KO + */ + function setMulticurrencyCode($code) + { + dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + $fieldname = 'multicurrency_code'; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'"; + $sql .= ' WHERE rowid='.$this->id; + + if ($this->db->query($sql)) + { + $this->multicurrency_code = $code; list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code); if ($rate) $this->setMulticurrencyRate($rate); - return 1; - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } + return 1; + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible'); + $this->error='Status of the object is incompatible '.$this->statut; + return -2; + } + } /** - * Change the multicurrency rate - * - * @param double $rate multicurrency rate + * Change the multicurrency rate + * + * @param double $rate multicurrency rate * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency - * @return int >0 if OK, <0 if KO - */ - function setMulticurrencyRate($rate, $mode=1) - { - dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - $fieldname = 'multicurrency_tx'; + * @return int >0 if OK, <0 if KO + */ + function setMulticurrencyRate($rate, $mode=1) + { + dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + $fieldname = 'multicurrency_tx'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$rate; - $sql .= ' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.$rate; + $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { - $this->multicurrency_tx = $rate; + if ($this->db->query($sql)) + { + $this->multicurrency_tx = $rate; // Update line price if (!empty($this->lines)) @@ -1587,249 +1678,249 @@ abstract class CommonObject } } - return 1; - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } + return 1; + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible'); + $this->error='Status of the object is incompatible '.$this->statut; + return -2; + } + } - /** - * Change the payments terms - * - * @param int $id Id of new payment terms - * @return int >0 if OK, <0 if KO - */ - function setPaymentTerms($id) - { - dol_syslog(get_class($this).'::setPaymentTerms('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - // TODO uniformize field name - $fieldname = 'fk_cond_reglement'; - if ($this->element == 'societe') $fieldname = 'cond_reglement'; - if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier'; + /** + * Change the payments terms + * + * @param int $id Id of new payment terms + * @return int >0 if OK, <0 if KO + */ + function setPaymentTerms($id) + { + dol_syslog(get_class($this).'::setPaymentTerms('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + // TODO uniformize field name + $fieldname = 'fk_cond_reglement'; + if ($this->element == 'societe') $fieldname = 'cond_reglement'; + if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$id; - $sql .= ' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.$id; + $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { - $this->cond_reglement_id = $id; - // for supplier - if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id; - $this->cond_reglement = $id; // for compatibility - return 1; - } - else - { - dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } + if ($this->db->query($sql)) + { + $this->cond_reglement_id = $id; + // for supplier + if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id; + $this->cond_reglement = $id; // for compatibility + return 1; + } + else + { + dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible'); + $this->error='Status of the object is incompatible '.$this->statut; + return -2; + } + } - /** - * Define delivery address - * @deprecated - * - * @param int $id Address id - * @return int <0 si ko, >0 si ok - */ - function setDeliveryAddress($id) - { - $fieldname = 'fk_delivery_address'; - if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address'; + /** + * Define delivery address + * @deprecated + * + * @param int $id Address id + * @return int <0 si ko, >0 si ok + */ + function setDeliveryAddress($id) + { + $fieldname = 'fk_delivery_address'; + if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address'; - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - if ($this->db->query($sql)) - { - $this->fk_delivery_address = $id; - return 1; - } - else - { - $this->error=$this->db->error(); - dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error); - return -1; - } - } + if ($this->db->query($sql)) + { + $this->fk_delivery_address = $id; + return 1; + } + else + { + $this->error=$this->db->error(); + dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error); + return -1; + } + } - /** - * Change the shipping method - * - * @param int $shipping_method_id Id of shipping method - * @return int 1 if OK, 0 if KO - */ - function setShippingMethod($shipping_method_id) - { - if (! $this->table_element) { - dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - if ($shipping_method_id<0) $shipping_method_id='NULL'; - dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')'); + /** + * Change the shipping method + * + * @param int $shipping_method_id Id of shipping method + * @return int 1 if OK, 0 if KO + */ + function setShippingMethod($shipping_method_id) + { + if (! $this->table_element) { + dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + if ($shipping_method_id<0) $shipping_method_id='NULL'; + dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')'); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_shipping_method = ".$shipping_method_id; - $sql.= " WHERE rowid=".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_shipping_method = ".$shipping_method_id; + $sql.= " WHERE rowid=".$this->id; - if ($this->db->query($sql)) { - $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id; - return 1; - } else { - dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG); - $this->error=$this->db->error(); - return 0; - } - } + if ($this->db->query($sql)) { + $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id; + return 1; + } else { + dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG); + $this->error=$this->db->error(); + return 0; + } + } - /** - * Change the warehouse - * - * @param int $warehouse_id Id of warehouse - * @return int 1 if OK, 0 if KO - */ - function setWarehouse($warehouse_id) - { - if (! $this->table_element) { - dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - if ($warehouse_id<0) $warehouse_id='NULL'; - dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')'); + /** + * Change the warehouse + * + * @param int $warehouse_id Id of warehouse + * @return int 1 if OK, 0 if KO + */ + function setWarehouse($warehouse_id) + { + if (! $this->table_element) { + dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + if ($warehouse_id<0) $warehouse_id='NULL'; + dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')'); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_warehouse = ".$warehouse_id; - $sql.= " WHERE rowid=".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_warehouse = ".$warehouse_id; + $sql.= " WHERE rowid=".$this->id; - if ($this->db->query($sql)) { - $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id; - return 1; - } else { - dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG); - $this->error=$this->db->error(); - return 0; - } - } + if ($this->db->query($sql)) { + $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id; + return 1; + } else { + dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG); + $this->error=$this->db->error(); + return 0; + } + } - /** - * Set last model used by doc generator - * - * @param User $user User object that make change - * @param string $modelpdf Modele name - * @return int <0 if KO, >0 if OK - */ - function setDocModel($user, $modelpdf) - { - if (! $this->table_element) - { - dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR); - return -1; - } + /** + * Set last model used by doc generator + * + * @param User $user User object that make change + * @param string $modelpdf Modele name + * @return int <0 if KO, >0 if OK + */ + function setDocModel($user, $modelpdf) + { + if (! $this->table_element) + { + dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR); + return -1; + } - $newmodelpdf=dol_trunc($modelpdf,255); + $newmodelpdf=dol_trunc($modelpdf,255); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'"; - $sql.= " WHERE rowid = ".$this->id; - // if ($this->element == 'facture') $sql.= " AND fk_statut < 2"; - // if ($this->element == 'propal') $sql.= " AND fk_statut = 0"; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'"; + $sql.= " WHERE rowid = ".$this->id; + // if ($this->element == 'facture') $sql.= " AND fk_statut < 2"; + // if ($this->element == 'propal') $sql.= " AND fk_statut = 0"; - dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->modelpdf=$modelpdf; - return 1; - } - else - { - dol_print_error($this->db); - return 0; - } - } + dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->modelpdf=$modelpdf; + return 1; + } + else + { + dol_print_error($this->db); + return 0; + } + } - /** - * Change the bank account - * - * @param int $fk_account Id of bank account - * @return int 1 if OK, 0 if KO - */ - function setBankAccount($fk_account) - { - if (! $this->table_element) { - dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - if ($fk_account<0) $fk_account='NULL'; - dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')'); + /** + * Change the bank account + * + * @param int $fk_account Id of bank account + * @return int 1 if OK, 0 if KO + */ + function setBankAccount($fk_account) + { + if (! $this->table_element) { + dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + if ($fk_account<0) $fk_account='NULL'; + dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')'); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_account = ".$fk_account; - $sql.= " WHERE rowid=".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_account = ".$fk_account; + $sql.= " WHERE rowid=".$this->id; - if ($this->db->query($sql)) { - $this->fk_account = ($fk_account=='NULL')?null:$fk_account; - return 1; - } else { - dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return 0; - } - } + if ($this->db->query($sql)) { + $this->fk_account = ($fk_account=='NULL')?null:$fk_account; + return 1; + } else { + dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return 0; + } + } // TODO: Move line related operations to CommonObjectLine? - /** - * Save a new position (field rang) for details lines. - * You can choose to set position for lines with already a position or lines without any position defined. - * - * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines. - * @param string $rowidorder ASC or DESC - * @param boolean $fk_parent_line Table with fk_parent_line field or not - * @return int <0 if KO, >0 if OK - */ - function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true) - { - if (! $this->table_element_line) - { - dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR); - return -1; - } - if (! $this->fk_element) - { - dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR); - return -1; - } + /** + * Save a new position (field rang) for details lines. + * You can choose to set position for lines with already a position or lines without any position defined. + * + * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines. + * @param string $rowidorder ASC or DESC + * @param boolean $fk_parent_line Table with fk_parent_line field or not + * @return int <0 if KO, >0 if OK + */ + function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true) + { + if (! $this->table_element_line) + { + dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR); + return -1; + } + if (! $this->fk_element) + { + dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR); + return -1; + } - // Count number of lines to reorder (according to choice $renum) - $nl=0; - $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line; + // Count number of lines to reorder (according to choice $renum) + $nl=0; + $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line; $sql.= ' WHERE '.$this->fk_element.'='.$this->id; if (! $renum) $sql.= ' AND rang = 0'; if ($renum) $sql.= ' AND rang <> 0'; @@ -1924,44 +2015,44 @@ abstract class CommonObject return $rows; } - /** - * Update a line to have a lower rank - * - * @param int $rowid Id of line - * @param boolean $fk_parent_line Table with fk_parent_line field or not - * @return void - */ - function line_up($rowid, $fk_parent_line=true) - { - $this->line_order(false, 'ASC', $fk_parent_line); + /** + * Update a line to have a lower rank + * + * @param int $rowid Id of line + * @param boolean $fk_parent_line Table with fk_parent_line field or not + * @return void + */ + function line_up($rowid, $fk_parent_line=true) + { + $this->line_order(false, 'ASC', $fk_parent_line); - // Get rang of line - $rang = $this->getRangOfLine($rowid); + // Get rang of line + $rang = $this->getRangOfLine($rowid); - // Update position of line - $this->updateLineUp($rowid, $rang); - } + // Update position of line + $this->updateLineUp($rowid, $rang); + } - /** - * Update a line to have a higher rank - * - * @param int $rowid Id of line - * @param boolean $fk_parent_line Table with fk_parent_line field or not - * @return void - */ - function line_down($rowid, $fk_parent_line=true) - { - $this->line_order(false, 'ASC', $fk_parent_line); + /** + * Update a line to have a higher rank + * + * @param int $rowid Id of line + * @param boolean $fk_parent_line Table with fk_parent_line field or not + * @return void + */ + function line_down($rowid, $fk_parent_line=true) + { + $this->line_order(false, 'ASC', $fk_parent_line); - // Get rang of line - $rang = $this->getRangOfLine($rowid); + // Get rang of line + $rang = $this->getRangOfLine($rowid); - // Get max value for rang - $max = $this->line_max(); + // Get max value for rang + $max = $this->line_max(); - // Update position of line - $this->updateLineDown($rowid, $rang, $max); - } + // Update position of line + $this->updateLineDown($rowid, $rang, $max); + } /** * Update position of line (rang) @@ -1972,8 +2063,8 @@ abstract class CommonObject */ function updateRangOfLine($rowid,$rang) { - $fieldposition = 'rang'; - if ($this->table_element_line == 'ecm_files') $fieldposition = 'position'; + $fieldposition = 'rang'; + if ($this->table_element_line == 'ecm_files') $fieldposition = 'position'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang; $sql.= ' WHERE rowid = '.$rowid; @@ -1985,400 +2076,426 @@ abstract class CommonObject } } - /** - * Update position of line with ajax (rang) - * - * @param array $rows Array of rows - * @return void - */ - function line_ajaxorder($rows) - { - $num = count($rows); - for ($i = 0 ; $i < $num ; $i++) - { - $this->updateRangOfLine($rows[$i], ($i+1)); - } - } + /** + * Update position of line with ajax (rang) + * + * @param array $rows Array of rows + * @return void + */ + function line_ajaxorder($rows) + { + $num = count($rows); + for ($i = 0 ; $i < $num ; $i++) + { + $this->updateRangOfLine($rows[$i], ($i+1)); + } + } - /** - * Update position of line up (rang) - * - * @param int $rowid Id of line - * @param int $rang Position - * @return void - */ - function updateLineUp($rowid,$rang) - { - if ($rang > 1 ) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang ; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.($rang - 1); - if ($this->db->query($sql) ) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang - 1); - $sql.= ' WHERE rowid = '.$rowid; - if (! $this->db->query($sql) ) - { - dol_print_error($this->db); - } - } - else - { - dol_print_error($this->db); - } - } - } + /** + * Update position of line up (rang) + * + * @param int $rowid Id of line + * @param int $rang Position + * @return void + */ + function updateLineUp($rowid,$rang) + { + if ($rang > 1 ) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang ; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql.= ' AND rang = '.($rang - 1); + if ($this->db->query($sql) ) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang - 1); + $sql.= ' WHERE rowid = '.$rowid; + if (! $this->db->query($sql) ) + { + dol_print_error($this->db); + } + } + else + { + dol_print_error($this->db); + } + } + } - /** - * Update position of line down (rang) - * - * @param int $rowid Id of line - * @param int $rang Position - * @param int $max Max - * @return void - */ - function updateLineDown($rowid,$rang,$max) - { - if ($rang < $max) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.($rang+1); - if ($this->db->query($sql) ) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang+1); - $sql.= ' WHERE rowid = '.$rowid; - if (! $this->db->query($sql) ) - { - dol_print_error($this->db); - } - } - else - { - dol_print_error($this->db); - } - } - } + /** + * Update position of line down (rang) + * + * @param int $rowid Id of line + * @param int $rang Position + * @param int $max Max + * @return void + */ + function updateLineDown($rowid,$rang,$max) + { + if ($rang < $max) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql.= ' AND rang = '.($rang+1); + if ($this->db->query($sql) ) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang+1); + $sql.= ' WHERE rowid = '.$rowid; + if (! $this->db->query($sql) ) + { + dol_print_error($this->db); + } + } + else + { + dol_print_error($this->db); + } + } + } - /** - * Get position of line (rang) - * - * @param int $rowid Id of line - * @return int Value of rang in table of lines - */ - function getRangOfLine($rowid) - { - $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE rowid ='.$rowid; + /** + * Get position of line (rang) + * + * @param int $rowid Id of line + * @return int Value of rang in table of lines + */ + function getRangOfLine($rowid) + { + $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE rowid ='.$rowid; - dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } + dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + return $row[0]; + } + } - /** - * Get rowid of the line relative to its position - * - * @param int $rang Rang value - * @return int Rowid of the line - */ - function getIdOfLine($rang) - { - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.$rang; - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } + /** + * Get rowid of the line relative to its position + * + * @param int $rang Rang value + * @return int Rowid of the line + */ + function getIdOfLine($rang) + { + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql.= ' AND rang = '.$rang; + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + return $row[0]; + } + } - /** - * Get max value used for position of line (rang) - * - * @param int $fk_parent_line Parent line id - * @return int Max value of rang in table of lines - */ - function line_max($fk_parent_line=0) - { - // Search the last rang with fk_parent_line - if ($fk_parent_line) - { - $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND fk_parent_line = '.$fk_parent_line; + /** + * Get max value used for position of line (rang) + * + * @param int $fk_parent_line Parent line id + * @return int Max value of rang in table of lines + */ + function line_max($fk_parent_line=0) + { + // Search the last rang with fk_parent_line + if ($fk_parent_line) + { + $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql.= ' AND fk_parent_line = '.$fk_parent_line; - dol_syslog(get_class($this)."::line_max", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - if (! empty($row[0])) - { - return $row[0]; - } - else - { - return $this->getRangOfLine($fk_parent_line); - } - } - } - // If not, search the last rang of element - else - { - $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + dol_syslog(get_class($this)."::line_max", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + if (! empty($row[0])) + { + return $row[0]; + } + else + { + return $this->getRangOfLine($fk_parent_line); + } + } + } + // If not, search the last rang of element + else + { + $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - dol_syslog(get_class($this)."::line_max", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } - } + dol_syslog(get_class($this)."::line_max", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + return $row[0]; + } + } + } - /** - * Update external ref of element - * - * @param string $ref_ext Update field ref_ext - * @return int <0 if KO, >0 if OK - */ - function update_ref_ext($ref_ext) - { - if (! $this->table_element) - { - dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR); - return -1; - } + /** + * Update external ref of element + * + * @param string $ref_ext Update field ref_ext + * @return int <0 if KO, >0 if OK + */ + function update_ref_ext($ref_ext) + { + if (! $this->table_element) + { + dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR); + return -1; + } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'"; - $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'"; + $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id; - dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->ref_ext = $ref_ext; - return 1; - } - else - { - $this->error=$this->db->error(); - return -1; - } - } + dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->ref_ext = $ref_ext; + return 1; + } + else + { + $this->error=$this->db->error(); + return -1; + } + } - /** - * Update note of element - * - * @param string $note New value for note - * @param string $suffix '', '_public' or '_private' - * @return int <0 if KO, >0 if OK - */ - function update_note($note,$suffix='') - { - global $user; + /** + * Update note of element + * + * @param string $note New value for note + * @param string $suffix '', '_public' or '_private' + * @return int <0 if KO, >0 if OK + */ + function update_note($note,$suffix='') + { + global $user; - if (! $this->table_element) - { - dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR); - return -1; - } + if (! $this->table_element) + { + dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR); + return -1; + } if (! in_array($suffix,array('','_public','_private'))) { - dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR); + dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR); return -2; } - // Special cas - //var_dump($this->table_element);exit; + // Special cas + //var_dump($this->table_element);exit; if ($this->table_element == 'product') $suffix=''; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL"); - $sql.= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))?"fk_user_mod":"fk_user_modif")." = ".$user->id; - $sql.= " WHERE rowid =". $this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL"); + $sql.= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))?"fk_user_mod":"fk_user_modif")." = ".$user->id; + $sql.= " WHERE rowid =". $this->id; - dol_syslog(get_class($this)."::update_note", LOG_DEBUG); - if ($this->db->query($sql)) - { - if ($suffix == '_public') $this->note_public = $note; - else if ($suffix == '_private') $this->note_private = $note; - else - { - $this->note = $note; // deprecated - $this->note_private = $note; - } - return 1; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } + dol_syslog(get_class($this)."::update_note", LOG_DEBUG); + if ($this->db->query($sql)) + { + if ($suffix == '_public') $this->note_public = $note; + else if ($suffix == '_private') $this->note_private = $note; + else + { + $this->note = $note; // deprecated + $this->note_private = $note; + } + return 1; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } - /** - * Update public note (kept for backward compatibility) - * - * @param string $note New value for note - * @return int <0 if KO, >0 if OK - * @deprecated - * @see update_note() - */ - function update_note_public($note) - { - return $this->update_note($note,'_public'); - } + /** + * Update public note (kept for backward compatibility) + * + * @param string $note New value for note + * @return int <0 if KO, >0 if OK + * @deprecated + * @see update_note() + */ + function update_note_public($note) + { + return $this->update_note($note,'_public'); + } - /** - * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines). - * Must be called at end of methods addline or updateline. - * - * @param int $exclspec >0 = Exclude special product (product_type=9) - * @param string $roundingadjust 'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total - * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object. - * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object. - * @return int <0 if KO, >0 if OK - */ - function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null) - { - global $conf; + /** + * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines). + * Must be called at end of methods addline or updateline. + * + * @param int $exclspec >0 = Exclude special product (product_type=9) + * @param string $roundingadjust 'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total + * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object. + * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object. + * @return int <0 if KO, >0 if OK + */ + function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null) + { + global $conf; - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield) + $MODULE = ""; + if ($this->element == 'propal') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL"; + elseif ($this->element == 'order') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER"; + elseif ($this->element == 'facture') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE"; + elseif ($this->element == 'facture_fourn') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE"; + elseif ($this->element == 'order_supplier') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER"; + elseif ($this->element == 'supplier_proposal') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL"; - if ($roundingadjust == '-1') $roundingadjust='auto'; // For backward compatibility + if (! empty($MODULE)) { + if (! empty($conf->global->$MODULE)) { + $modsactivated = explode(',', $conf->global->$MODULE); + foreach ($modsactivated as $mod) { + if ($conf->$mod->enabled) + return 1; // update was disabled by specific setup + } + } + } - $forcedroundingmode=$roundingadjust; - if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND; - elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - $error=0; + if ($roundingadjust == '-1') $roundingadjust='auto'; // For backward compatibility - $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1; + $forcedroundingmode=$roundingadjust; + if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND; + elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0'; - // Define constants to find lines to sum - $fieldtva='total_tva'; - $fieldlocaltax1='total_localtax1'; - $fieldlocaltax2='total_localtax2'; - $fieldup='subprice'; - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') - { - $fieldtva='tva'; - $fieldup='pu_ht'; - } - if ($this->element == 'expensereport') - { - $fieldup='value_unit'; - } + $error=0; - $sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,'; - $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type'; - if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent'; - $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - if ($exclspec) - { - $product_field='product_type'; - if ($this->table_element_line == 'contratdet') $product_field=''; // contratdet table has no product_type field - if ($product_field) $sql.= ' AND '.$product_field.' <> 9'; - } - $sql.= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used + $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1; - dol_syslog(get_class($this)."::update_price", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->total_ht = 0; - $this->total_tva = 0; - $this->total_localtax1 = 0; - $this->total_localtax2 = 0; - $this->total_ttc = 0; - $total_ht_by_vats = array(); - $total_tva_by_vats = array(); - $total_ttc_by_vats = array(); + // Define constants to find lines to sum + $fieldtva='total_tva'; + $fieldlocaltax1='total_localtax1'; + $fieldlocaltax2='total_localtax2'; + $fieldup='subprice'; + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') + { + $fieldtva='tva'; + $fieldup='pu_ht'; + } + if ($this->element == 'expensereport') + { + $fieldup='value_unit'; + } + + $sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,'; + $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type'; + if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent'; + $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + if ($exclspec) + { + $product_field='product_type'; + if ($this->table_element_line == 'contratdet') $product_field=''; // contratdet table has no product_type field + if ($product_field) $sql.= ' AND '.$product_field.' <> 9'; + } + $sql.= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used + + dol_syslog(get_class($this)."::update_price", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->total_ht = 0; + $this->total_tva = 0; + $this->total_localtax1 = 0; + $this->total_localtax2 = 0; + $this->total_ttc = 0; + $total_ht_by_vats = array(); + $total_tva_by_vats = array(); + $total_ttc_by_vats = array(); $this->multicurrency_total_ht = 0; - $this->multicurrency_total_tva = 0; - $this->multicurrency_total_ttc = 0; + $this->multicurrency_total_tva = 0; + $this->multicurrency_total_ttc = 0; - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none' - if ($forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto' - { - $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx); - $tmpcal=calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx); - $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); - if ($diff) - { - $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid; - dol_syslog('We found unconsistent data into detailed line (difference of '.$diff.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); - $resqlfix=$this->db->query($sqlfix); - if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); - $obj->total_tva = $tmpcal[1]; - $obj->total_ttc = $tmpcal[2]; - // - } - } + // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none' + if ($forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto' + { + $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx); + $tmpcal=calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx); + $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); + if ($diff) + { + $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid; + dol_syslog('We found unconsistent data into detailed line (difference of '.$diff.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); + $resqlfix=$this->db->query($sqlfix); + if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); + $obj->total_tva = $tmpcal[1]; + $obj->total_ttc = $tmpcal[2]; + // + } + } - $this->total_ht += $obj->total_ht; // The field visible at end of line detail - $this->total_tva += $obj->total_tva; - $this->total_localtax1 += $obj->total_localtax1; - $this->total_localtax2 += $obj->total_localtax2; - $this->total_ttc += $obj->total_ttc; - $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail - $this->multicurrency_total_tva += $obj->multicurrency_total_tva; - $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc; + $this->total_ht += $obj->total_ht; // The field visible at end of line detail + $this->total_tva += $obj->total_tva; + $this->total_localtax1 += $obj->total_localtax1; + $this->total_localtax2 += $obj->total_localtax2; + $this->total_ttc += $obj->total_ttc; + $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail + $this->multicurrency_total_tva += $obj->multicurrency_total_tva; + $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc; - if (! isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate]=0; - if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0; - if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0; - $total_ht_by_vats[$obj->vatrate] += $obj->total_ht; - $total_tva_by_vats[$obj->vatrate] += $obj->total_tva; - $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc; + if (! isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate]=0; + if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0; + if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0; + $total_ht_by_vats[$obj->vatrate] += $obj->total_ht; + $total_tva_by_vats[$obj->vatrate] += $obj->total_tva; + $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc; - if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency - { - $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1); - $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1); - //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."
    \n"; - if ($diff) - { - if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; } - $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid; - dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); - $resqlfix=$this->db->query($sqlfix); - if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); - $this->total_tva -= $diff; - $this->total_ttc -= $diff; - $total_tva_by_vats[$obj->vatrate] -= $diff; - $total_ttc_by_vats[$obj->vatrate] -= $diff; + if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency + { + $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1); + $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1); + //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."
    \n"; + if ($diff) + { + if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; } + $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid; + dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); + $resqlfix=$this->db->query($sqlfix); + if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); + $this->total_tva -= $diff; + $this->total_ttc -= $diff; + $total_tva_by_vats[$obj->vatrate] -= $diff; + $total_ttc_by_vats[$obj->vatrate] -= $diff; - } - } + } + } - $i++; - } + $i++; + } - // Add revenue stamp to total - $this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0; - $this->multicurrency_total_ttc += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0; + // Add revenue stamp to total + $this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0; + $this->multicurrency_total_ttc += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0; // Situations totals - if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits')) { + if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits')) + { $prev_sits = $this->get_prev_sits(); foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch. @@ -2393,93 +2510,93 @@ abstract class CommonObject } } - $this->db->free($resql); + $this->db->free($resql); - // Now update global field total_ht, total_ttc and tva - $fieldht='total_ht'; - $fieldtva='tva'; - $fieldlocaltax1='localtax1'; - $fieldlocaltax2='localtax2'; - $fieldttc='total_ttc'; - // Specific code for backward compatibility with old field names - if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total'; - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva'; - if ($this->element == 'propal') $fieldttc='total'; - if ($this->element == 'expensereport') $fieldtva='total_tva'; - if ($this->element == 'supplier_proposal') $fieldttc='total'; + // Now update global field total_ht, total_ttc and tva + $fieldht='total_ht'; + $fieldtva='tva'; + $fieldlocaltax1='localtax1'; + $fieldlocaltax2='localtax2'; + $fieldttc='total_ttc'; + // Specific code for backward compatibility with old field names + if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total'; + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva'; + if ($this->element == 'propal') $fieldttc='total'; + if ($this->element == 'expensereport') $fieldtva='total_tva'; + if ($this->element == 'supplier_proposal') $fieldttc='total'; - if (empty($nodatabaseupdate)) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; - $sql .= " ".$fieldht."='".price2num($this->total_ht)."',"; - $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',"; - $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',"; - $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',"; - $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'"; - $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'"; - $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'"; - $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'"; - $sql .= ' WHERE rowid = '.$this->id; + if (empty($nodatabaseupdate)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; + $sql .= " ".$fieldht."='".price2num($this->total_ht)."',"; + $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',"; + $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',"; + $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',"; + $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'"; + $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'"; + $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'"; + $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'"; + $sql .= ' WHERE rowid = '.$this->id; - //print "xx".$sql; - dol_syslog(get_class($this)."::update_price", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - $error++; - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); - } - } + //print "xx".$sql; + dol_syslog(get_class($this)."::update_price", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) + { + $error++; + $this->error=$this->db->lasterror(); + $this->errors[]=$this->db->lasterror(); + } + } - if (! $error) - { - return 1; - } - else - { - return -1; - } - } - else - { - dol_print_error($this->db,'Bad request in update_price'); - return -1; - } - } + if (! $error) + { + return 1; + } + else + { + return -1; + } + } + else + { + dol_print_error($this->db,'Bad request in update_price'); + return -1; + } + } - /** - * Add objects linked in llx_element_element. - * - * @param string $origin Linked element type - * @param int $origin_id Linked element id - * @return int <=0 if KO, >0 if OK - * @see fetchObjectLinked, updateObjectLinked, deleteObjectLinked - */ - function add_object_linked($origin=null, $origin_id=null) - { - $origin = (! empty($origin) ? $origin : $this->origin); - $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id); + /** + * Add objects linked in llx_element_element. + * + * @param string $origin Linked element type + * @param int $origin_id Linked element id + * @return int <=0 if KO, >0 if OK + * @see fetchObjectLinked, updateObjectLinked, deleteObjectLinked + */ + function add_object_linked($origin=null, $origin_id=null) + { + $origin = (! empty($origin) ? $origin : $this->origin); + $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id); - // Special case - if ($origin == 'order') $origin='commande'; - if ($origin == 'invoice') $origin='facture'; + // Special case + if ($origin == 'order') $origin='commande'; + if ($origin == 'invoice') $origin='facture'; - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $origin_id; - $sql.= ", '".$origin."'"; - $sql.= ", ".$this->id; - $sql.= ", '".$this->element."'"; - $sql.= ")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; + $sql.= "fk_source"; + $sql.= ", sourcetype"; + $sql.= ", fk_target"; + $sql.= ", targettype"; + $sql.= ") VALUES ("; + $sql.= $origin_id; + $sql.= ", '".$this->db->escape($origin)."'"; + $sql.= ", ".$this->id; + $sql.= ", '".$this->db->escape($this->element)."'"; + $sql.= ")"; - dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG); + dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG); if ($this->db->query($sql)) { $this->db->commit(); @@ -2493,263 +2610,263 @@ abstract class CommonObject } } - /** - * Fetch array of objects linked to current object. Links are loaded into this->linkedObjects array and this->linkedObjectsIds - * Possible usage for parameters: - * - all parameters empty -> we look all link to current object (current object can be source or target) - * - source id+type -> will get target list linked to source - * - target id+type -> will get source list linked to target - * - source id+type + target type -> will get target list of the type - * - target id+type + target source -> will get source list of the type - * - * @param int $sourceid Object source id (if not defined, id of object) - * @param string $sourcetype Object source type (if not defined, element name of object) - * @param int $targetid Object target id (if not defined, id of object) - * @param string $targettype Object target type (if not defined, elemennt name of object) - * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided - * @param int $alsosametype 0=Return only links to object that differs from source. 1=Include also link to objects of same type. - * @return void - * @see add_object_linked, updateObjectLinked, deleteObjectLinked - */ + /** + * Fetch array of objects linked to current object. Links are loaded into this->linkedObjects array and this->linkedObjectsIds + * Possible usage for parameters: + * - all parameters empty -> we look all link to current object (current object can be source or target) + * - source id+type -> will get target list linked to source + * - target id+type -> will get source list linked to target + * - source id+type + target type -> will get target list of the type + * - target id+type + target source -> will get source list of the type + * + * @param int $sourceid Object source id (if not defined, id of object) + * @param string $sourcetype Object source type (if not defined, element name of object) + * @param int $targetid Object target id (if not defined, id of object) + * @param string $targettype Object target type (if not defined, elemennt name of object) + * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided + * @param int $alsosametype 0=Return only links to object that differs from source. 1=Include also link to objects of same type. + * @return void + * @see add_object_linked, updateObjectLinked, deleteObjectLinked + */ function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1) - { - global $conf; + { + global $conf; - $this->linkedObjectsIds=array(); - $this->linkedObjects=array(); + $this->linkedObjectsIds=array(); + $this->linkedObjects=array(); - $justsource=false; - $justtarget=false; - $withtargettype=false; - $withsourcetype=false; + $justsource=false; + $justtarget=false; + $withtargettype=false; + $withsourcetype=false; - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid)) - { - $justsource=true; // the source (id and type) is a search criteria - if (! empty($targettype)) $withtargettype=true; - } - if (! empty($targetid) && ! empty($targettype) && empty($sourceid)) - { - $justtarget=true; // the target (id and type) is a search criteria - if (! empty($sourcetype)) $withsourcetype=true; - } + if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid)) + { + $justsource=true; // the source (id and type) is a search criteria + if (! empty($targettype)) $withtargettype=true; + } + if (! empty($targetid) && ! empty($targettype) && empty($sourceid)) + { + $justtarget=true; // the target (id and type) is a search criteria + if (! empty($sourcetype)) $withsourcetype=true; + } - $sourceid = (! empty($sourceid) ? $sourceid : $this->id); - $targetid = (! empty($targetid) ? $targetid : $this->id); - $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element); - $targettype = (! empty($targettype) ? $targettype : $this->element); + $sourceid = (! empty($sourceid) ? $sourceid : $this->id); + $targetid = (! empty($targetid) ? $targetid : $this->id); + $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element); + $targettype = (! empty($targettype) ? $targettype : $this->element); - /*if (empty($sourceid) && empty($targetid)) + /*if (empty($sourceid) && empty($targetid)) { dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR); return -1; }*/ - // Links between objects are stored in table element_element - $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element'; - $sql.= " WHERE "; - if ($justsource || $justtarget) - { - if ($justsource) - { - $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'"; - if ($withtargettype) $sql.= " AND targettype = '".$targettype."'"; - } - else if ($justtarget) - { - $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'"; - if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'"; - } - } - else + // Links between objects are stored in table element_element + $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element'; + $sql.= " WHERE "; + if ($justsource || $justtarget) { - $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; - $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; - } - $sql .= ' ORDER BY sourcetype'; - //print $sql; + if ($justsource) + { + $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'"; + if ($withtargettype) $sql.= " AND targettype = '".$targettype."'"; + } + else if ($justtarget) + { + $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'"; + if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'"; + } + } + else + { + $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; + $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; + } + $sql .= ' ORDER BY sourcetype'; + //print $sql; - dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - if ($justsource || $justtarget) - { - if ($justsource) - { - $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; - } - else if ($justtarget) - { - $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; - } - } - else - { - if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) - { - $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; - } - if ($obj->fk_target == $targetid && $obj->targettype == $targettype) - { - $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; - } - } - $i++; - } + dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + if ($justsource || $justtarget) + { + if ($justsource) + { + $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; + } + else if ($justtarget) + { + $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; + } + } + else + { + if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) + { + $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; + } + if ($obj->fk_target == $targetid && $obj->targettype == $targettype) + { + $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; + } + } + $i++; + } - if (! empty($this->linkedObjectsIds)) - { - foreach($this->linkedObjectsIds as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...) - { - // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...) - $module = $element = $subelement = $objecttype; - if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier' - && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs)) - { - $module = $element = $regs[1]; - $subelement = $regs[2]; - } + if (! empty($this->linkedObjectsIds)) + { + foreach($this->linkedObjectsIds as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...) + { + // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...) + $module = $element = $subelement = $objecttype; + if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier' + && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs)) + { + $module = $element = $regs[1]; + $subelement = $regs[2]; + } - $classpath = $element.'/class'; - // To work with non standard classpath or module name - if ($objecttype == 'facture') { - $classpath = 'compta/facture/class'; - } - else if ($objecttype == 'facturerec') { - $classpath = 'compta/facture/class'; $module = 'facture'; - } - else if ($objecttype == 'propal') { - $classpath = 'comm/propal/class'; - } - else if ($objecttype == 'supplier_proposal') { - $classpath = 'supplier_proposal/class'; - } - else if ($objecttype == 'shipping') { - $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon'; - } - else if ($objecttype == 'delivery') { - $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon'; - } - else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { - $classpath = 'fourn/class'; $module = 'fournisseur'; - } - else if ($objecttype == 'fichinter') { - $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter'; - } - else if ($objecttype == 'subscription') { - $classpath = 'adherents/class'; $module = 'adherent'; - } + $classpath = $element.'/class'; + // To work with non standard classpath or module name + if ($objecttype == 'facture') { + $classpath = 'compta/facture/class'; + } + else if ($objecttype == 'facturerec') { + $classpath = 'compta/facture/class'; $module = 'facture'; + } + else if ($objecttype == 'propal') { + $classpath = 'comm/propal/class'; + } + else if ($objecttype == 'supplier_proposal') { + $classpath = 'supplier_proposal/class'; + } + else if ($objecttype == 'shipping') { + $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon'; + } + else if ($objecttype == 'delivery') { + $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon'; + } + else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { + $classpath = 'fourn/class'; $module = 'fournisseur'; + } + else if ($objecttype == 'fichinter') { + $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter'; + } + else if ($objecttype == 'subscription') { + $classpath = 'adherents/class'; $module = 'adherent'; + } - // Set classfile - $classfile = strtolower($subelement); $classname = ucfirst($subelement); + // Set classfile + $classfile = strtolower($subelement); $classname = ucfirst($subelement); - if ($objecttype == 'order') { - $classfile = 'commande'; $classname = 'Commande'; - } - else if ($objecttype == 'invoice_supplier') { - $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur'; - } - else if ($objecttype == 'order_supplier') { - $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur'; - } - else if ($objecttype == 'supplier_proposal') { - $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; - } - else if ($objecttype == 'facturerec') { - $classfile = 'facture-rec'; $classname = 'FactureRec'; - } - else if ($objecttype == 'subscription') { - $classfile = 'subscription'; $classname = 'Subscription'; - } + if ($objecttype == 'order') { + $classfile = 'commande'; $classname = 'Commande'; + } + else if ($objecttype == 'invoice_supplier') { + $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur'; + } + else if ($objecttype == 'order_supplier') { + $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur'; + } + else if ($objecttype == 'supplier_proposal') { + $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; + } + else if ($objecttype == 'facturerec') { + $classfile = 'facture-rec'; $classname = 'FactureRec'; + } + else if ($objecttype == 'subscription') { + $classfile = 'subscription'; $classname = 'Subscription'; + } - // Here $module, $classfile and $classname are set - if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) - { - dol_include_once('/'.$classpath.'/'.$classfile.'.class.php'); - //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname); - if (class_exists($classname)) - { - foreach($objectids as $i => $objectid) // $i is rowid into llx_element_element - { - $object = new $classname($this->db); - $ret = $object->fetch($objectid); - if ($ret >= 0) - { - $this->linkedObjects[$objecttype][$i] = $object; - } - } - } - } - } - } - } - else - { - dol_print_error($this->db); - } - } + // Here $module, $classfile and $classname are set + if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) + { + dol_include_once('/'.$classpath.'/'.$classfile.'.class.php'); + //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname); + if (class_exists($classname)) + { + foreach($objectids as $i => $objectid) // $i is rowid into llx_element_element + { + $object = new $classname($this->db); + $ret = $object->fetch($objectid); + if ($ret >= 0) + { + $this->linkedObjects[$objecttype][$i] = $object; + } + } + } + } + } + } + } + else + { + dol_print_error($this->db); + } + } - /** - * Update object linked of a current object - * - * @param int $sourceid Object source id - * @param string $sourcetype Object source type - * @param int $targetid Object target id - * @param string $targettype Object target type - * @return int >0 if OK, <0 if KO - * @see add_object_linked, fetObjectLinked, deleteObjectLinked - */ - function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='') - { - $updatesource=false; - $updatetarget=false; + /** + * Update object linked of a current object + * + * @param int $sourceid Object source id + * @param string $sourcetype Object source type + * @param int $targetid Object target id + * @param string $targettype Object target type + * @return int >0 if OK, <0 if KO + * @see add_object_linked, fetObjectLinked, deleteObjectLinked + */ + function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='') + { + $updatesource=false; + $updatetarget=false; - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true; - else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true; + if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true; + else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true; - $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET "; - if ($updatesource) - { - $sql.= "fk_source = ".$sourceid; - $sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'"; - $sql.= " WHERE fk_target = ".$this->id; - $sql.= " AND targettype = '".$this->db->escape($this->element)."'"; - } - else if ($updatetarget) - { - $sql.= "fk_target = ".$targetid; - $sql.= ", targettype = '".$this->db->escape($targettype)."'"; - $sql.= " WHERE fk_source = ".$this->id; - $sql.= " AND sourcetype = '".$this->db->escape($this->element)."'"; - } + $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET "; + if ($updatesource) + { + $sql.= "fk_source = ".$sourceid; + $sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'"; + $sql.= " WHERE fk_target = ".$this->id; + $sql.= " AND targettype = '".$this->db->escape($this->element)."'"; + } + else if ($updatetarget) + { + $sql.= "fk_target = ".$targetid; + $sql.= ", targettype = '".$this->db->escape($targettype)."'"; + $sql.= " WHERE fk_source = ".$this->id; + $sql.= " AND sourcetype = '".$this->db->escape($this->element)."'"; + } - dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } + dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG); + if ($this->db->query($sql)) + { + return 1; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } /** * Delete all links between an object $this * * @param int $sourceid Object source id - * @param string $sourcetype Object source type - * @param int $targetid Object target id - * @param string $targettype Object target type - * @param int $rowid Row id of line to delete. If defined, other parameters are not used. + * @param string $sourcetype Object source type + * @param int $targetid Object target id + * @param string $targettype Object target type + * @param int $rowid Row id of line to delete. If defined, other parameters are not used. * @return int >0 if OK, <0 if KO * @see add_object_linked, updateObjectLinked, fetchObjectLinked */ @@ -2805,73 +2922,73 @@ abstract class CommonObject } } - /** - * Set status of an object - * - * @param int $status Status to set - * @param int $elementId Id of element to force (use this->id by default) - * @param string $elementType Type of element to force (use this->table_element by default) - * @return int <0 if KO, >0 if OK - */ - function setStatut($status,$elementId=null,$elementType='') - { - global $user,$langs,$conf; + /** + * Set status of an object + * + * @param int $status Status to set + * @param int $elementId Id of element to force (use this->id by default) + * @param string $elementType Type of element to force (use this->table_element by default) + * @return int <0 if KO, >0 if OK + */ + function setStatut($status,$elementId=null,$elementType='') + { + global $user,$langs,$conf; - $savElementId=$elementId; // To be used later to know if we were using the method using the id of this or not. + $savElementId=$elementId; // To be used later to know if we were using the method using the id of this or not. - $elementId = (!empty($elementId)?$elementId:$this->id); - $elementTable = (!empty($elementType)?$elementType:$this->table_element); + $elementId = (!empty($elementId)?$elementId:$this->id); + $elementTable = (!empty($elementType)?$elementType:$this->table_element); - $this->db->begin(); + $this->db->begin(); - $fieldstatus="fk_statut"; - if ($elementTable == 'mailing') $fieldstatus="statut"; - if ($elementTable == 'user') $fieldstatus="statut"; - if ($elementTable == 'expensereport') $fieldstatus="fk_statut"; + $fieldstatus="fk_statut"; + if ($elementTable == 'mailing') $fieldstatus="statut"; + if ($elementTable == 'user') $fieldstatus="statut"; + if ($elementTable == 'expensereport') $fieldstatus="fk_statut"; if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status"; - $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable; - $sql.= " SET ".$fieldstatus." = ".$status; - // If status = 1 = validated, update also fk_user_valid - if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id; - $sql.= " WHERE rowid=".$elementId; + $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable; + $sql.= " SET ".$fieldstatus." = ".$status; + // If status = 1 = validated, update also fk_user_valid + if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id; + $sql.= " WHERE rowid=".$elementId; - dol_syslog(get_class($this)."::setStatut", LOG_DEBUG); - if ($this->db->query($sql)) - { - $error = 0; + dol_syslog(get_class($this)."::setStatut", LOG_DEBUG); + if ($this->db->query($sql)) + { + $error = 0; - $trigkey=''; - if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class - if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE'; - if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; - if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; + $trigkey=''; + if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class + if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE'; + if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; + if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; - if ($trigkey) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers - } + if ($trigkey) + { + // Appel des triggers + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf); + if ($result < 0) { + $error++; $this->errors=$interface->errors; + } + // Fin appel triggers + } if (! $error) { $this->db->commit(); - if (empty($savElementId)) // If the element we update was $this (so $elementId is null) - { - $this->statut = $status; - $this->status = $status; - } + if (empty($savElementId)) // If the element we update was $this (so $elementId is null) + { + $this->statut = $status; + $this->status = $status; + } - return 1; + return 1; } else { @@ -2879,244 +2996,260 @@ abstract class CommonObject dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR); return -1; } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } - /** - * Load type of canvas of an object if it exists - * - * @param int $id Record id - * @param string $ref Record ref - * @return int <0 if KO, 0 if nothing done, >0 if OK - */ - function getCanvas($id=0,$ref='') - { - global $conf; + /** + * Load type of canvas of an object if it exists + * + * @param int $id Record id + * @param string $ref Record ref + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + function getCanvas($id=0,$ref='') + { + global $conf; - if (empty($id) && empty($ref)) return 0; - if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default. + if (empty($id) && empty($ref)) return 0; + if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default. - // Clean parameters - $ref = trim($ref); + // Clean parameters + $ref = trim($ref); - $sql = "SELECT rowid, canvas"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; - if (! empty($id)) $sql.= " AND rowid = ".$id; - if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'"; + $sql = "SELECT rowid, canvas"; + $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; + if (! empty($id)) $sql.= " AND rowid = ".$id; + if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'"; - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $this->canvas = $obj->canvas; - return 1; - } - else return 0; - } - else - { - dol_print_error($this->db); - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $this->canvas = $obj->canvas; + return 1; + } + else return 0; + } + else + { + dol_print_error($this->db); + return -1; + } + } - /** - * Get special code of a line - * - * @param int $lineid Id of line - * @return int Special code - */ - function getSpecialCode($lineid) - { - $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE rowid = '.$lineid; - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } + /** + * Get special code of a line + * + * @param int $lineid Id of line + * @return int Special code + */ + function getSpecialCode($lineid) + { + $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE rowid = '.$lineid; + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + return $row[0]; + } + } - /** - * Function to check if an object is used by others. - * Check is done into this->childtables. There is no check into llx_element_element. - * - * @param int $id Force id of object - * @return int <0 if KO, 0 if not used, >0 if already used - */ - function isObjectUsed($id=0) - { - if (empty($id)) $id=$this->id; + /** + * Function to check if an object is used by others. + * Check is done into this->childtables. There is no check into llx_element_element. + * + * @param int $id Force id of object + * @return int <0 if KO, 0 if not used, >0 if already used + */ + function isObjectUsed($id=0) + { + global $langs; - // Check parameters - if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0) - { - dol_print_error('Called isObjectUsed on a class with property this->childtables not defined'); - return -1; - } + if (empty($id)) $id=$this->id; - // Test if child exists - $haschild=0; - foreach($this->childtables as $table) - { - // Check if third party can be deleted - $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$this->fk_element." = ".$id; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $haschild+=$obj->nb; - //print 'Found into table '.$table; - if ($haschild) break; // We found at least on, we stop here - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } - if ($haschild > 0) - { - $this->error="ErrorRecordHasChildren"; - return $haschild; - } - else return 0; - } + // Check parameters + if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0) + { + dol_print_error('Called isObjectUsed on a class with property this->childtables not defined'); + return -1; + } - /** - * Function to say how many lines object contains - * - * @param int $predefined -1=All, 0=Count free product/service only, 1=Count predefined product/service only, 2=Count predefined product, 3=Count predefined service - * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found - */ - function hasProductsOrServices($predefined=-1) - { - $nb=0; + $arraytoscan = $this->childtables; + // For backward compatibility, we check if array is old format array('table1', 'table2', ...) + $tmparray=array_keys($this->childtables); + if (is_numeric($tmparray[0])) + { + $arraytoscan = array_flip($this->childtables); + } - foreach($this->lines as $key => $val) - { - $qualified=0; - if ($predefined == -1) $qualified=1; - if ($predefined == 1 && $val->fk_product > 0) $qualified=1; - if ($predefined == 0 && $val->fk_product <= 0) $qualified=1; - if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1; - if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1; - if ($qualified) $nb++; - } - dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies'); - return $nb; - } + // Test if child exists + $haschild=0; + foreach($arraytoscan as $table => $elementname) + { + //print $id.'-'.$table.'-'.$elementname.'
    '; + // Check if third party can be deleted + $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table; + $sql.= " WHERE ".$this->fk_element." = ".$id; + $resql=$this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + if ($obj->nb > 0) + { + $langs->load("errors"); + //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild; + $haschild += $obj->nb; + $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); + break; // We found at least one, we stop here + } + } + else + { + $this->errors[]=$this->db->lasterror(); + return -1; + } + } + if ($haschild > 0) + { + $this->errors[]="ErrorRecordHasChildren"; + return $haschild; + } + else return 0; + } - /** - * Function that returns the total amount HT of discounts applied for all lines. - * - * @return float - */ - function getTotalDiscount() - { - $total_discount=0.00; + /** + * Function to say how many lines object contains + * + * @param int $predefined -1=All, 0=Count free product/service only, 1=Count predefined product/service only, 2=Count predefined product, 3=Count predefined service + * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found + */ + function hasProductsOrServices($predefined=-1) + { + $nb=0; - $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det"; - $sql.= " WHERE ".$this->fk_element." = ".$this->id; + foreach($this->lines as $key => $val) + { + $qualified=0; + if ($predefined == -1) $qualified=1; + if ($predefined == 1 && $val->fk_product > 0) $qualified=1; + if ($predefined == 0 && $val->fk_product <= 0) $qualified=1; + if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1; + if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1; + if ($qualified) $nb++; + } + dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies'); + return $nb; + } - dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + /** + * Function that returns the total amount HT of discounts applied for all lines. + * + * @return float + */ + function getTotalDiscount() + { + $total_discount=0.00; - $pu_ht = $obj->pu_ht; - $qty= $obj->qty; - $total_ht = $obj->total_ht; + $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht"; + $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det"; + $sql.= " WHERE ".$this->fk_element." = ".$this->id; - $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT')); - $total_discount += $total_discount_line; + dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num=$this->db->num_rows($resql); + $i=0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - $i++; - } - } + $pu_ht = $obj->pu_ht; + $qty= $obj->qty; + $total_ht = $obj->total_ht; - //print $total_discount; exit; - return price2num($total_discount); - } + $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT')); + $total_discount += $total_discount_line; + + $i++; + } + } + + //print $total_discount; exit; + return price2num($total_discount); + } - /** - * Return into unit=0, the calculated total of weight and volume of all lines * qty - * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line. - * - * @return array array('weight'=>...,'volume'=>...) - */ - function getTotalWeightVolume() - { - $totalWeight = 0; - $totalVolume = 0; - // defined for shipment only - $totalOrdered = ''; - // defined for shipment only - $totalToShip = ''; + /** + * Return into unit=0, the calculated total of weight and volume of all lines * qty + * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line. + * + * @return array array('weight'=>...,'volume'=>...) + */ + function getTotalWeightVolume() + { + $totalWeight = 0; + $totalVolume = 0; + // defined for shipment only + $totalOrdered = ''; + // defined for shipment only + $totalToShip = ''; - foreach ($this->lines as $line) - { - if (isset($line->qty_asked)) - { - if (empty($totalOrdered)) $totalOrdered=0; // Avoid warning because $totalOrdered is '' - $totalOrdered+=$line->qty_asked; // defined for shipment only - } - if (isset($line->qty_shipped)) - { - if (empty($totalToShip)) $totalToShip=0; // Avoid warning because $totalToShip is '' - $totalToShip+=$line->qty_shipped; // defined for shipment only - } + foreach ($this->lines as $line) + { + if (isset($line->qty_asked)) + { + if (empty($totalOrdered)) $totalOrdered=0; // Avoid warning because $totalOrdered is '' + $totalOrdered+=$line->qty_asked; // defined for shipment only + } + if (isset($line->qty_shipped)) + { + if (empty($totalToShip)) $totalToShip=0; // Avoid warning because $totalToShip is '' + $totalToShip+=$line->qty_shipped; // defined for shipment only + } - // Define qty, weight, volume, weight_units, volume_units - if ($this->element == 'shipping') { - // for shipments - $qty = $line->qty_shipped ? $line->qty_shipped : 0; - } - else { - $qty = $line->qty ? $line->qty : 0; - } + // Define qty, weight, volume, weight_units, volume_units + if ($this->element == 'shipping') { + // for shipments + $qty = $line->qty_shipped ? $line->qty_shipped : 0; + } + else { + $qty = $line->qty ? $line->qty : 0; + } - $weight = $line->weight ? $line->weight : 0; - $volume = $line->volume ? $line->volume : 0; + $weight = $line->weight ? $line->weight : 0; + $volume = $line->volume ? $line->volume : 0; - $weight_units=$line->weight_units; - $volume_units=$line->volume_units; + $weight_units=$line->weight_units; + $volume_units=$line->volume_units; - $weightUnit=0; - $volumeUnit=0; - if (! empty($weight_units)) $weightUnit = $weight_units; - if (! empty($volume_units)) $volumeUnit = $volume_units; + $weightUnit=0; + $volumeUnit=0; + if (! empty($weight_units)) $weightUnit = $weight_units; + if (! empty($volume_units)) $volumeUnit = $volume_units; - if (empty($totalWeight)) $totalWeight=0; // Avoid warning because $totalWeight is '' - if (empty($totalVolume)) $totalVolume=0; // Avoid warning because $totalVolume is '' + if (empty($totalWeight)) $totalWeight=0; // Avoid warning because $totalWeight is '' + if (empty($totalVolume)) $totalVolume=0; // Avoid warning because $totalVolume is '' - //var_dump($line->volume_units); - if ($weight_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) - { - $trueWeightUnit=pow(10, $weightUnit); - $totalWeight += $weight * $qty * $trueWeightUnit; - } - else { + //var_dump($line->volume_units); + if ($weight_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) + { + $trueWeightUnit=pow(10, $weightUnit); + $totalWeight += $weight * $qty * $trueWeightUnit; + } + else { if ($weight_units == 99) { // conversion 1 Pound = 0.45359237 KG $trueWeightUnit = 0.45359237; @@ -3127,65 +3260,65 @@ abstract class CommonObject $totalWeight += $weight * $qty * $trueWeightUnit; } else - $totalWeight += $weight * $qty; // This may be wrong if we mix different units - } - if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) - { - //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit; - $trueVolumeUnit=pow(10, $volumeUnit); - //print $line->volume; - $totalVolume += $volume * $qty * $trueVolumeUnit; - } - else - { - $totalVolume += $volume * $qty; // This may be wrong if we mix different units - } - } + $totalWeight += $weight * $qty; // This may be wrong if we mix different units + } + if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) + { + //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit; + $trueVolumeUnit=pow(10, $volumeUnit); + //print $line->volume; + $totalVolume += $volume * $qty * $trueVolumeUnit; + } + else + { + $totalVolume += $volume * $qty; // This may be wrong if we mix different units + } + } - return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip); - } - - - /** - * Set extra parameters - * - * @return int <0 if KO, >0 if OK - */ - function setExtraParameters() - { - $this->db->begin(); - - $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null); - - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null"); - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } + return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip); + } /** - * Return incoterms informations - * TODO Use a cache for label get - * - * @return string incoterms info - */ - function display_incoterms() - { - $out = ''; + * Set extra parameters + * + * @return int <0 if KO, >0 if OK + */ + function setExtraParameters() + { + $this->db->begin(); + + $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null); + + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null"); + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + + + /** + * Return incoterms informations + * TODO Use a cache for label get + * + * @return string incoterms info + */ + function display_incoterms() + { + $out = ''; $this->libelle_incoterms = ''; if (!empty($this->fk_incoterms)) { @@ -3201,13 +3334,13 @@ abstract class CommonObject $out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms; return $out; - } + } /** - * Return incoterms informations for pdf display - * - * @return string incoterms info - */ + * Return incoterms informations for pdf display + * + * @return string incoterms info + */ function getIncotermsForPDF() { $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; @@ -3227,31 +3360,31 @@ abstract class CommonObject } else { - $this->errors[] = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); return false; } } /** - * Define incoterms values of current object - * - * @param int $id_incoterm Id of incoterm to set or '' to remove + * Define incoterms values of current object + * + * @param int $id_incoterm Id of incoterm to set or '' to remove * @param string $location location of incoterm - * @return int <0 if KO, >0 if OK - */ - function setIncoterms($id_incoterm, $location) - { - if ($this->id && $this->table_element) - { - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); + * @return int <0 if KO, >0 if OK + */ + function setIncoterms($id_incoterm, $location) + { + if ($this->id && $this->table_element) + { + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); $sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null"); - $sql.= " WHERE rowid = " . $this->id; + $sql.= " WHERE rowid = " . $this->id; dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->fk_incoterms = $id_incoterm; + $resql=$this->db->query($sql); + if ($resql) + { + $this->fk_incoterms = $id_incoterm; $this->location_incoterms = $location; $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; @@ -3261,45 +3394,45 @@ abstract class CommonObject $obj = $this->db->fetch_object($res); $this->libelle_incoterms = $obj->libelle; } - return 1; - } - else + return 1; + } + else { - $this->errors[] = $this->db->lasterror(); - return -1; - } - } - else return -1; - } + $this->errors[] = $this->db->lasterror(); + return -1; + } + } + else return -1; + } - /** - * Return if a country is inside the EEC (European Economic Community) - * @deprecated - * - * @return boolean true = country inside EEC, false = country outside EEC - */ - function isInEEC() - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - return isInEEC($this); - } + /** + * Return if a country is inside the EEC (European Economic Community) + * @deprecated + * + * @return boolean true = country inside EEC, false = country outside EEC + */ + function isInEEC() + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + return isInEEC($this); + } - // -------------------- - // TODO: All functions here must be redesigned and moved as they are not business functions but output functions - // -------------------- + // -------------------- + // TODO: All functions here must be redesigned and moved as they are not business functions but output functions + // -------------------- - /* This is to show add lines */ + /* This is to show add lines */ - /** - * Show add free and predefined products/services form - * - * @param int $dateSelector 1=Show also date range input fields - * @param Societe $seller Object thirdparty who sell - * @param Societe $buyer Object thirdparty who buy - * @return void - */ + /** + * Show add free and predefined products/services form + * + * @param int $dateSelector 1=Show also date range input fields + * @param Societe $seller Object thirdparty who sell + * @param Societe $buyer Object thirdparty who buy + * @return void + */ function formAddObjectLine($dateSelector,$seller,$buyer) { global $conf,$user,$langs,$object,$hookmanager; @@ -3311,7 +3444,7 @@ abstract class CommonObject $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line); // Output template part (modules that overwrite templates must declare this into descriptor) - // Use global variables + $dateSelector + $seller and $buyer + // Use global variables + $dateSelector + $seller and $buyer $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); foreach($dirtpls as $reldir) { @@ -3321,13 +3454,13 @@ abstract class CommonObject } else { $res=include $tpl; // for debug } - if ($res) break; + if ($res) break; } - } + } - /* This is to show array of line of details */ + /* This is to show array of line of details */ /** @@ -3364,75 +3497,75 @@ abstract class CommonObject $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { - print ''; + print ''; - if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ' '; + if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ' '; - // Description - print ''.$langs->trans('Description').''; + // Description + print ''.$langs->trans('Description').''; - if ($this->element == 'supplier_proposal') - { - print ''.$langs->trans("SupplierProposalRefFourn").''; - } + if ($this->element == 'supplier_proposal') + { + print ''.$langs->trans("SupplierProposalRefFourn").''; + } - // VAT - print ''.$langs->trans('VAT').''; + // VAT + print ''.$langs->trans('VAT').''; - // Price HT - print ''.$langs->trans('PriceUHT').''; + // Price HT + print ''.$langs->trans('PriceUHT').''; - // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''; + // Multicurrency + if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''; - if ($inputalsopricewithtax) print ''.$langs->trans('PriceUTTC').''; + if ($inputalsopricewithtax) print ''.$langs->trans('PriceUTTC').''; - // Qty - print ''.$langs->trans('Qty').''; + // Qty + print ''.$langs->trans('Qty').''; - if($conf->global->PRODUCT_USE_UNITS) - { - print ''.$langs->trans('Unit').''; - } + if($conf->global->PRODUCT_USE_UNITS) + { + print ''.$langs->trans('Unit').''; + } - // Reduction short - print ''.$langs->trans('ReductionShort').''; + // Reduction short + print ''.$langs->trans('ReductionShort').''; - if ($this->situation_cycle_ref) { - print '' . $langs->trans('Progress') . ''; - } + if ($this->situation_cycle_ref) { + print '' . $langs->trans('Progress') . ''; + } - if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id)) - { - if (!empty($user->rights->margins->creer)) - { - if ($conf->global->MARGIN_TYPE == "1") - print ''.$langs->trans('BuyingPrice').''; - else - print ''.$langs->trans('CostPrice').''; - } + if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id)) + { + if (!empty($user->rights->margins->creer)) + { + if ($conf->global->MARGIN_TYPE == "1") + print ''.$langs->trans('BuyingPrice').''; + else + print ''.$langs->trans('CostPrice').''; + } - if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) - print ''.$langs->trans('MarginRate').''; - if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) - print ''.$langs->trans('MarkRate').''; - } + if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) + print ''.$langs->trans('MarginRate').''; + if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) + print ''.$langs->trans('MarkRate').''; + } - // Total HT - print ''.$langs->trans('TotalHTShort').''; + // Total HT + print ''.$langs->trans('TotalHTShort').''; - // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''; + // Multicurrency + if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''; - if ($outputalsopricetotalwithtax) print ''.$langs->trans('TotalTTCShort').''; + if ($outputalsopricetotalwithtax) print ''.$langs->trans('TotalTTCShort').''; - print ''; // No width to allow autodim + print ''; // No width to allow autodim - print ''; + print ''; - print ''; + print ''; - print "\n"; + print "\n"; } $var = true; @@ -3446,20 +3579,20 @@ abstract class CommonObject //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) - if (is_object($hookmanager)) // Old code is commented on preceding line. + if (is_object($hookmanager)) // Old code is commented on preceding line. { if (empty($line->fk_parent_line)) { $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline); - $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } else { $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline, 'fk_parent_line'=>$line->fk_parent_line); - $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } } - if (empty($reshook)) + if (empty($reshook)) { $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline); } @@ -3511,8 +3644,8 @@ abstract class CommonObject $product_static = new Product($this->db); $product_static->fetch($line->fk_product); - $product_static->ref = $line->ref; //can change ref in hook - $product_static->label = $line->label; //can change label in hook + $product_static->ref = $line->ref; //can change ref in hook + $product_static->label = $line->label; //can change label in hook $text=$product_static->getNomUrl(1); // Define output language and label @@ -3569,8 +3702,7 @@ abstract class CommonObject if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) { $label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : '')); - if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("Label").'"'; - else $placeholder=' title="'.$langs->trans("Label").'"'; + $placeholder=' placeholder="'.$langs->trans("Label").'"'; $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU'); @@ -3591,74 +3723,74 @@ abstract class CommonObject } - /* This is to show array of line of details of source object */ + /* This is to show array of line of details of source object */ - /** - * Return HTML table table of source object lines - * TODO Move this and previous function into output html class file (htmlline.class.php). - * If lines are into a template, title must also be into a template - * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. - * - * @return void - */ - function printOriginLinesList() - { - global $langs, $hookmanager, $conf; + /** + * Return HTML table table of source object lines + * TODO Move this and previous function into output html class file (htmlline.class.php). + * If lines are into a template, title must also be into a template + * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects. + * + * @param string $restrictlist ''=All lines, 'services'=Restrict to services only + * @return void + */ + function printOriginLinesList($restrictlist='') + { + global $langs, $hookmanager, $conf; - print ''; - print ''.$langs->trans('Ref').''; - print ''.$langs->trans('Description').''; - print ''.$langs->trans('VATRate').''; - print ''.$langs->trans('PriceUHT').''; + print ''; + print ''.$langs->trans('Ref').''; + print ''.$langs->trans('Description').''; + print ''.$langs->trans('VATRate').''; + print ''.$langs->trans('PriceUHT').''; if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency').''; - print ''.$langs->trans('Qty').''; - if($conf->global->PRODUCT_USE_UNITS) - { - print ''.$langs->trans('Unit').''; - } - print ''.$langs->trans('ReductionShort').''; + print ''.$langs->trans('Qty').''; + if($conf->global->PRODUCT_USE_UNITS) + { + print ''.$langs->trans('Unit').''; + } + print ''.$langs->trans('ReductionShort').''; - $var = true; - $i = 0; + $var = true; + $i = 0; - foreach ($this->lines as $line) - { + foreach ($this->lines as $line) + { + if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) + { + if (empty($line->fk_parent_line)) + { + $parameters=array('line'=>$line,'var'=>$var,'i'=>$i); + $action=''; + $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + } + } + else + { + $this->printOriginLine($line, $var, $restrictlist); + } + $i++; + } + } - if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) - { - if (empty($line->fk_parent_line)) - { - $parameters=array('line'=>$line,'var'=>$var,'i'=>$i); - $action=''; - $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - } - } - else - { - $this->printOriginLine($line,$var); - } + /** + * Return HTML with a line of table array of source object lines + * TODO Move this and previous function into output html class file (htmlline.class.php). + * If lines are into a template, title must also be into a template + * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. + * + * @param CommonObjectLine $line Line + * @param string $var Var + * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not) + * @return void + */ + function printOriginLine($line, $var, $restrictlist='') + { + global $langs, $conf; - $i++; - } - } - - /** - * Return HTML with a line of table array of source object lines - * TODO Move this and previous function into output html class file (htmlline.class.php). - * If lines are into a template, title must also be into a template - * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. - * - * @param CommonObjectLine $line Line - * @param string $var Var - * @return void - */ - function printOriginLine($line,$var) - { - global $langs, $conf; - - //var_dump($line); + //var_dump($line); if (!empty($line->date_start)) { $date_start=$line->date_start; @@ -3678,98 +3810,102 @@ abstract class CommonObject if ($line->date_fin_reel) $date_end=$line->date_fin_reel; } - $this->tpl['label'] = ''; - if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow'); + $this->tpl['label'] = ''; + if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow'); - if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object - { - $discount=new DiscountAbsolute($this->db); - $discount->fk_soc = $this->socid; - $this->tpl['label'].= $discount->getNomUrl(0,'discount'); - } - else if (! empty($line->fk_product)) - { - $productstatic = new Product($this->db); - $productstatic->id = $line->fk_product; - $productstatic->ref = $line->ref; - $productstatic->type = $line->fk_product_type; - $this->tpl['label'].= $productstatic->getNomUrl(1); - $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label); - // Dates - if ($line->product_type == 1 && ($date_start || $date_end)) - { - $this->tpl['label'].= get_date_range($date_start,$date_end); - } - } - else - { - $this->tpl['label'].= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product'))); - if (!empty($line->desc)) { - $this->tpl['label'].=$line->desc; - }else { - $this->tpl['label'].= ($line->label ? ' '.$line->label : ''); - } - // Dates - if ($line->product_type == 1 && ($date_start || $date_end)) - { - $this->tpl['label'].= get_date_range($date_start,$date_end); - } - } + if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object + { + $discount=new DiscountAbsolute($this->db); + $discount->fk_soc = $this->socid; + $this->tpl['label'].= $discount->getNomUrl(0,'discount'); + } + else if (! empty($line->fk_product)) + { + $productstatic = new Product($this->db); + $productstatic->id = $line->fk_product; + $productstatic->ref = $line->ref; + $productstatic->type = $line->fk_product_type; + $this->tpl['label'].= $productstatic->getNomUrl(1); + $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label); + // Dates + if ($line->product_type == 1 && ($date_start || $date_end)) + { + $this->tpl['label'].= get_date_range($date_start,$date_end); + } + } + else + { + $this->tpl['label'].= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product'))); + if (!empty($line->desc)) { + $this->tpl['label'].=$line->desc; + }else { + $this->tpl['label'].= ($line->label ? ' '.$line->label : ''); + } + // Dates + if ($line->product_type == 1 && ($date_start || $date_end)) + { + $this->tpl['label'].= get_date_range($date_start,$date_end); + } + } - if (! empty($line->desc)) - { - if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object - { - $discount=new DiscountAbsolute($this->db); - $discount->fetch($line->fk_remise_except); - $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0)); - } - elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object - { - $discount=new DiscountAbsolute($this->db); - $discount->fetch($line->fk_remise_except); - $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); - } - elseif ($line->desc == '(EXCESS RECEIVED)') - { - $discount=new DiscountAbsolute($this->db); - $discount->fetch($line->fk_remise_except); - $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } - else - { - $this->tpl['description'] = dol_trunc($line->desc,60); - } - } - else - { - $this->tpl['description'] = ' '; - } + if (! empty($line->desc)) + { + if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0)); + } + elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); + } + elseif ($line->desc == '(EXCESS RECEIVED)') + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); + } + else + { + $this->tpl['description'] = dol_trunc($line->desc,60); + } + } + else + { + $this->tpl['description'] = ' '; + } - // VAT Rate - $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); - if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')'; + // VAT Rate + $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); + if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')'; - $this->tpl['price'] = price($line->subprice); + $this->tpl['price'] = price($line->subprice); $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice); - $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' '; - if($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $line->getLabelOfUnit('long'); - $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' '; + $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' '; + if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long')); + $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' '; - // Output template part (modules that overwrite templates must declare this into descriptor) - // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); - foreach($dirtpls as $reldir) - { - $tpl = dol_buildpath($reldir.'/originproductline.tpl.php'); - if (empty($conf->file->strict_mode)) { - $res=@include $tpl; - } else { - $res=include $tpl; // for debug - } - if ($res) break; - } - } + // Is the line strike or not + $this->tpl['strike']=0; + if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1; + + // Output template part (modules that overwrite templates must declare this into descriptor) + // Use global variables + $dateSelector + $seller and $buyer + $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); + foreach($dirtpls as $reldir) + { + $tpl = dol_buildpath($reldir.'/originproductline.tpl.php'); + if (empty($conf->file->strict_mode)) { + $res=@include $tpl; + } else { + $res=include $tpl; // for debug + } + if ($res) break; + } + } /** @@ -3795,11 +3931,11 @@ abstract class CommonObject $sql.= ", mandatory"; $sql.= ") VALUES ("; $sql.= $resource_id; - $sql.= ", '".$resource_type."'"; - $sql.= ", '".$this->id."'"; - $sql.= ", '".$this->element."'"; - $sql.= ", '".$busy."'"; - $sql.= ", '".$mandatory."'"; + $sql.= ", '".$this->db->escape($resource_type)."'"; + $sql.= ", '".$this->db->escape($this->id)."'"; + $sql.= ", '".$this->db->escape($this->element)."'"; + $sql.= ", '".$this->db->escape($busy)."'"; + $sql.= ", '".$this->db->escape($mandatory)."'"; $sql.= ")"; dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG); @@ -3826,32 +3962,32 @@ abstract class CommonObject */ function delete_resource($rowid, $element, $notrigger=0) { - global $user; + global $user; - $this->db->begin(); + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; - $sql.= " WHERE rowid=".$rowid; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; + $sql.= " WHERE rowid=".$rowid; - dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG); + dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); - if ($result < 0) { $this->db->rollback(); return -1; } - } - $this->db->commit(); - return 1; - } + $resql=$this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + if (! $notrigger) + { + $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); + if ($result < 0) { $this->db->rollback(); return -1; } + } + $this->db->commit(); + return 1; + } } @@ -3861,24 +3997,24 @@ abstract class CommonObject * @return void */ function __clone() - { - // Force a copy of this->lines, otherwise it will point to same object. - if (isset($this->lines) && is_array($this->lines)) - { - $nboflines=count($this->lines); - for($i=0; $i < $nboflines; $i++) - { - $this->lines[$i] = clone $this->lines[$i]; - } - } - } + { + // Force a copy of this->lines, otherwise it will point to same object. + if (isset($this->lines) && is_array($this->lines)) + { + $nboflines=count($this->lines); + for($i=0; $i < $nboflines; $i++) + { + $this->lines[$i] = clone $this->lines[$i]; + } + } + } /** * Common function for all objects extending CommonObject for generating documents * * @param string $modelspath Relative folder where generators are placed * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example. - * @param Translate $outputlangs Language to use + * @param Translate $outputlangs Output language to use * @param int $hidedetails 1 to hide details. 0 by default * @param int $hidedesc 1 to hide product description. 0 by default * @param int $hideref 1 to hide product reference. 0 by default @@ -3887,7 +4023,7 @@ abstract class CommonObject */ protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null) { - global $conf, $langs; + global $conf, $langs, $user; $srctemplatepath=''; @@ -3905,7 +4041,6 @@ abstract class CommonObject $srctemplatepath=$tmp[1]; } - // Search template files $file=''; $classname=''; $filefound=0; $dirmodels=array('/'); @@ -3914,7 +4049,7 @@ abstract class CommonObject { foreach(array('doc','pdf') as $prefix) { - if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php + if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php else $file = $prefix."_".$modele.".modules.php"; // On verifie l'emplacement du modele @@ -3949,27 +4084,27 @@ abstract class CommonObject $listoffiles=array(); // Now we add first model found in directories scanned - $listofdir=explode(',',$dirtoscan); - foreach($listofdir as $key => $tmpdir) - { - $tmpdir=trim($tmpdir); - $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir); - if (! $tmpdir) { unset($listofdir[$key]); continue; } - if (is_dir($tmpdir)) - { - $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0); - if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles); - } - } + $listofdir=explode(',',$dirtoscan); + foreach($listofdir as $key => $tmpdir) + { + $tmpdir=trim($tmpdir); + $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir); + if (! $tmpdir) { unset($listofdir[$key]); continue; } + if (is_dir($tmpdir)) + { + $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0); + if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles); + } + } - if (count($listoffiles)) - { - foreach($listoffiles as $record) - { - $srctemplatepath=$record['fullname']; - break; - } - } + if (count($listoffiles)) + { + foreach($listoffiles as $record) + { + $srctemplatepath=$record['fullname']; + break; + } + } } if (empty($srctemplatepath)) @@ -3979,14 +4114,14 @@ abstract class CommonObject } } - if ($obj->type == 'odt' && ! empty($srctemplatepath)) - { - if (! dol_is_file($srctemplatepath)) - { - $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; - return -1; - } - } + if ($obj->type == 'odt' && ! empty($srctemplatepath)) + { + if (! dol_is_file($srctemplatepath)) + { + $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; + return -1; + } + } // We save charset_output to restore it because write_file can change it if needed for // output format that does not support UTF8. @@ -3994,10 +4129,14 @@ abstract class CommonObject if (in_array(get_class($this), array('Adherent'))) { - $arrayofrecords = array(); // The write_file of templates of adherent class need this - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); + $arrayofrecords = array(); // The write_file of templates of adherent class need this var + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); } - else $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); + else + { + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); + } + // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. if ($resultwritefile > 0) { @@ -4007,6 +4146,89 @@ abstract class CommonObject require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; dol_delete_preview($this); + // Index file in database + if (! empty($obj->result['fullpath'])) + { + $destfull = $obj->result['fullpath']; + $upload_dir = dirname($destfull); + $destfile = basename($destfull); + $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir); + + if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir + { + $filename = basename($destfile); + $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); + $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); + + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile=new EcmFiles($this->db); + $result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename); + + // Set the public "share" key + $setsharekey = false; + if ($this->element == 'propal' && ! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'commande' && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'facture' && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($setsharekey) + { + if (empty($ecmfile->share)) // Because object not found or share not set yet + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $ecmfile->share = getRandomPassword(true); + } + } + + if ($result > 0) + { + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $result = $ecmfile->update($user); + if ($result < 0) + { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } + else + { + $ecmfile->entity = $conf->entity; + $ecmfile->filepath = $rel_dir; + $ecmfile->filename = $filename; + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $result = $ecmfile->create($user); + if ($result < 0) + { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } + + /*$this->result['fullname']=$destfull; + $this->result['filepath']=$ecmfile->filepath; + $this->result['filename']=$ecmfile->filename;*/ + + // Update the last_main_doc field into main object + $update_main_doc_field=0; + if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1; + if ($update_main_doc_field && ! empty($this->table_element)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'"; + $sql.= ' WHERE rowid = '.$this->id; + $resql = $this->db->query($sql); + if (! $resql) dol_print_error($this->db); + } + } + } + else + { + dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING); + } + // Success in building document. We build meta file. dol_meta_create($this); @@ -4044,190 +4266,190 @@ abstract class CommonObject if (file_exists($file_osencoded)) { // Create small thumbs for company (Ratio is near 16/9) - // Used on logon for example - vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality); + // Used on logon for example + vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality); - // Create mini thumbs for company (Ratio is near 16/9) - // Used on menu or for setup page for example - vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality); + // Create mini thumbs for company (Ratio is near 16/9) + // Used on menu or for setup page for example + vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality); } } /* Functions common to commonobject and commonobjectline */ - /* For default values */ + /* For default values */ - /** - * Return the default value to use for a field when showing the create form of object. - * Return values in this order: - * 1) If parameter is available into POST, we return it first. - * 2) If not but an alternate value was provided as parameter of function, we return it. - * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table). - * 4) Return value found into database (TODO No yet implemented) - * - * @param string $fieldname Name of field - * @param string $alternatevalue Alternate value to use - * @return string|string[] Default value (can be an array if the GETPOST return an array) - **/ + /** + * Return the default value to use for a field when showing the create form of object. + * Return values in this order: + * 1) If parameter is available into POST, we return it first. + * 2) If not but an alternate value was provided as parameter of function, we return it. + * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table). + * 4) Return value found into database (TODO No yet implemented) + * + * @param string $fieldname Name of field + * @param string $alternatevalue Alternate value to use + * @return string|string[] Default value (can be an array if the GETPOST return an array) + **/ function getDefaultCreateValueFor($fieldname, $alternatevalue=null) - { - global $conf, $_POST; + { + global $conf, $_POST; - // If param here has been posted, we use this value first. - if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2); + // If param here has been posted, we use this value first. + if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2); - if (isset($alternatevalue)) return $alternatevalue; + if (isset($alternatevalue)) return $alternatevalue; - $newelement=$this->element; - if ($newelement == 'facture') $newelement='invoice'; - if ($newelement == 'commande') $newelement='order'; - if (empty($newelement)) - { - dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING); - return ''; - } + $newelement=$this->element; + if ($newelement == 'facture') $newelement='invoice'; + if ($newelement == 'commande') $newelement='order'; + if (empty($newelement)) + { + dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING); + return ''; + } - $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname); - //var_dump($keyforfieldname); - if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname; + $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname); + //var_dump($keyforfieldname); + if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname; - // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname + // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname - } + } /* For triggers */ - /** - * Call trigger based on this instance. - * Some context information may also be provided into array property this->context. - * NB: Error from trigger are stacked in interface->errors - * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction. - * - * @param string $trigger_name trigger's name to execute - * @param User $user Object user - * @return int Result of run_triggers - */ - function call_trigger($trigger_name, $user) - { - global $langs,$conf; + /** + * Call trigger based on this instance. + * Some context information may also be provided into array property this->context. + * NB: Error from trigger are stacked in interface->errors + * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction. + * + * @param string $trigger_name trigger's name to execute + * @param User $user Object user + * @return int Result of run_triggers + */ + function call_trigger($trigger_name, $user) + { + global $langs,$conf; - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf); + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf); - if ($result < 0) - { - if (!empty($this->errors)) - { - $this->errors=array_unique(array_merge($this->errors,$interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice. - } - else - { - $this->errors=$interface->errors; - } - } - return $result; - } + if ($result < 0) + { + if (!empty($this->errors)) + { + $this->errors=array_unique(array_merge($this->errors,$interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice. + } + else + { + $this->errors=$interface->errors; + } + } + return $result; + } - /* Functions for extrafields */ + /* Functions for extrafields */ - /** - * Function to get extra fields of a member into $this->array_options - * This method is in most cases called by method fetch of objects but you can call it separately. - * - * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters. - * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters. - * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded - */ - function fetch_optionals($rowid=null,$optionsArray=null) - { - if (empty($rowid)) $rowid=$this->id; + /** + * Function to get extra fields of a member into $this->array_options + * This method is in most cases called by method fetch of objects but you can call it separately. + * + * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters. + * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters. + * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded + */ + function fetch_optionals($rowid=null,$optionsArray=null) + { + if (empty($rowid)) $rowid=$this->id; - // To avoid SQL errors. Probably not the better solution though - if (!$this->table_element) { - return 0; - } + // To avoid SQL errors. Probably not the better solution though + if (!$this->table_element) { + return 0; + } - if (! is_array($optionsArray)) - { - // $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page. - // TODO Use of existing extrafield is not yet ready (must mutualize code that use extrafields in form first) - // global $extrafields; - //if (! is_object($extrafields)) - //{ - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - //} + if (! is_array($optionsArray)) + { + // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page. + // TODO Use of existing extrafield is not yet ready (must mutualize code that use extrafields in form first) + // global $extrafields; + //if (! is_object($extrafields)) + //{ + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + //} - // Load array of extrafields for elementype = $this->table_element - if (empty($extrafields->attributes[$this->table_element]['loaded'])) - { - $extrafields->fetch_name_optionals_label($this->table_element); - } - $optionsArray = $extrafields->attributes[$this->table_element]['label']; - } + // Load array of extrafields for elementype = $this->table_element + if (empty($extrafields->attributes[$this->table_element]['loaded'])) + { + $extrafields->fetch_name_optionals_label($this->table_element); + } + $optionsArray = $extrafields->attributes[$this->table_element]['label']; + } - $table_element = $this->table_element; - if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility + $table_element = $this->table_element; + if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility - // Request to get complementary values - if (is_array($optionsArray) && count($optionsArray) > 0) - { - $sql = "SELECT rowid"; - foreach ($optionsArray as $name => $label) - { - if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') - { - $sql.= ", ".$name; - } - } - $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; - $sql.= " WHERE fk_object = ".$rowid; + // Request to get complementary values + if (is_array($optionsArray) && count($optionsArray) > 0) + { + $sql = "SELECT rowid"; + foreach ($optionsArray as $name => $label) + { + if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') + { + $sql.= ", ".$name; + } + } + $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; + $sql.= " WHERE fk_object = ".$rowid; - dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $numrows=$this->db->num_rows($resql); - if ($numrows) - { - $tab = $this->db->fetch_array($resql); + dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $numrows=$this->db->num_rows($resql); + if ($numrows) + { + $tab = $this->db->fetch_array($resql); - foreach ($tab as $key => $value) - { - // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine) - if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key)) - { - // we can add this attribute to object - $this->array_options["options_".$key]=$value; - } - } - } + foreach ($tab as $key => $value) + { + // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine) + if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key)) + { + // we can add this attribute to object + $this->array_options["options_".$key]=$value; + } + } + } - $this->db->free($resql); + $this->db->free($resql); - if ($numrows) return $numrows; - else return 0; - } - else - { - dol_print_error($this->db); - return -1; - } - } - return 0; - } + if ($numrows) return $numrows; + else return 0; + } + else + { + dol_print_error($this->db); + return -1; + } + } + return 0; + } - /** - * Delete all extra fields values for the current object. - * - * @return int <0 if KO, >0 if OK - */ + /** + * Delete all extra fields values for the current object. + * + * @return int <0 if KO, >0 if OK + */ function deleteExtraFields() { $this->db->begin(); @@ -4251,256 +4473,1140 @@ abstract class CommonObject } } - /** - * Add/Update all extra fields values for the current object. - * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) - * This function delete record with all extrafields and insert them again from the array $this->array_options. - * - * @return int -1=error, O=did nothing, 1=OK - */ - function insertExtraFields() - { - global $conf,$langs; + /** + * Add/Update all extra fields values for the current object. + * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) + * This function delete record with all extrafields and insert them again from the array $this->array_options. + * + * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY) + * @param User $userused Object user + * @return int -1=error, O=did nothing, 1=OK + */ + function insertExtraFields($trigger='',$userused=null) + { + global $conf,$langs,$user; + + if (empty($userused)) $userused=$user; $error=0; if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used - if (! empty($this->array_options)) - { - // Check parameters - $langs->load('admin'); - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); + if (! empty($this->array_options)) + { + // Check parameters + $langs->load('admin'); + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); - //Eliminate copied source object extra_fields that do not exist in target object - $new_array_options=array(); - foreach ($this->array_options as $key => $value) { - if (in_array(substr($key,8), array_keys($target_extrafields))) - $new_array_options[$key] = $value; - } + //Eliminate copied source object extra_fields that do not exist in target object + $new_array_options=array(); + foreach ($this->array_options as $key => $value) { + if (in_array(substr($key,8), array_keys($target_extrafields))) // We remove the 'options_' from $key + $new_array_options[$key] = $value; + } - foreach($new_array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - $attributeType = $extrafields->attribute_type[$attributeKey]; - $attributeLabel = $extrafields->attribute_label[$attributeKey]; - $attributeParam = $extrafields->attribute_param[$attributeKey]; - switch ($attributeType) - { - case 'int': - if (!is_numeric($value) && $value!='') - { - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); - return -1; - } - elseif ($value=='') - { - $new_array_options[$key] = null; - } - break; - /*case 'select': // Not required, we chosed value='0' for undefined values + foreach($new_array_options as $key => $value) + { + $attributeKey = substr($key,8); // Remove 'options_' prefix + $attributeType = $extrafields->attribute_type[$attributeKey]; + $attributeLabel = $extrafields->attribute_label[$attributeKey]; + $attributeParam = $extrafields->attribute_param[$attributeKey]; + switch ($attributeType) + { + case 'int': + if (!is_numeric($value) && $value!='') + { + $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); + return -1; + } + elseif ($value=='') + { + $new_array_options[$key] = null; + } + break; + /*case 'select': // Not required, we chosed value='0' for undefined values if ($value=='-1') { $this->array_options[$key] = null; } break;*/ - case 'price': - $new_array_options[$key] = price2num($this->array_options[$key]); - break; - case 'date': - $new_array_options[$key] = $this->db->idate($this->array_options[$key]); - break; - case 'datetime': - $new_array_options[$key] = $this->db->idate($this->array_options[$key]); - break; - case 'link': + case 'price': + $new_array_options[$key] = price2num($this->array_options[$key]); + break; + case 'date': + $new_array_options[$key] = $this->db->idate($this->array_options[$key]); + break; + case 'datetime': + $new_array_options[$key] = $this->db->idate($this->array_options[$key]); + break; + case 'link': $param_list=array_keys($attributeParam ['options']); // 0 : ObjectName // 1 : classPath $InfoFieldList = explode(":", $param_list[0]); dol_include_once($InfoFieldList[1]); - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) - { - $object = new $InfoFieldList[0]($this->db); - if ($value) - { - if (is_numeric($value)) $res=$object->fetch($value); + if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) + { + $object = new $InfoFieldList[0]($this->db); + if ($value) + { + if (is_numeric($value)) $res=$object->fetch($value); else $res=$object->fetch('',$value); - if ($res > 0) $new_array_options[$key]=$object->id; - else - { - $this->error="Ref '".$value."' for object '".$object->element."' not found"; - $this->db->rollback(); - return -1; - } - } - } - else - { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); - } + if ($res > 0) $new_array_options[$key]=$object->id; + else + { + $this->error="Ref '".$value."' for object '".$object->element."' not found"; + $this->db->rollback(); + return -1; + } + } + } + else + { + dol_syslog('Error bad setup of extrafield', LOG_WARNING); + } break; - } - } - $this->db->begin(); + } + } + $this->db->begin(); - $table_element = $this->table_element; - if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility + $table_element = $this->table_element; + if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility - $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id; - dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG); - $this->db->query($sql_del); + $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id; + dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG); + $this->db->query($sql_del); - $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object"; - foreach($new_array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - // Add field of attribut - if ($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate - $sql.=",".$attributeKey; - } - $sql .= ") VALUES (".$this->id; - foreach($new_array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - // Add field o fattribut - if($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate) - { - if ($new_array_options[$key] != '') - { - $sql.=",'".$this->db->escape($new_array_options[$key])."'"; - } - else - { - $sql.=",null"; - } - } - } - $sql.=")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object"; + foreach($new_array_options as $key => $value) + { + $attributeKey = substr($key,8); // Remove 'options_' prefix + // Add field of attribut + if ($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate + $sql.=",".$attributeKey; + } + $sql .= ") VALUES (".$this->id; - dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - else return 0; - } + foreach($new_array_options as $key => $value) + { + $attributeKey = substr($key,8); // Remove 'options_' prefix + // Add field o fattribut + if($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate) + { + if ($new_array_options[$key] != '') + { + $sql.=",'".$this->db->escape($new_array_options[$key])."'"; + } + else + { + $sql.=",null"; + } + } + } + $sql.=")"; - /** - * Update an exta field value for the current object. - * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) - * This function delte record with all extrafields and insert them again from the array $this->array_options. - * - * @param string $key Key of the extrafield - * @return int -1=error, O=did nothing, 1=OK - */ - function updateExtraField($key) - { - global $conf,$langs; + dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $error++; + } + else + { + if ($trigger) + { + // Call trigger + $this->context=array('extrafieldaddupdate'=>1); + $result=$this->call_trigger($trigger, $userused); + if ($result < 0) $error++; + // End call trigger + } + } + + if ($error) + { + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + else return 0; + } + + /** + * Update an exta field value for the current object. + * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) + * This function delte record with all extrafields and insert them again from the array $this->array_options. + * + * @param string $key Key of the extrafield + * @return int -1=error, O=did nothing, 1=OK + */ + function updateExtraField($key) + { + global $conf,$langs; $error=0; if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used - if (! empty($this->array_options) && isset($this->array_options["options_".$key])) - { - // Check parameters - $langs->load('admin'); - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); + if (! empty($this->array_options) && isset($this->array_options["options_".$key])) + { + // Check parameters + $langs->load('admin'); + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); - $value=$this->array_options["options_".$key]; - $attributeType = $extrafields->attribute_type[$key]; - $attributeLabel = $extrafields->attribute_label[$key]; - $attributeParam = $extrafields->attribute_param[$key]; - switch ($attributeType) - { - case 'int': - if (!is_numeric($value) && $value!='') - { - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); - return -1; - } - elseif ($value=='') - { - $this->array_options["options_".$key] = null; - } - break; - /*case 'select': // Not required, we chosed value='0' for undefined values + $value=$this->array_options["options_".$key]; + $attributeType = $extrafields->attribute_type[$key]; + $attributeLabel = $extrafields->attribute_label[$key]; + $attributeParam = $extrafields->attribute_param[$key]; + switch ($attributeType) + { + case 'int': + if (!is_numeric($value) && $value!='') + { + $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); + return -1; + } + elseif ($value=='') + { + $this->array_options["options_".$key] = null; + } + break; + /*case 'select': // Not required, we chosed value='0' for undefined values if ($value=='-1') { $this->array_options[$key] = null; } break;*/ - case 'price': - $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]); - break; - case 'date': - $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); - break; - case 'datetime': - $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); - break; - case 'link': - $param_list=array_keys($attributeParam ['options']); - // 0 : ObjectName - // 1 : classPath - $InfoFieldList = explode(":", $param_list[0]); - dol_include_once($InfoFieldList[1]); - $object = new $InfoFieldList[0]($this->db); - if ($value) - { - $object->fetch(0,$value); - $this->array_options["options_".$key]=$object->id; - } - break; - } + case 'price': + $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]); + break; + case 'date': + $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); + break; + case 'datetime': + $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); + break; + case 'link': + $param_list=array_keys($attributeParam ['options']); + // 0 : ObjectName + // 1 : classPath + $InfoFieldList = explode(":", $param_list[0]); + dol_include_once($InfoFieldList[1]); + $object = new $InfoFieldList[0]($this->db); + if ($value) + { + $object->fetch(0,$value); + $this->array_options["options_".$key]=$object->id; + } + break; + } - $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'"; - $sql .= " WHERE fk_object = ".$this->id; - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - else return 0; - } + $this->db->begin(); + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'"; + $sql .= " WHERE fk_object = ".$this->id; + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + else return 0; + } - /** - * Function to show lines of extrafields with output datas - * + + /** + * Return HTML string to put an input field into a page + * Code very similar with showInputField of extra fields + * + * @param array $val Array of properties for field to show + * @param string $key Key of attribute + * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) + * @param string $moreparam To add more parametes on html input tag + * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param mixed $showsize Value for css to define size. May also be a numeric. + * @return string + */ + function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0) + { + global $conf,$langs,$form; + + if (! is_object($form)) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; + $form=new Form($this->db); + } + + $objectid = $this->id; + + $label=$val['label']; + $type =$val['type']; + $size =$val['css']; + + // Convert var to be able to share same code than showInputField of extrafields + if (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar + if (is_array($val['arrayofkeyval'])) $type='select'; + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link'; + + //$elementtype=$this->attribute_elementtype[$key]; // seems to not be used + $default=$val['default']; + $computed=$val['computed']; + $unique=$val['unique']; + $required=$val['required']; + $param=$val['param']; + if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval']; + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) + { + $type='link'; + $param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]); + } + $langfile=$val['langfile']; + $list=$val['list']; + $hidden=(abs($val['visible'])!=1 ? 1 : 0); + $help=$val['help']; + + if ($computed) + { + if (! preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; + else return ''; + } + + if (empty($showsize)) + { + if ($type == 'date') + { + //$showsize=10; + $showsize = 'minwidth100imp'; + } + elseif ($type == 'datetime') + { + //$showsize=19; + $showsize = 'minwidth200imp'; + } + elseif (in_array($type,array('int','double','price'))) + { + //$showsize=10; + $showsize = 'maxwidth75'; + } + elseif ($type == 'url') + { + $showsize='minwidth400'; + } + elseif ($type == 'boolean') + { + $showsize=''; + } + else + { + if (round($size) < 12) + { + $showsize = 'minwidth100'; + } + else if (round($size) <= 48) + { + $showsize = 'minwidth200'; + } + else + { + //$showsize=48; + $showsize = 'minwidth400'; + } + } + } + + if (in_array($type,array('date','datetime'))) + { + $tmp=explode(',',$size); + $newsize=$tmp[0]; + + $showtime = in_array($type,array('datetime')) ? 1 : 0; + + // Do not show current date when field not required (see select_date() method) + if (!$required && $value == '') $value = '-1'; + + // TODO Must also support $moreparam + $out = $form->select_date($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, ($keyprefix != 'search_' ? 1 : 0), 1, 0, 1); + } + elseif (in_array($type,array('int','integer'))) + { + $tmp=explode(',',$size); + $newsize=$tmp[0]; + $out=''; + } + elseif (preg_match('/varchar/', $type)) + { + $out=''; + } + elseif (in_array($type, array('mail', 'phone', 'url'))) + { + $out=''; + } + elseif ($type == 'text') + { + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%'); + $out=$doleditor->Create(1); + } + elseif ($type == 'boolean') + { + $checked=''; + if (!empty($value)) { + $checked=' checked value="1" '; + } else { + $checked=' value="1" '; + } + $out=''; + } + elseif ($type == 'price') + { + if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. + $value=price($value); + } + $out=' '.$langs->getCurrencySymbol($conf->currency); + } + elseif ($type == 'double') + { + if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. + $value=price($value); + } + $out=' '; + } + elseif ($type == 'select') + { + $out = ''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); + } + + $out.=''; + } + elseif ($type == 'sellist') + { + $out = ''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); + } + + $out.=''; + } + elseif ($type == 'checkbox') + { + $value_arr=explode(',',$value); + $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); + } + elseif ($type == 'radio') + { + $out=''; + foreach ($param['options'] as $keyopt => $val) + { + $out.=''.$val.'
    '; + } + } + elseif ($type == 'chkbxlst') + { + if (is_array($value)) { + $value_arr = $value; + } + else { + $value_arr = explode(',', $value); + } + + if (is_array($param['options'])) { + $param_list = array_keys($param['options']); + $InfoFieldList = explode(":", $param_list[0]); + // 0 : tableName + // 1 : label field name + // 2 : key fields name (if differ of rowid) + // 3 : key field parent (for dependent lists) + // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value + $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid'); + + if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) { + list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]); + $keyList .= ', ' . $parentField; + } + if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) { + if (strpos($InfoFieldList[4], 'extra.') !== false) { + $keyList = 'main.' . $InfoFieldList[2] . ' as rowid'; + } else { + $keyList = $InfoFieldList[2] . ' as rowid'; + } + } + + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $keyList .= ', '; + $keyList .= implode(', ', $fields_label); + } + + $sqlwhere = ''; + $sql = 'SELECT ' . $keyList; + $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; + if (! empty($InfoFieldList[4])) { + + // can use SELECT request + if (strpos($InfoFieldList[4], '$SEL$')!==false) { + $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]); + } + + // current object id can be use into filter + if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) { + $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]); + } else { + $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]); + } + + // We have to join on extrafield table + if (strpos($InfoFieldList[4], 'extra') !== false) { + $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra'; + $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4]; + } else { + $sqlwhere .= ' WHERE ' . $InfoFieldList[4]; + } + } else { + $sqlwhere .= ' WHERE 1=1'; + } + // Some tables may have field, some other not. For the moment we disable it. + if (in_array($InfoFieldList[0], array ('tablewithentity'))) + { + $sqlwhere .= ' AND entity = ' . $conf->entity; + } + // $sql.=preg_replace('/^ AND /','',$sqlwhere); + // print $sql; + + $sql .= $sqlwhere; + dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + + $data=array(); + + while ( $i < $num ) { + $labeltoshow = ''; + $obj = $this->db->fetch_object($resql); + + // Several field into label (eq table:code|libelle:rowid) + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $notrans = true; + foreach ( $fields_label as $field_toshow ) { + $labeltoshow .= $obj->$field_toshow . ' '; + } + } else { + $labeltoshow = $obj->{$InfoFieldList[1]}; + } + $labeltoshow = dol_trunc($labeltoshow, 45); + + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + foreach ( $fields_label as $field_toshow ) { + $translabel = $langs->trans($obj->$field_toshow); + if ($translabel != $obj->$field_toshow) { + $labeltoshow = dol_trunc($translabel, 18) . ' '; + } else { + $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' '; + } + } + + $data[$obj->rowid]=$labeltoshow; + + } else { + if (! $notrans) { + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); + if ($translabel != $obj->{$InfoFieldList[1]}) { + $labeltoshow = dol_trunc($translabel, 18); + } else { + $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18); + } + } + if (empty($labeltoshow)) + $labeltoshow = '(not defined)'; + + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + $data[$obj->rowid]=$labeltoshow; + } + + if (! empty($InfoFieldList[3])) { + $parent = $parentName . ':' . $obj->{$parentField}; + } + + $data[$obj->rowid]=$labeltoshow; + } + + $i ++; + } + $this->db->free($resql); + + $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); + + } else { + print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.
    '; + } + } + $out .= ''; + } + elseif ($type == 'link') + { + $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' + $showempty=(($val['notnull'] == 1 && $val['default'] != '')?0:1); + $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty); + } + elseif ($type == 'password') + { + // If prefix is 'search_', field is used as a filter, we use a common text field. + $out=''; + } + if (!empty($hidden)) { + $out=''; + } + /* Add comments + if ($type == 'date') $out.=' (YYYY-MM-DD)'; + elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)'; + */ + return $out; + } + + + /** + * Return HTML string to show a field into a page + * Code very similar with showOutputField of extra fields + * + * @param array $val Array of properties of field to show + * @param string $key Key of attribute + * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) + * @param string $moreparam To add more parametes on html input tag + * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param mixed $showsize Value for css to define size. May also be a numeric. + * @return string + */ + function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0) + { + global $conf,$langs,$form; + + if (! is_object($form)) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; + $form=new Form($this->db); + } + + $objectid = $this->id; + $label=$val['label']; + $type =$val['type']; + $size =$val['css']; + + // Convert var to be able to share same code than showOutputField of extrafields + if (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar + if (is_array($val['arrayofkeyval'])) $type='select'; + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link'; + + //$elementtype=$this->attribute_elementtype[$key]; // seems to not be used + $default=$val['default']; + $computed=$val['computed']; + $unique=$val['unique']; + $required=$val['required']; + $param=$val['param']; + if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval']; + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) + { + $type='link'; + $param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]); + } + $langfile=$val['langfile']; + $list=$val['list']; + $help=$val['help']; + $hidden=(($val['visible'] == 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) + + if ($hidden) return ''; + + // 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); + } + + if (empty($showsize)) + { + if ($type == 'date') + { + $showsize=10; + } + elseif ($type == 'datetime') + { + $showsize=19; + } + elseif ($type == 'int' || $type == 'integer') + { + $showsize=10; + } + else + { + $showsize=round($size); + if ($showsize > 48) $showsize=48; + } + } + + // Format output value differently according to properties of field + if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1); + elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3); + elseif ($type == 'date') + { + $value=dol_print_date($value,'day'); + } + elseif ($type == 'datetime') + { + $value=dol_print_date($value,'dayhour'); + } + elseif ($type == 'double') + { + if (!empty($value)) { + $value=price($value); + } + } + elseif ($type == 'boolean') + { + $checked=''; + if (!empty($value)) { + $checked=' checked '; + } + $value=''; + } + elseif ($type == 'mail') + { + $value=dol_print_email($value,0,0,0,64,1,1); + } + elseif ($type == 'url') + { + $value=dol_print_url($value,'_blank',32,1); + } + elseif ($type == 'phone') + { + $value=dol_print_phone($value, '', 0, 0, '', ' ', 1); + } + elseif ($type == 'price') + { + $value=price($value,0,$langs,0,0,-1,$conf->currency); + } + elseif ($type == 'select') + { + $value=$param['options'][$value]; + } + elseif ($type == 'sellist') + { + $param_list=array_keys($param['options']); + $InfoFieldList = explode(":", $param_list[0]); + + $selectkey="rowid"; + $keyList='rowid'; + + if (count($InfoFieldList)>=3) + { + $selectkey = $InfoFieldList[2]; + $keyList=$InfoFieldList[2].' as rowid'; + } + + $fields_label = explode('|',$InfoFieldList[1]); + if(is_array($fields_label)) { + $keyList .=', '; + $keyList .= implode(', ', $fields_label); + } + + $sql = 'SELECT '.$keyList; + $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0]; + if (strpos($InfoFieldList[4], 'extra')!==false) + { + $sql.= ' as main'; + } + if ($selectkey=='rowid' && empty($value)) { + $sql.= " WHERE ".$selectkey."=0"; + } elseif ($selectkey=='rowid') { + $sql.= " WHERE ".$selectkey."=".$this->db->escape($value); + }else { + $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; + } + + //$sql.= ' AND entity = '.$conf->entity; + + dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $value=''; // value was used, so now we reste it to use it to build final output + + $obj = $this->db->fetch_object($resql); + + // Several field into label (eq table:code|libelle:rowid) + $fields_label = explode('|',$InfoFieldList[1]); + + if(is_array($fields_label) && count($fields_label)>1) + { + foreach ($fields_label as $field_toshow) + { + $translabel=''; + if (!empty($obj->$field_toshow)) { + $translabel=$langs->trans($obj->$field_toshow); + } + if ($translabel!=$field_toshow) { + $value.=dol_trunc($translabel,18).' '; + }else { + $value.=$obj->$field_toshow.' '; + } + } + } + else + { + $translabel=''; + if (!empty($obj->{$InfoFieldList[1]})) { + $translabel=$langs->trans($obj->{$InfoFieldList[1]}); + } + if ($translabel!=$obj->{$InfoFieldList[1]}) { + $value=dol_trunc($translabel,18); + }else { + $value=$obj->{$InfoFieldList[1]}; + } + } + } + else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING); + } + elseif ($type == 'radio') + { + $value=$param['options'][$value]; + } + elseif ($type == 'checkbox') + { + $value_arr=explode(',',$value); + $value=''; + if (is_array($value_arr)) + { + foreach ($value_arr as $keyval=>$valueval) { + $toprint[]='
  • '.$param['options'][$valueval].'
  • '; + } + } + $value='
      '.implode(' ', $toprint).'
    '; + } + elseif ($type == 'chkbxlst') + { + $value_arr = explode(',', $value); + + $param_list = array_keys($param['options']); + $InfoFieldList = explode(":", $param_list[0]); + + $selectkey = "rowid"; + $keyList = 'rowid'; + + if (count($InfoFieldList) >= 3) { + $selectkey = $InfoFieldList[2]; + $keyList = $InfoFieldList[2] . ' as rowid'; + } + + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $keyList .= ', '; + $keyList .= implode(', ', $fields_label); + } + + $sql = 'SELECT ' . $keyList; + $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; + if (strpos($InfoFieldList[4], 'extra') !== false) { + $sql .= ' as main'; + } + // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; + // $sql.= ' AND entity = '.$conf->entity; + + dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $value = ''; // value was used, so now we reste it to use it to build final output + $toprint=array(); + while ( $obj = $this->db->fetch_object($resql) ) { + + // Several field into label (eq table:code|libelle:rowid) + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + if (is_array($fields_label) && count($fields_label) > 1) { + foreach ( $fields_label as $field_toshow ) { + $translabel = ''; + if (! empty($obj->$field_toshow)) { + $translabel = $langs->trans($obj->$field_toshow); + } + if ($translabel != $field_toshow) { + $toprint[]='
  • '.dol_trunc($translabel, 18).'
  • '; + } else { + $toprint[]='
  • '.$obj->$field_toshow.'
  • '; + } + } + } else { + $translabel = ''; + if (! empty($obj->{$InfoFieldList[1]})) { + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); + } + if ($translabel != $obj->{$InfoFieldList[1]}) { + $toprint[]='
  • '.dol_trunc($translabel, 18).'
  • '; + } else { + $toprint[]='
  • '.$obj->{$InfoFieldList[1]}.'
  • '; + } + } + } + } + $value='
      '.implode(' ', $toprint).'
    '; + + } else { + dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING); + } + } + elseif ($type == 'link') + { + $out=''; + + // only if something to display (perf) + if ($value) + { + $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' + + $InfoFieldList = explode(":", $param_list[0]); + $classname=$InfoFieldList[0]; + $classpath=$InfoFieldList[1]; + if (! empty($classpath)) + { + dol_include_once($InfoFieldList[1]); + if ($classname && class_exists($classname)) + { + $object = new $classname($this->db); + $object->fetch($value); + $value=$object->getNomUrl(3); + } + } + else + { + dol_syslog('Error bad setup of extrafield', LOG_WARNING); + return 'Error bad setup of extrafield'; + } + } + } + elseif ($type == 'text') + { + $value=dol_htmlentitiesbr($value); + } + elseif ($type == 'password') + { + $value=preg_replace('/./i','*',$value); + } + + //print $type.'-'.$size; + $out=$value; + + return $out; + } + + + /** + * Function to show lines of extrafields with output datas + * * @param Extrafields $extrafields Extrafield Object * @param string $mode Show output (view) or input (edit) for extrafield * @param array $params Optional parameters - * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * - * @return string - */ - function showOptionals($extrafields, $mode='view', $params=null, $keyprefix='') - { - global $_POST, $conf, $langs; + * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names) + * + * @return string + */ + function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='') + { + global $_POST, $conf, $langs, $action; $out = ''; @@ -4513,6 +5619,12 @@ abstract class CommonObject $e = 0; foreach($extrafields->attribute_label as $key=>$label) { + if (empty($extrafields->attribute_list[$key])) continue; // 0 = Never visible field + if (($mode == 'create' || $mode == 'edit') && abs($extrafields->attribute_list[$key]) != 1) continue; // <> -1 and <> 1 = not visible on forms, only on list + + // Load language if required + if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]); + if (is_array($params) && count($params)>0) { if (array_key_exists('colspan',$params)) { $colspan=$params['colspan']; @@ -4520,23 +5632,29 @@ abstract class CommonObject }else { $colspan='3'; } + switch($mode) { case "view": - $value=$this->array_options["options_".$key]; + $value=$this->array_options["options_".$key.$keysuffix]; break; case "edit": - if (isset($_POST["options_" . $key])) { - if (is_array($_POST["options_" . $key])) { - // $_POST["options"] is an array but following code expects a comma separated string - $value = implode(",", $_POST["options_" . $key]); + $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none'); // GETPOST can get value from GET, POST or setup of default values. + // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc') + if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) + { + if (is_array($getposttemp)) { + // $getposttemp is an array but following code expects a comma separated string + $value = implode(",", $getposttemp); } else { - $value = $_POST["options_" . $key]; + $value = $getposttemp; } } else { - $value = $this->array_options["options_" . $key]; + $value = $this->array_options["options_" . $key]; // No GET, no POST, no default value, so we take value of object. } break; } + //var_dump($value); + if ($extrafields->attribute_type[$key] == 'separate') { $out .= $extrafields->showSeparator($key); @@ -4562,27 +5680,32 @@ abstract class CommonObject // Convert date into timestamp format (value in memory must be a timestamp) if (in_array($extrafields->attribute_type[$key],array('date','datetime'))) { - $value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$this->db->jdate($this->array_options['options_'.$key]); + $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min",'int',3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year",'int',3)):$this->db->jdate($this->array_options['options_'.$key]); } // Convert float submited string into real php numeric (value in memory must be a php numeric) if (in_array($extrafields->attribute_type[$key],array('price','double'))) { - $value = isset($_POST["options_".$key])?price2num($_POST["options_".$key]):$this->array_options['options_'.$key]; + $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix,'int',3)):$this->array_options['options_'.$key]; } - if($extrafields->attribute_required[$key]) - $label = ''.$label.''; - $out .= ''.$langs->trans($label).''; + $labeltoshow = $langs->trans($label); + + if($extrafields->attribute_required[$key]) + { + $labeltoshow = ''.$labeltoshow.''; + } + $out .= ''.$labeltoshow.''; + $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : ''; $out .=''; switch($mode) { - case "view": - $out .= $extrafields->showOutputField($key, $value); - break; - case "edit": - $out .= $extrafields->showInputField($key, $value, '', $keyprefix, '', 0, $this->id); - break; + case "view": + $out .= $extrafields->showOutputField($key, $value); + break; + case "edit": + $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id); + break; } $out .= ''; @@ -4594,8 +5717,8 @@ abstract class CommonObject } $out .= "\n"; // Add code to manage list depending on others - if (! empty($conf->use_javascript_ajax)) - $out .= ' + if (! empty($conf->use_javascript_ajax)) { + $out .= ' '."\n"; - $out .= ' '."\n"; + $out .= ' '."\n"; + } } return $out; } + /** * Returns the rights used for this class * @return stdClass @@ -4663,9 +5788,9 @@ abstract class CommonObject if (! $db->query($sql)) { - if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B. + if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B. //$this->errors = $db->lasterror(); - return false; + return false; } } @@ -4755,19 +5880,6 @@ abstract class CommonObject - - /** - * Function test if type is date - * - * @param array $info content informations of field - * @return bool - */ - protected function isDate($info) - { - if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true; - else return false; - } - /** * Function test if type is array * @@ -4800,13 +5912,26 @@ abstract class CommonObject else return false; } + + /** + * Function test if type is date + * + * @param array $info content informations of field + * @return bool + */ + public function isDate($info) + { + if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true; + else return false; + } + /** * Function test if type is integer * * @param array $info content informations of field * @return bool */ - protected function isInt($info) + public function isInt($info) { if(is_array($info)) { @@ -4822,7 +5947,7 @@ abstract class CommonObject * @param array $info content informations of field * @return bool */ - protected function isFloat($info) + public function isFloat($info) { if(is_array($info)) { @@ -4838,7 +5963,7 @@ abstract class CommonObject * @param array $info content informations of field * @return bool */ - protected function isText($info) + public function isText($info) { if(is_array($info)) { @@ -4899,7 +6024,7 @@ abstract class CommonObject else { $queryarray[$field] = (int) price2num($this->{$field}); - if (empty($queryarray[$field])) $queryarray[$field]=0; // May be rest to null later if property 'nullifempty' is on for this field. + if (empty($queryarray[$field])) $queryarray[$field]=0; // May be reset to null later if property 'notnull' is -1 for this field. } } else if($this->isFloat($info)) @@ -4913,52 +6038,55 @@ abstract class CommonObject } if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]); - if (! empty($info['nullifempty']) && empty($queryarray[$field])) $queryarray[$field] = null; + if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null; } return $queryarray; } /** - * Function to load data into current object this + * Function to load data from a SQL pointer into properties of current object $this * * @param stdClass $obj Contain data of object from database */ - private function set_vars_by_db(&$obj) + private function setVarsFromFetchObj(&$obj) { - foreach ($this->fields as $field => $info) - { - if($this->isDate($info)) - { - if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0; - else $this->{$field} = strtotime($obj->{$field}); - } - elseif($this->isArray($info)) - { - $this->{$field} = @unserialize($obj->{$field}); - // Hack for data not in UTF8 - if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field})); - } - elseif($this->isInt($info)) - { - $this->{$field} = (int) $obj->{$field}; - } - elseif($this->isFloat($info)) - { - $this->{$field} = (double) $obj->{$field}; - } - elseif($this->isNull($info)) - { - $val = $obj->{$field}; - // zero is not null - $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val); - } - else - { - $this->{$field} = $obj->{$field}; - } + foreach ($this->fields as $field => $info) + { + if($this->isDate($info)) + { + if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0; + else $this->{$field} = strtotime($obj->{$field}); + } + elseif($this->isArray($info)) + { + $this->{$field} = @unserialize($obj->{$field}); + // Hack for data not in UTF8 + if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field})); + } + elseif($this->isInt($info)) + { + if ($field == 'rowid') $this->id = (int) $obj->{$field}; + else $this->{$field} = (int) $obj->{$field}; + } + elseif($this->isFloat($info)) + { + $this->{$field} = (double) $obj->{$field}; + } + elseif($this->isNull($info)) + { + $val = $obj->{$field}; + // zero is not null + $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val); + } + else + { + $this->{$field} = $obj->{$field}; + } + } - } + // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions. + if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id; } /** @@ -4968,8 +6096,8 @@ abstract class CommonObject */ private function get_field_list() { - $keys = array_keys($this->fields); - return implode(',', $keys); + $keys = array_keys($this->fields); + return implode(',', $keys); } /** @@ -4980,9 +6108,9 @@ abstract class CommonObject * @return string */ protected function quote($value, $fieldsentry) { - if (is_null($value)) return 'NULL'; - else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value"); - else return "'".$this->db->escape($value)."'"; + if (is_null($value)) return 'NULL'; + else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value"); + else return "'".$this->db->escape($value)."'"; } @@ -4995,46 +6123,66 @@ abstract class CommonObject */ public function createCommon(User $user, $notrigger = false) { - $error = 0; + global $langs; - $now=dol_now(); + $error = 0; - $fieldvalues = $this->set_save_query(); + $now=dol_now(); + + $fieldvalues = $this->set_save_query(); if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now); - unset($fieldvalues['rowid']); // We suppose the field rowid is reserved field for autoincrement field. + if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id; + unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert. - $keys=array(); - $values = array(); - foreach ($fieldvalues as $k => $v) { - $keys[] = $k; - $values[] = $this->quote($v, $this->fields[$k]); - } + $keys=array(); + $values = array(); + foreach ($fieldvalues as $k => $v) { + $keys[$k] = $k; + $value = $this->fields[$k]; + $values[$k] = $this->quote($v, $value); + } - $this->db->begin(); + // Clean and check mandatory + foreach($keys as $key) + { + if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]=''; // This is an implicit foreign key field + if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]=''; // This is an explicit foreign key field - if (! $error) - { - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; - $sql.= ' ('.implode( ", ", $keys ).')'; - $sql.= ' VALUES ('.implode( ", ", $values ).')'; + //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1)); + if ($this->fields[$key]['notnull'] == 1 && empty($values[$key])) + { + $error++; + $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']); + } + } - $res = $this->db->query( $sql ); - if ($res===false) { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } + if ($error) return -1; - if (! $error && ! $notrigger) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); + $this->db->begin(); - if (!$notrigger) { - // Call triggers - $result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } + if (! $error) + { + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; + $sql.= ' ('.implode( ", ", $keys ).')'; + $sql.= ' VALUES ('.implode( ", ", $values ).')'; + + $res = $this->db->query($sql); + if ($res===false) { + $error++; + $this->errors[] = $this->db->lasterror(); + } + } + + if (! $error && ! $notrigger) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); + + if (!$notrigger) { + // Call triggers + $result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } // Commit or rollback if ($error) { @@ -5046,55 +6194,6 @@ abstract class CommonObject } } - /** - * Load an object from its id and create a new one in database - * - * @param User $user User that creates - * @param int $fromid Id of object to clone - * @return int New id of clone - */ - public function createFromCloneCommon(User $user, $fromid) - { - global $user, $langs; - - $error = 0; - - dol_syslog(__METHOD__, LOG_DEBUG); - - $object = new self($this->db); - - $this->db->begin(); - - // Load source object - $object->fetchCommon($fromid); - // Reset object - $object->id = 0; - - // Clear fields - $object->ref = "copy_of_".$object->ref; - $object->title = $langs->trans("CopyOf")." ".$object->title; - // ... - - // Create clone - $result = $object->createCommon($user); - - // Other options - if ($result < 0) { - $error++; - $this->error = $object->error; - $this->errors = $object->errors; - dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR); - } - - // End - if (!$error) { - $this->db->commit(); - return $object->id; - } else { - $this->db->rollback(); - return -1; - } - } /** * Load object in memory from the database @@ -5107,7 +6206,7 @@ abstract class CommonObject { if (empty($id) && empty($ref)) return false; - $sql = 'SELECT '.$this->get_field_list().', date_creation, tms'; + $sql = 'SELECT '.$this->get_field_list(); $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element; if(!empty($id)) $sql.= ' WHERE rowid = '.$id; @@ -5116,35 +6215,30 @@ abstract class CommonObject $res = $this->db->query($sql); if ($res) { - if ($obj = $this->db->fetch_object($res)) - { - if ($obj) - { - $this->id = $id; - $this->set_vars_by_db($obj); - - $this->date_creation = $this->db->idate($obj->date_creation); - $this->tms = $this->db->idate($obj->tms); - - return $this->id; - } - else - { - return 0; - } - } - else - { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - return -1; - } + if ($obj = $this->db->fetch_object($res)) + { + if ($obj) + { + $this->setVarsFromFetchObj($obj); + return $this->id; + } + else + { + return 0; + } + } + else + { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + return -1; + } } else { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - return -1; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + return -1; } } @@ -5157,53 +6251,68 @@ abstract class CommonObject */ public function updateCommon(User $user, $notrigger = false) { - $error = 0; + global $langs; + + $error = 0; + + $now=dol_now(); $fieldvalues = $this->set_save_query(); - unset($fieldvalues['rowid']); // We don't update this field, it is the key to define which record to update. + if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now); + if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id; + unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update. + $keys=array(); + $values = array(); foreach ($fieldvalues as $k => $v) { - if (is_array($key)){ - $i=array_search($k, $key); - if ( $i !== false) { - $where[] = $key[$i].'=' . $this->quote($v, $this->fields[$k]); - continue; - } - } else { - if ( $k == $key) { - $where[] = $k.'=' .$this->quote($v, $this->fields[$k]); - continue; - } - } + $keys[$k] = $k; + $value = $this->fields[$k]; + $values[$k] = $this->quote($v, $value); $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]); } + + // Clean and check mandatory + foreach($keys as $key) + { + if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]=''; // This is an implicit foreign key field + if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]=''; // This is an explicit foreign key field + + //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1)); + /* + if ($this->fields[$key]['notnull'] == 1 && empty($values[$key])) + { + $error++; + $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']); + }*/ + } + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ; $this->db->begin(); if (! $error) { - $res = $this->db->query($sql); - if ($res===false) - { - $error++; - $this->errors[] = $this->db->lasterror(); - } + $res = $this->db->query($sql); + if ($res===false) + { + $error++; + $this->errors[] = $this->db->lasterror(); + } } if (! $error && ! $notrigger) { - // Call triggers - $result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user); - if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail - // End call triggers + // Call triggers + $result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user); + if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail + // End call triggers } // Commit or rollback if ($error) { - $this->db->rollback(); - return -1; + $this->db->rollback(); + return -1; } else { - $this->db->commit(); - return $this->id; + $this->db->commit(); + return $this->id; } } @@ -5216,37 +6325,37 @@ abstract class CommonObject */ public function deleteCommon(User $user, $notrigger = false) { - $error=0; + $error=0; - $this->db->begin(); + $this->db->begin(); - if (! $error) { - if (! $notrigger) { - // Call triggers - $result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user); - if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail - // End call triggers - } - } + if (! $error) { + if (! $notrigger) { + // Call triggers + $result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user); + if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail + // End call triggers + } + } - if (! $error) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; + if (! $error) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; - $res = $this->db->query($sql); - if($res===false) { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } + $res = $this->db->query($sql); + if($res===false) { + $error++; + $this->errors[] = $this->db->lasterror(); + } + } - // Commit or rollback + // Commit or rollback if ($error) { - $this->db->rollback(); - return -1; + $this->db->rollback(); + return -1; } else { - $this->db->commit(); - return 1; + $this->db->commit(); + return 1; } } @@ -5258,9 +6367,32 @@ abstract class CommonObject */ public function initAsSpecimenCommon() { - $this->id = 0; + $this->id = 0; - // TODO... + // TODO... + } + + /** + * Load comments linked with current task + * @return boolean 1 if ok + */ + public function fetchComments() + { + require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php'; + + $comment = new Comment($this->db); + $this->comments = Comment::fetchAllFor($this->element, $this->id); + return 1; + } + + /** + * Return nb comments already posted + * + * @return int + */ + public function getNbComments() + { + return count($this->comments); } } diff --git a/htdocs/core/class/commonobjectline.class.php b/htdocs/core/class/commonobjectline.class.php index 84c49f6392d..bed227eb408 100644 --- a/htdocs/core/class/commonobjectline.class.php +++ b/htdocs/core/class/commonobjectline.class.php @@ -51,8 +51,9 @@ abstract class CommonObjectLine extends CommonObject /** - * Returns the text label from units dictionary - * + * Returns the translation key from units dictionary. + * A langs->trans() must be called on result to get translated value. + * * @param string $type Label type (long or short) * @return string|int <0 if ko, label if ok */ diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index da44eeeb6f6..e0e032d7e25 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -254,13 +254,13 @@ class Conf if (! isset($this->global->LDAP_KEY_GROUPS)) $this->global->LDAP_KEY_GROUPS=$this->global->LDAP_FIELD_FULLNAME; if (! isset($this->global->LDAP_KEY_CONTACTS)) $this->global->LDAP_KEY_CONTACTS=$this->global->LDAP_FIELD_FULLNAME; if (! isset($this->global->LDAP_KEY_MEMBERS)) $this->global->LDAP_KEY_MEMBERS=$this->global->LDAP_FIELD_FULLNAME; + if (! isset($this->global->LDAP_KEY_MEMBERS_TYPES)) $this->global->LDAP_KEY_MEMBERS_TYPES=$this->global->LDAP_FIELD_FULLNAME; // Load translation object with current language if (empty($this->global->MAIN_LANG_DEFAULT)) $this->global->MAIN_LANG_DEFAULT="en_US"; - // By default, we repeat info on all tabs - if (! isset($this->global->MAIN_REPEATCONTACTONEACHTAB)) $this->global->MAIN_REPEATCONTACTONEACHTAB=1; - if (! isset($this->global->MAIN_REPEATADDRESSONEACHTAB)) $this->global->MAIN_REPEATADDRESSONEACHTAB=1; + //if (! isset($this->global->MAIN_REPEATCONTACTONEACHTAB)) $this->global->MAIN_REPEATCONTACTONEACHTAB=1; + //if (! isset($this->global->MAIN_REPEATADDRESSONEACHTAB)) $this->global->MAIN_REPEATADDRESSONEACHTAB=1; $rootfordata = DOL_DATA_ROOT; $rootforuser = DOL_DATA_ROOT; @@ -287,15 +287,18 @@ class Conf { foreach($this->modules_parts['dir'] as $module => $dirs) { - foreach($dirs as $type => $name) + if (! empty($this->$module->enabled)) { - $subdir=($type=='temp'?'/temp':''); - // For multicompany sharings - $varname = 'multidir_'.$type; - $this->$module->$varname = array($this->entity => $rootfordata."/".$name.$subdir); - // For backward compatibility - $varname = 'dir_'.$type; - $this->$module->$varname = $rootfordata."/".$name.$subdir; + foreach($dirs as $type => $name) + { + $subdir=($type=='temp'?'/temp':''); + // For multicompany sharings + $varname = 'multidir_'.$type; + $this->$module->$varname = array($this->entity => $rootfordata."/".$name.$subdir); + // For backward compatibility + $varname = 'dir_'.$type; + $this->$module->$varname = $rootfordata."/".$name.$subdir; + } } } } @@ -584,6 +587,9 @@ class Conf $conf->global->AGENDA_DEFAULT_FILTER_TYPE='0'; // 'AC_NON_AUTO' does not exists when AGENDA_DEFAULT_FILTER_TYPE is not on. } + $conf->global->MAIN_MODULE_DOLISTORE_API_SRV='https://www.dolistore.com'; + $conf->global->MAIN_MODULE_DOLISTORE_API_KEY='dolistorecatalogpublickey1234567'; + // For backward compatibility if (isset($this->product)) $this->produit=$this->product; if (isset($this->facture)) $this->invoice=$this->facture; diff --git a/htdocs/core/class/cstate.class.php b/htdocs/core/class/cstate.class.php index a2a84d3b9ed..ae2adde87d4 100644 --- a/htdocs/core/class/cstate.class.php +++ b/htdocs/core/class/cstate.class.php @@ -85,10 +85,10 @@ class Cstate // extends CommonObject $sql.= "nom,"; $sql.= "active"; $sql.= ") VALUES ("; - $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->rowid."'").","; + $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").","; $sql.= " ".(! isset($this->code_departement)?'NULL':"'".$this->db->escape($this->code_departement)."'").","; $sql.= " ".(! isset($this->nom)?'NULL':"'".$this->db->escape($this->nom)."'").","; - $sql.= " ".(! isset($this->active)?'NULL':"'".$this->active."'").""; + $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'").""; $sql.= ")"; $this->db->begin(); diff --git a/htdocs/core/class/ctypent.class.php b/htdocs/core/class/ctypent.class.php index c7894c7c848..b3bb750bd80 100644 --- a/htdocs/core/class/ctypent.class.php +++ b/htdocs/core/class/ctypent.class.php @@ -91,10 +91,10 @@ class Ctypent // extends CommonObject $sql.= ") VALUES ("; - $sql.= " ".(! isset($this->id)?'NULL':"'".$this->id."'").","; + $sql.= " ".(! isset($this->id)?'NULL':"'".$this->db->escape($this->id)."'").","; $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; $sql.= " ".(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").","; - $sql.= " ".(! isset($this->active)?'NULL':"'".$this->active."'").","; + $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->active($this->active)."'").","; $sql.= " ".(! isset($this->module)?'NULL':"'".$this->db->escape($this->module)."'").""; diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index bef86a320ab..37dedea8b6b 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -165,7 +165,7 @@ class DiscountAbsolute $sql.= ")"; $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".$user->id.", '".$this->db->escape($this->description)."',"; $sql.= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.","; - $sql.= " ".($this->fk_facture_source?"'".$this->fk_facture_source."'":"null"); + $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null"); $sql.= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); diff --git a/htdocs/core/class/doleditor.class.php b/htdocs/core/class/doleditor.class.php index 549037a6fe2..723ae0d47b1 100644 --- a/htdocs/core/class/doleditor.class.php +++ b/htdocs/core/class/doleditor.class.php @@ -48,22 +48,23 @@ class DolEditor /** * Create an object to build an HTML area to edit a large string content * - * @param string $htmlname HTML name of WYSIWIG field - * @param string $content Content of WYSIWIG field - * @param int $width Width in pixel of edit area (auto by default) - * @param int $height Height in pixel of edit area (200px by default) - * @param string $toolbarname Name of bar set to use ('Full', 'dolibarr_notes[_encoded]', 'dolibarr_details[_encoded]'=the less featured, 'dolibarr_mailings[_encoded]', 'dolibarr_readonly') - * @param string $toolbarlocation Where bar is stored : - * 'In' each window has its own toolbar - * 'Out:name' share toolbar into the div called 'name' - * @param boolean $toolbarstartexpanded Bar is visible or not at start - * @param int $uselocalbrowser Enabled to add links to local object with local browser. If false, only external images can be added in content. - * @param int $okforextendededitor True=Allow usage of extended editor tool (like fckeditor). If false, use simple textarea. - * @param int $rows Size of rows for textarea tool - * @param string $cols Size of cols for textarea tool (textarea number of cols '70' or percent 'x%') - * @param int $readonly 0=Read/Edit, 1=Read only + * @param string $htmlname HTML name of WYSIWIG field + * @param string $content Content of WYSIWIG field + * @param int $width Width in pixel of edit area (auto by default) + * @param int $height Height in pixel of edit area (200px by default) + * @param string $toolbarname Name of bar set to use ('Full', 'dolibarr_notes[_encoded]', 'dolibarr_details[_encoded]'=the less featured, 'dolibarr_mailings[_encoded]', 'dolibarr_readonly'). + * @param string $toolbarlocation Where bar is stored : + * 'In' each window has its own toolbar + * 'Out:name' share toolbar into the div called 'name' + * @param boolean $toolbarstartexpanded Bar is visible or not at start + * @param int $uselocalbrowser Enabled to add links to local object with local browser. If false, only external images can be added in content. + * @param boolean|string $okforextendededitor True=Allow usage of extended editor tool if qualified (like ckeditor). If 'textarea', force use of simple textarea. If 'ace', force use of Ace. + * Warning: If you use 'ace', don't forget to also include ace.js in page header. Also, the button "save" must have class="buttonforacesave". + * @param int $rows Size of rows for textarea tool + * @param string $cols Size of cols for textarea tool (textarea number of cols '70' or percent 'x%') + * @param int $readonly 0=Read/Edit, 1=Read only */ - function __construct($htmlname,$content,$width='',$height=200,$toolbarname='Basic',$toolbarlocation='In',$toolbarstartexpanded=false,$uselocalbrowser=true,$okforextendededitor=true,$rows=0,$cols=0,$readonly=0) + function __construct($htmlname, $content, $width='', $height=200, $toolbarname='Basic', $toolbarlocation='In', $toolbarstartexpanded=false, $uselocalbrowser=true, $okforextendededitor=true, $rows=0, $cols=0, $readonly=0) { global $conf,$langs; @@ -80,7 +81,8 @@ class DolEditor $this->readonly=$readonly; // Check if extended editor is ok. If not we force textarea - if (empty($conf->fckeditor->enabled) || ! $okforextendededitor) $this->tool = 'textarea'; + if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) $this->tool = 'textarea'; + if ($okforextendededitor === 'ace') $this->tool='ace'; //if ($conf->dol_use_jmobile) $this->tool = 'textarea'; // ckeditor and ace seems ok with mobile // Define content and some properties @@ -122,7 +124,7 @@ class DolEditor } // Define some properties - if (in_array($this->tool,array('textarea','ckeditor'))) + if (in_array($this->tool,array('textarea','ckeditor','ace'))) { $this->content = $content; $this->htmlname = $htmlname; @@ -141,11 +143,13 @@ class DolEditor * Output depends on this->tool (fckeditor, ckeditor, textarea, ...) * * @param int $noprint 1=Return HTML string instead of printing it to output - * @param string $morejs Add more js. For example: ".on( \'saveSnapshot\', function(e) { alert(\'ee\'); });" - * @param boolean $disallowAnyContent Disallow to use any content. true=restrict to a predefined list of allowed elements. + * @param string $morejs Add more js. For example: ".on( \'saveSnapshot\', function(e) { alert(\'ee\'); });". Used by CKEditor only. + * @param boolean $disallowAnyContent Disallow to use any content. true=restrict to a predefined list of allowed elements. Used by CKEditor only. + * @param string $titlecontent Show title content before editor area. Used by ACE editor only. + * @param string $option For ACE editor, set the source language ('html', 'php', 'javascript', ...) * @return void|string */ - function Create($noprint=0,$morejs='',$disallowAnyContent=true) + function Create($noprint=0, $morejs='', $disallowAnyContent=true, $titlecontent='', $option='') { global $conf,$langs; @@ -160,13 +164,14 @@ class DolEditor if ($this->tool == 'fckeditor') // not used anymore { - $found=1; + $found=1; $this->editor->Create(); } if (in_array($this->tool,array('textarea','ckeditor'))) { $found=1; - //$out.= ''; @@ -242,11 +247,83 @@ class DolEditor filebrowserImageWindowHeight : \'500\''; } $out.= ' })'.$morejs; - $out.= '}); - '; + $out.= '});'."\n"; + $out.= ''."\n"; } } + // Output editor ACE + // Warning: ace.js and ext-statusbar.js must be loaded by the parent page. + if (preg_match('/^ace/', $this->tool)) + { + $found=1; + $format=$option; + + $out.= "\n".''."\n"; + + if ($titlecontent) + { + $out.= '
    '.$titlecontent; + $out.= '   -   '.dol_escape_htmltag($langs->trans("ShowMoreLines")).'     '; + $out.= '
    '; + $out.= ''."\n"; + } + + $out.= '
    content);
    +        	$out.= '
    '; + $out.= ''; + + $out.= ''."\n"; + } + if (empty($found)) { $out.= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.'; diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index d603d1b6cc1..f2885a50951 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -81,14 +81,16 @@ class DolGraph /** * Constructor + * + * @param string $library 'jflot' (default) or 'artichow' (no more supported) */ - function __construct() + function __construct($library='jflot') { global $conf; global $theme_bordercolor, $theme_datacolor, $theme_bgcolor, $theme_bgcoloronglet; // To use old feature - if (isset($conf->global->MAIN_GRAPH_LIBRARY) && $conf->global->MAIN_GRAPH_LIBRARY == 'artichow') + if ($library == 'artichow') { $this->_library='artichow'; @@ -586,7 +588,7 @@ class DolGraph } /** - * Build a graph onto disk using correct library + * Build a graph into memory using correct library (may also be wrote on disk, depending on library used) * * @param string $file Image file name to use to save onto disk (also used as javascript unique id) * @param string $fileurl Url path to show image if saved onto disk diff --git a/htdocs/core/class/emailsenderprofile.class.php b/htdocs/core/class/emailsenderprofile.class.php new file mode 100644 index 00000000000..7f34165030b --- /dev/null +++ b/htdocs/core/class/emailsenderprofile.class.php @@ -0,0 +1,439 @@ + + * Copyright (C) 2014-2016 Juanjo Menent + * Copyright (C) 2015 Florian Henry + * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file class/emailsenderprofile.class.php + * \ingroup monmodule + * \brief This file is a CRUD class file for EmailSenderProfile (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for EmailSenderProfile + */ +class EmailSenderProfile extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'emailsenderprofile'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'c_email_senderprofile'; + /** + * @var array Does emailsenderprofile support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 1; + /** + * @var string String with name of icon for emailsenderprofile + */ + public $picto = 'emailsenderprofile@monmodule'; + + + /** + * 'type' if the field format. + * 'label' the translation key. + * 'enabled' is a condition when the filed must be managed. + * 'visible' says if field is visible in list (-1 means not shown by default but can be added into list to be viewed). + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'position' is the sort order of field. + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'help' is a string visible as a tooltip on field + * 'comment' is not used. You can store here any text of your choice. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>-1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,), + 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1), + 'email' => array('type'=>'varchar(255)', 'label'=>'Email', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1), + //'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + //'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>-1,), + 'signature' => array('type'=>'text', 'label'=>'Signature', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,), + 'position' => array('type'=>'integer', 'label'=>'Position', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + 'active' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1), + ); + public $rowid; + public $entity; + public $label; + public $email; + public $date_creation; + public $tms; + //public $fk_user_creat; + //public $fk_user_modif; + public $signature; + public $position; + public $active; + // END MODULEBUILDER PROPERTIES + + + + // If this object has a subtable with lines + + /** + * @var int Name of subtable line + */ + //public $table_element_line = 'emailsenderprofiledet'; + /** + * @var int Field with ID of parent key if this field has a parent + */ + //public $fk_element = 'fk_emailsenderprofile'; + /** + * @var int Name of subtable class that manage subtable lines + */ + //public $class_element_line = 'EmailSenderProfileline'; + /** + * @var array Array of child tables (child tables to delete before deleting a record) + */ + //protected $childtables=array('emailsenderprofiledet'); + /** + * @var EmailSenderProfileLine[] Array of subtable lines + */ + //public $lines = array(); + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + /** + * Clone and object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $hookmanager, $langs; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $object->fetchCommon($fromid); + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + // Clear fields + $object->ref = "copy_of_".$object->ref; + $object->title = $langs->trans("CopyOf")." ".$object->title; + // ... + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetchLines() + { + $this->lines=array(); + + // Load lines with object EmailSenderProfileLine + + return count($this->lines)?1:0; + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + } + + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @return string String with URL + */ + function getNomUrl($withpicto=0) + { + global $db, $conf, $langs; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; + + $result = ''; + $companylink = ''; + + $label=$this->label; + + $url=''; + //$url = dol_buildpath('/monmodule/emailsenderprofile_card.php',1).'?id='.$this->id; + + $linkstart = ''; + $linkend=''; + + if ($withpicto) + { + $result.=($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend); + if ($withpicto != 2) $result.=' '; + } + $result.= $linkstart . $this->label . $linkend; + return $result; + } + + /** + * Return link to download file from a direct external access + * + * @param int $withpicto Add download picto into link + * @return string HTML link to file + */ + function getDirectExternalLink($withpicto=0) + { + return 'todo'; + } + + /** + * 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, 6=Long label + Picto + * @return string Label of status + */ + static function LibStatut($status,$mode=0) + { + global $langs; + + if ($mode == 0) + { + $prefix=''; + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 1) + { + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 2) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 3) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 4) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 5) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 6) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } + } + + /** + * Charge les informations d'ordre info dans l'objet commande + * + * @param int $id Id of order + * @return void + */ + function info($id) + { + $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; + $sql.= ' fk_user_creat, fk_user_modif'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql.= ' WHERE t.rowid = '.$id; + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if ($obj->fk_user_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + + } + else + { + dol_print_error($this->db); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } + +} + +/** + * Class EmailSenderProfileLine. You can also remove this and generate a CRUD class for lines objects. + */ +/* +class EmailSenderProfileLine +{ + // @var int ID + public $id; + // @var mixed Sample line property 1 + public $prop1; + // @var mixed Sample line property 2 + public $prop2; +} +*/ \ No newline at end of file diff --git a/htdocs/core/class/events.class.php b/htdocs/core/class/events.class.php index 68f033870c2..abdbb1689f8 100644 --- a/htdocs/core/class/events.class.php +++ b/htdocs/core/class/events.class.php @@ -48,7 +48,7 @@ class Events // extends CommonObject var $dateevent; var $description; - // List of all events supported by triggers + // List of all Audit/Security events supported by triggers var $eventstolog=array( array('id'=>'USER_LOGIN', 'test'=>1), array('id'=>'USER_LOGIN_FAILED', 'test'=>1), @@ -126,12 +126,12 @@ class Events // extends CommonObject $sql.= "fk_user,"; $sql.= "description"; $sql.= ") VALUES ("; - $sql.= " '".$this->type."',"; + $sql.= " '".$this->db->escape($this->type)."',"; $sql.= " ".$conf->entity.","; - $sql.= " '".$_SERVER['REMOTE_ADDR']."',"; - $sql.= " ".($_SERVER['HTTP_USER_AGENT']?"'".dol_trunc($_SERVER['HTTP_USER_AGENT'],250)."'":'NULL').","; + $sql.= " '".$this->db->escape($_SERVER['REMOTE_ADDR'])."',"; + $sql.= " ".($_SERVER['HTTP_USER_AGENT']?"'".$this->db->escape(dol_trunc($_SERVER['HTTP_USER_AGENT'],250))."'":'NULL').","; $sql.= " '".$this->db->idate($this->dateevent)."',"; - $sql.= " ".($user->id?"'".$user->id."'":'NULL').","; + $sql.= " ".($user->id?"'".$this->db->escape($user->id)."'":'NULL').","; $sql.= " '".$this->db->escape(dol_trunc($this->description,250))."'"; $sql.= ")"; diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index f6f0006a6d6..ae704edc2bd 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -65,7 +65,9 @@ class ExtraFields var $attribute_alwayseditable; // Array to store permission to check var $attribute_perms; - // Array to store permission to check + // Array to store language file to translate label of values + var $attribute_langfile; + // Array to store if field is visible by default on list var $attribute_list; // Array to store if extra field is hidden var $attribute_hidden; // warning, do not rely on this. If your module need a hidden data, it must use its own table. @@ -118,6 +120,7 @@ class ExtraFields $this->attribute_unique = array(); $this->attribute_required = array(); $this->attribute_perms = array(); + $this->attribute_langfile = array(); $this->attribute_list = array(); $this->attribute_hidden = array(); } @@ -125,24 +128,26 @@ class ExtraFields /** * Add a new extra field parameter * - * @param string $attrname Code of attribute - * @param string $label label of attribute - * @param int $type Type of attribute ('boolean', 'int', 'text', 'varchar', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...) - * @param int $pos Position of attribute - * @param string $size Size/length of attribute - * @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 (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 + * @param string $attrname Code of attribute + * @param string $label label of attribute + * @param int $type Type of attribute ('boolean', 'int', 'text', 'varchar', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...) + * @param int $pos Position of attribute + * @param string $size Size/length of attribute + * @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 (In database. use the default_value feature for default value on screen. Example: '', '0', 'null', 'avalue') + * @param array|string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) + * @param int $alwayseditable Is attribute always editable regardless of the document status + * @param string $perms Permission to check + * @param int $list Visibilty + * @param int $ishidden Deprecated. Us visibility instead. + * @param string $computed Computed value + * @param string $entity Entity of extrafields + * @param string $langfile Language file * @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, $computed='') + function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param='', $alwayseditable=0, $perms='', $list=-1, $ishidden=0, $computed='', $entity='', $langfile='') { if (empty($attrname)) return -1; if (empty($label)) return -1; @@ -159,7 +164,7 @@ class ExtraFields 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, $default, $computed); + $result2=$this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $ishidden, $default, $computed, $entity, $langfile); $err2=$this->errno; if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS')) { @@ -271,18 +276,20 @@ 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 array||string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) + * @param array|string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) * @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 int $list Visibily + * @param int $ishidden Deprecated. Use visibility instead. * @param string $default Default value (in database. use the default_value feature for default value on screen). * @param string $computed Computed value + * @param string $entity Entity of extrafields + * @param string $langfile Language file * @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, $default='', $computed='') + private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='', $alwayseditable=0, $perms='', $list=-1, $ishidden=0, $default='', $computed='',$entity='', $langfile='') { - global $conf; + global $conf,$user; if ($elementtype == 'thirdparty') $elementtype='societe'; if ($elementtype == 'contact') $elementtype='socpeople'; @@ -306,23 +313,46 @@ class ExtraFields $params=''; } - $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(name, label, type, pos, size, entity, elementtype, fieldunique, fieldrequired, param, alwayseditable, perms, list, ishidden, fielddefault, fieldcomputed)"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields("; + $sql.= " name,"; + $sql.= " label,"; + $sql.= " type,"; + $sql.= " pos,"; + $sql.= " size,"; + $sql.= " entity,"; + $sql.= " elementtype,"; + $sql.= " fieldunique,"; + $sql.= " fieldrequired,"; + $sql.= " param,"; + $sql.= " alwayseditable,"; + $sql.= " perms,"; + $sql.= " langs,"; + $sql.= " list,"; + $sql.= " fielddefault,"; + $sql.= " fieldcomputed,"; + $sql.= " fk_user_author,"; + $sql.= " fk_user_modif,"; + $sql.= " datec"; + $sql.= " )"; $sql.= " VALUES('".$attrname."',"; $sql.= " '".$this->db->escape($label)."',"; $sql.= " '".$type."',"; $sql.= " '".$pos."',"; $sql.= " '".$size."',"; - $sql.= " ".$conf->entity.","; + $sql.= " ".($entity===''?$conf->entity:$entity).","; $sql.= " '".$elementtype."',"; $sql.= " '".$unique."',"; $sql.= " '".$required."',"; $sql.= " '".$params."',"; $sql.= " '".$alwayseditable."',"; $sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").","; + $sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").","; $sql.= " ".$list.","; - $sql.= " ".$ishidden.","; $sql.= " ".($default?"'".$this->db->escape($default)."'":"null").","; - $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null"); + $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").","; + $sql .= " " . $user->id . ","; + $sql .= " " . $user->id . ","; + $sql .= "'" . $this->db->idate(dol_now()) . "'"; $sql.=')'; dol_syslog(get_class($this)."::create_label", LOG_DEBUG); @@ -442,22 +472,24 @@ class ExtraFields * * @param string $attrname Name of attribute * @param string $label Label of attribute - * @param string $type Type of attribute + * @param string $type Type of attribute ('boolean', 'int', 'text', 'varchar', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...) * @param int $length Length of attribute * @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 int $pos Position of attribute - * @param array $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) + * @param array $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) * @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 int $list Visibility + * @param int $ishidden Deprecated. Use visiblity instead. * @param string $default Default value (in database. use the default_value feature for default value on screen). * @param string $computed Computed value + * @param string $entity Entity of extrafields + * @param string $langfile Language file * @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,$default='',$computed='') + function update($attrname, $label, $type, $length, $elementtype, $unique=0, $required=0, $pos=0, $param='', $alwayseditable=0, $perms='', $list='', $ishidden=0, $default='', $computed='', $entity='', $langfile='') { if ($elementtype == 'thirdparty') $elementtype='societe'; if ($elementtype == 'contact') $elementtype='socpeople'; @@ -495,7 +527,7 @@ class ExtraFields $typedb=$type; $lengthdb=$length; } - $field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required?'NOT NULL':'NULL')); + $field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required?'NOT NULL':'NULL'), 'default'=>$default); if ($type != 'separate') // No table update when separate type { @@ -505,7 +537,7 @@ class ExtraFields { if ($label) { - $result=$this->update_label($attrname,$label,$type,$length,$elementtype,$unique,$required,$pos,$param,$alwayseditable,$perms,$list,$ishidden,$default,$computed); + $result=$this->update_label($attrname,$label,$type,$length,$elementtype,$unique,$required,$pos,$param,$alwayseditable,$perms,$list,$ishidden,$default,$computed,$entity,$langfile); } if ($result > 0) { @@ -555,16 +587,18 @@ class ExtraFields * @param array $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) * @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 int $list Visiblity + * @param int $ishidden Deprecated. Use visility instead. * @param string $default Default value (in database. use the default_value feature for default value on screen). * @param string $computed Computed value + * @param string $entity Entity of extrafields + * @param string $langfile Language file * @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,$default='',$computed='') + 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='',$entity='',$langfile='') { - global $conf; - dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$ishidden.", ".$default.", ".$computed); + global $conf, $user; + dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$ishidden.", ".$default.", ".$computed.", ".$entity.", ".$langfile); // Clean parameters if ($elementtype == 'thirdparty') $elementtype='societe'; @@ -583,7 +617,7 @@ class ExtraFields $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields"; $sql_del.= " WHERE name = '".$attrname."'"; - $sql_del.= " AND entity = ".$conf->entity; + $sql_del.= " AND entity = ".($entity===''?$conf->entity:$entity); $sql_del.= " AND elementtype = '".$elementtype."'"; $resql1=$this->db->query($sql_del); @@ -598,16 +632,19 @@ class ExtraFields $sql.= " fieldunique,"; $sql.= " fieldrequired,"; $sql.= " perms,"; + $sql.= " langs,"; $sql.= " pos,"; $sql.= " alwayseditable,"; $sql.= " param,"; $sql.= " list,"; - $sql.= " ishidden,"; $sql.= " fielddefault,"; - $sql.= " fieldcomputed"; + $sql.= " fieldcomputed,"; + $sql.= " fk_user_author,"; + $sql.= " fk_user_modif,"; + $sql.= " datec"; $sql.= ") VALUES ("; $sql.= "'".$attrname."',"; - $sql.= " ".$conf->entity.","; + $sql.= " ".($entity===''?$conf->entity:$entity).","; $sql.= " '".$this->db->escape($label)."',"; $sql.= " '".$type."',"; $sql.= " '".$size."',"; @@ -615,13 +652,16 @@ class ExtraFields $sql.= " '".$unique."',"; $sql.= " '".$required."',"; $sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").","; + $sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").","; $sql.= " '".$pos."',"; $sql.= " '".$alwayseditable."',"; $sql.= " '".$param."',"; $sql.= " ".$list.", "; - $sql.= " ".$ishidden.", "; - $sql.= " ".($default?"'".$this->db->escape($default)."'":"null").","; - $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null"); + $sql.= " ".(($default!='')?"'".$this->db->escape($default)."'":"null").","; + $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").","; + $sql .= " " . $user->id . ","; + $sql .= " " . $user->id . ","; + $sql .= "'" . $this->db->idate(dol_now()) . "'"; $sql.= ")"; $resql2=$this->db->query($sql); @@ -670,7 +710,8 @@ class ExtraFields // We should not have several time this log. If we have, there is some optimization to do by calling a simple $object->fetch_optionals() that include cache management. dol_syslog("fetch_name_optionals_label elementtype=".$elementtype); - $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,list,ishidden,fielddefault,fieldcomputed"; + $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,fielddefault,fieldcomputed"; + $sql .= ",entity"; $sql.= " FROM ".MAIN_DB_PREFIX."extrafields"; $sql.= " WHERE entity IN (0,".$conf->entity.")"; if ($elementtype) $sql.= " AND elementtype = '".$elementtype."'"; @@ -702,8 +743,9 @@ class ExtraFields $this->attribute_pos[$tab->name]=$tab->pos; $this->attribute_alwayseditable[$tab->name]=$tab->alwayseditable; $this->attribute_perms[$tab->name]=$tab->perms; + $this->attribute_langfile[$tab->name]=$tab->langs; $this->attribute_list[$tab->name]=$tab->list; - $this->attribute_hidden[$tab->name]=$tab->ishidden; + $this->attribute_entityid[$tab->name]=$tab->entity; // New usage $this->attributes[$tab->elementtype]['type'][$tab->name]=$tab->type; @@ -718,8 +760,26 @@ class ExtraFields $this->attributes[$tab->elementtype]['pos'][$tab->name]=$tab->pos; $this->attributes[$tab->elementtype]['alwayseditable'][$tab->name]=$tab->alwayseditable; $this->attributes[$tab->elementtype]['perms'][$tab->name]=$tab->perms; + $this->attributes[$tab->elementtype]['langfile'][$tab->name]=$tab->langs; $this->attributes[$tab->elementtype]['list'][$tab->name]=$tab->list; - $this->attributes[$tab->elementtype]['ishidden'][$tab->name]=$tab->ishidden; + $this->attributes[$tab->elementtype]['entityid'][$tab->name]=$tab->entity; + + if (!empty($conf->multicompany->enabled)) + { + $sql_entity_name='SELECT label FROM '.MAIN_DB_PREFIX.'entity WHERE rowid='.$tab->entity; + $resql_entity_name=$this->db->query($sql_entity_name); + if ($resql_entity_name) + { + if ($this->db->num_rows($resql_entity_name)) + { + if ($obj = $this->db->fetch_object($resql_entity_name)) + { + $this->attribute_entitylabel[$tab->name]=$obj->label; + $this->attributes[$tab->elementtype]['entitylabel'][$tab->name]=$obj->label; + } + } + } + } } } if ($elementtype) $this->attributes[$elementtype]['loaded']=1; @@ -736,80 +796,89 @@ class ExtraFields /** * Return HTML string to put an input field into a page + * Code very similar with showInputField of common object * * @param string $key Key of attribute * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) * @param string $moreparam To add more parametes on html input tag - * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * @param string $keysuffix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keysuffix Prefix string to add after name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add before name and id of field (can be used to avoid duplicate names) * @param mixed $showsize Value for css to define size. May also be a numeric. * @param int $objectid Current object id * @return string */ - function showInputField($key, $value, $moreparam='', $keyprefix='', $keysuffix='', $showsize=0, $objectid=0) + function showInputField($key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0, $objectid=0) { - global $conf,$langs; + global $conf,$langs,$form; + + if (! is_object($form)) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; + $form=new Form($this->db); + } + + $keyprefix = $keyprefix.'options_'; // Because we work on extrafields $label=$this->attribute_label[$key]; $type =$this->attribute_type[$key]; $size =$this->attribute_size[$key]; - $elementtype=$this->attribute_elementtype[$key]; + $elementtype=$this->attribute_elementtype[$key]; // Seems not used $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]; - $perms=$this->attribute_perms[$key]; + $langfile=$this->attribute_langfile[$key]; $list=$this->attribute_list[$key]; $hidden=$this->attribute_hidden[$key]; if ($computed) { - if ($keysuffix != 'search_') return ''.$langs->trans("AutomaticallyCalculated").''; - else return ''; + if (! preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; + else return ''; } if (empty($showsize)) { - if ($type == 'date') - { - //$showsize=10; - $showsize = 'minwidth100imp'; - } + if ($type == 'date') + { + //$showsize=10; + $showsize = 'minwidth100imp'; + } elseif ($type == 'datetime') - { - //$showsize=19; - $showsize = 'minwidth200imp'; - } - elseif (in_array($type,array('int','double','price'))) - { - //$showsize=10; - $showsize = 'maxwidth75'; - } - elseif ($type == 'url') - { - $showsize='minwidth400'; - } - elseif ($type == 'boolean') - { - $showsize=''; - } - else - { - if (round($size) < 12) - { - $showsize = 'minwidth100'; - } - else if (round($size) <= 48) - { - $showsize = 'minwidth200'; - } - else - { - //$showsize=48; - $showsize = 'minwidth400'; - } - } + { + //$showsize=19; + $showsize = 'minwidth200imp'; + } + elseif (in_array($type,array('int','integer','double','price'))) + { + //$showsize=10; + $showsize = 'maxwidth75'; + } + elseif ($type == 'url') + { + $showsize='minwidth400'; + } + elseif ($type == 'boolean') + { + $showsize=''; + } + else + { + if (round($size) < 12) + { + $showsize = 'minwidth100'; + } + else if (round($size) <= 48) + { + $showsize = 'minwidth200'; + } + else + { + //$showsize=48; + $showsize = 'minwidth400'; + } + } } if (in_array($type,array('date','datetime'))) @@ -822,31 +891,27 @@ class ExtraFields // Do not show current date when field not required (see select_date() method) if (!$required && $value == '') $value = '-1'; - require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - global $form; - if (! is_object($form)) $form=new Form($this->db); - // TODO Must also support $moreparam - $out = $form->select_date($value, $keysuffix.'options_'.$key.$keyprefix, $showtime, $showtime, $required, '', 1, 1, 1, 0, 1); + $out = $form->select_date($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, ($keyprefix != 'search_' ? 1 : 0), 1, 0, 1); } - elseif (in_array($type,array('int'))) + elseif (in_array($type,array('int','integer'))) { $tmp=explode(',',$size); $newsize=$tmp[0]; - $out=''; + $out=''; } - elseif ($type == 'varchar') + elseif (preg_match('/varchar/', $type)) { - $out=''; + $out=''; } elseif (in_array($type, array('mail', 'phone', 'url'))) { - $out=''; + $out=''; } elseif ($type == 'text') { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($keysuffix.'options_'.$key.$keyprefix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%'); + $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%'); $out=$doleditor->Create(1); } elseif ($type == 'boolean') @@ -857,21 +922,21 @@ class ExtraFields } else { $checked=' value="1" '; } - $out=''; + $out=''; } elseif ($type == 'price') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value=price($value); } - $out.=' '.$langs->getCurrencySymbol($conf->currency); + $out=' '.$langs->getCurrencySymbol($conf->currency); } elseif ($type == 'double') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value=price($value); } - $out=' '; + $out=' '; } elseif ($type == 'select') { @@ -879,10 +944,10 @@ class ExtraFields if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keysuffix.'options_'.$key.$keyprefix, array(), 0); + $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } - $out.=''; $out.=''; foreach ($param['options'] as $key => $val) { @@ -901,14 +966,16 @@ class ExtraFields if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keysuffix.'options_'.$key.$keyprefix, array(), 0); + $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } - $out.=''; if (is_array($param['options'])) { $param_list=array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); + $parentName=''; + $parentField=''; // 0 : tableName // 1 : label field name // 2 : key fields name (if differ of rowid) @@ -993,8 +1060,9 @@ class ExtraFields $obj = $this->db->fetch_object($resql); // Several field into label (eq table:code|libelle:rowid) + $notrans = false; $fields_label = explode('|',$InfoFieldList[1]); - if(is_array($fields_label)) + if (is_array($fields_label)) { $notrans = true; foreach ($fields_label as $field_toshow) @@ -1008,7 +1076,7 @@ class ExtraFields } $labeltoshow=dol_trunc($labeltoshow,45); - if ($value==$obj->rowid) + if ($value == $obj->rowid) { foreach ($fields_label as $field_toshow) { @@ -1023,7 +1091,7 @@ class ExtraFields } else { - if(!$notrans) + if (! $notrans) { $translabel=$langs->trans($obj->{$InfoFieldList[1]}); if ($translabel!=$obj->{$InfoFieldList[1]}) { @@ -1039,7 +1107,7 @@ class ExtraFields $out.=''; } - if (!empty($InfoFieldList[3])) + if (!empty($InfoFieldList[3]) && $parentField) { $parent = $parentName.':'.$obj->{$parentField}; } @@ -1062,23 +1130,19 @@ class ExtraFields } elseif ($type == 'checkbox') { - require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $form = new Form($db); - $value_arr=explode(',',$value); - $out=$form->multiselectarray($keysuffix.'options_'.$key.$keyprefix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); - + $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); } elseif ($type == 'radio') { $out=''; foreach ($param['options'] as $keyopt => $val) { - $out.=''.$val.'
    '; + $out.='/>
    '; } } elseif ($type == 'chkbxlst') @@ -1093,6 +1157,8 @@ class ExtraFields if (is_array($param['options'])) { $param_list = array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); + $parentName=''; + $parentField=''; // 0 : tableName // 1 : label field name // 2 : key fields name (if differ of rowid) @@ -1166,6 +1232,7 @@ class ExtraFields $labeltoshow = ''; $obj = $this->db->fetch_object($resql); + $notrans = false; // Several field into label (eq table:code|libelle:rowid) $fields_label = explode('|', $InfoFieldList[1]); if (is_array($fields_label)) { @@ -1202,89 +1269,63 @@ class ExtraFields if (empty($labeltoshow)) $labeltoshow = '(not defined)'; - if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + $data[$obj->rowid]=$labeltoshow; + } + + if (! empty($InfoFieldList[3]) && $parentField) { + $parent = $parentName . ':' . $obj->{$parentField}; + } + $data[$obj->rowid]=$labeltoshow; - } - - if (! empty($InfoFieldList[3])) { - $parent = $parentName . ':' . $obj->{$parentField}; - } - - $data[$obj->rowid]=$labeltoshow; } $i ++; } $this->db->free($resql); - require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $form = new Form($db); - - $out=$form->multiselectarray($keysuffix.'options_'.$key.$keyprefix, $data, $value_arr, '', 0, '', 0, '100%'); + $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); } else { print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.
    '; } } - $out .= ''; } elseif ($type == 'link') { - $out=''; - - $param_list=array_keys($param['options']); - // 0 : ObjectName - // 1 : classPath - $InfoFieldList = explode(":", $param_list[0]); - dol_include_once($InfoFieldList[1]); - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) - { - $valuetoshow=$value; - if (!empty($value)) - { - $object = new $InfoFieldList[0]($this->db); - $resfetch=$object->fetch($value); - if ($resfetch > 0) - { - $valuetoshow=$object->ref; - if ($object->element == 'societe') $valuetoshow=$object->name; // Special case for thirdparty because ->ref is not name but id (because name is not unique) - } - } - $out.=''; - } - else - { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); - $out.='Error bad setup of extrafield'; - } + $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' + $showempty=(($required && $default != '')?0:1); + $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty); } elseif ($type == 'password') { - $out=''; + // If prefix is 'search_', field is used as a filter, we use a common text field. + $out=''; } if (!empty($hidden)) { - $out=''; + $out=''; } /* Add comments if ($type == 'date') $out.=' (YYYY-MM-DD)'; - elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)'; - */ + elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)'; + */ return $out; } + /** * Return HTML string to put an output field into a page * * @param string $key Key of attribute * @param string $value Value to show - * @param string $moreparam To add more parametes on html input tag (only checkbox use html input for output rendering) + * @param string $moreparam To add more parameters on html input tag (only checkbox use html input for output rendering) * @return string Formated value */ function showOutputField($key,$value,$moreparam='') { global $conf,$langs; - $elementtype=$this->attribute_elementtype[$key]; + $elementtype=$this->attribute_elementtype[$key]; // seems not used $label=$this->attribute_label[$key]; $type=$this->attribute_type[$key]; $size=$this->attribute_size[$key]; @@ -1292,10 +1333,13 @@ class ExtraFields $computed=$this->attribute_computed[$key]; $unique=$this->attribute_unique[$key]; $required=$this->attribute_required[$key]; - $params=$this->attribute_param[$key]; + $param=$this->attribute_param[$key]; $perms=$this->attribute_perms[$key]; + $langfile=$this->attribute_langfile[$key]; $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. + $hidden=(($list != 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) + + if ($hidden) return ''; // This is a protection. If field is hidden, we should just not call this method. // If field is a computed field, value must become result of compute if ($computed) @@ -1352,11 +1396,11 @@ class ExtraFields } elseif ($type == 'select') { - $value=$params['options'][$value]; + $value=$param['options'][$value]; } elseif ($type == 'sellist') { - $param_list=array_keys($params['options']); + $param_list=array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); $selectkey="rowid"; @@ -1433,16 +1477,17 @@ class ExtraFields } elseif ($type == 'radio') { - $value=$params['options'][$value]; + $value=$param['options'][$value]; } elseif ($type == 'checkbox') { $value_arr=explode(',',$value); $value=''; + $toprint=array(); if (is_array($value_arr)) { foreach ($value_arr as $keyval=>$valueval) { - $toprint[]='
  • '.$params['options'][$valueval].'
  • '; + $toprint[]='
  • '.$param['options'][$valueval].'
  • '; } } $value='
      '.implode(' ', $toprint).'
    '; @@ -1451,7 +1496,7 @@ class ExtraFields { $value_arr = explode(',', $value); - $param_list = array_keys($params['options']); + $param_list = array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); $selectkey = "rowid"; @@ -1523,22 +1568,26 @@ class ExtraFields // only if something to display (perf) if ($value) { - $param_list=array_keys($params['options']); - // 0 : ObjectName - // 1 : classPath + $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' + $InfoFieldList = explode(":", $param_list[0]); - dol_include_once($InfoFieldList[1]); - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) - { - $object = new $InfoFieldList[0]($this->db); - $object->fetch($value); - $value=$object->getNomUrl(3); - } - else - { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); - $out.='Error bad setup of extrafield'; - } + $classname=$InfoFieldList[0]; + $classpath=$InfoFieldList[1]; + if (! empty($classpath)) + { + dol_include_once($InfoFieldList[1]); + if ($classname && class_exists($classname)) + { + $object = new $classname($this->db); + $object->fetch($value); + $value=$object->getNomUrl(3); + } + } + else + { + dol_syslog('Error bad setup of extrafield', LOG_WARNING); + return 'Error bad setup of extrafield'; + } } } elseif ($type == 'text') @@ -1558,10 +1607,6 @@ class ExtraFields //print $type.'-'.$size; $out=$value; - if (!empty($hidden)) { - $out=''; - } - return $out; } @@ -1619,7 +1664,7 @@ class ExtraFields */ function showSeparator($key) { - $out = ''.$this->attribute_label[$key].''; + $out = ''.$this->attribute_label[$key].''; return $out; } @@ -1645,7 +1690,7 @@ class ExtraFields if (! empty($onlykey) && $key != $onlykey) continue; $key_type = $this->attribute_type[$key]; - if($this->attribute_required[$key] && !GETPOST("options_$key",2)) + if ($this->attribute_required[$key] && empty($_POST["options_".$key])) // Check if empty without GETPOST, value can be alpha, int, array, etc... { $nofillrequired++; $error_field_required[] = $value; @@ -1658,7 +1703,7 @@ class ExtraFields } else if (in_array($key_type,array('checkbox','chkbxlst'))) { - $value_arr=GETPOST("options_".$key); + $value_arr=GETPOST("options_".$key, 'array'); // check if an array if (!empty($value_arr)) { $value_key=implode($value_arr,','); }else { @@ -1677,7 +1722,7 @@ class ExtraFields $object->array_options["options_".$key]=$value_key; } - if($nofillrequired) { + if ($nofillrequired) { $langs->load('errors'); setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ',$error_field_required), null, 'errors'); return -1; diff --git a/htdocs/core/class/fiscalyear.class.php b/htdocs/core/class/fiscalyear.class.php index a273443ef7c..5e5ff6e3ce8 100644 --- a/htdocs/core/class/fiscalyear.class.php +++ b/htdocs/core/class/fiscalyear.class.php @@ -32,7 +32,7 @@ class Fiscalyear extends CommonObject public $table_element='accounting_fiscalyear'; public $table_element_line = ''; public $fk_element = ''; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe var $rowid; @@ -86,7 +86,7 @@ class Fiscalyear extends CommonObject $sql.= ", datec"; $sql.= ", fk_user_author"; $sql.= ") VALUES ("; - $sql.= " '".$this->label."'"; + $sql.= " '".$this->db->escape($this->label)."'"; $sql.= ", '".$this->db->idate($this->date_start)."'"; $sql.= ", ".($this->date_end ? "'".$this->db->idate($this->date_end)."'":"null"); $sql.= ", 0"; diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 71b7b42fdcd..7df1fd1f4a2 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -46,527 +46,536 @@ */ class Form { - var $db; - var $error; - var $num; + var $db; + var $error; + var $num; - // Cache arrays - var $cache_types_paiements=array(); - var $cache_conditions_paiements=array(); - var $cache_availability=array(); - var $cache_demand_reason=array(); - var $cache_types_fees=array(); - var $cache_vatrates=array(); + // Cache arrays + var $cache_types_paiements=array(); + var $cache_conditions_paiements=array(); + var $cache_availability=array(); + var $cache_demand_reason=array(); + var $cache_types_fees=array(); + var $cache_vatrates=array(); - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Output key field for an editable field - * - * @param string $text Text of label or key to translate - * @param string $htmlname Name of select field ('edit' prefix will be added) - * @param string $preselected Value to show/edit (not used in this function) - * @param object $object Object - * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field. - * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...) - * @param string $moreparam More param to add on a href URL. - * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS. - * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' ' - * @return string HTML edit field - */ - function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0) - { - global $conf,$langs; + /** + * Output key field for an editable field + * + * @param string $text Text of label or key to translate + * @param string $htmlname Name of select field ('edit' prefix will be added) + * @param string $preselected Value to show/edit (not used in this function) + * @param object $object Object + * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field. + * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...) + * @param string $moreparam More param to add on a href URL. + * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS. + * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' ' + * @return string HTML edit field + */ + function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0) + { + global $conf,$langs; - $ret=''; + $ret=''; - // TODO change for compatibility - if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata)) - { - if (! empty($perm)) - { - $tmp=explode(':',$typeofdata); - $ret.= '
    '; - if ($fieldrequired) $ret.=''; - $ret.= $langs->trans($text); - if ($fieldrequired) $ret.=''; - $ret.= '
    '."\n"; - } - else - { - if ($fieldrequired) $ret.=''; - $ret.= $langs->trans($text); - if ($fieldrequired) $ret.=''; - } - } - else + // TODO change for compatibility + if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata)) { - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='
    '; - if ($fieldrequired) $ret.=''; - $ret.=$langs->trans($text); - if ($fieldrequired) $ret.=''; - if (! empty($notabletag)) $ret.=' '; - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; - if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).''; - if (! empty($notabletag) && $notabletag == 1) $ret.=' : '; - if (! empty($notabletag) && $notabletag == 3) $ret.=' '; - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='
    '; - } + if (! empty($perm)) + { + $tmp=explode(':',$typeofdata); + $ret.= '
    '; + if ($fieldrequired) $ret.=''; + $ret.= $langs->trans($text); + if ($fieldrequired) $ret.=''; + $ret.= '
    '."\n"; + } + else + { + if ($fieldrequired) $ret.=''; + $ret.= $langs->trans($text); + if ($fieldrequired) $ret.=''; + } + } + else + { + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='
    '; + if ($fieldrequired) $ret.=''; + $ret.=$langs->trans($text); + if ($fieldrequired) $ret.=''; + if (! empty($notabletag)) $ret.=' '; + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; + if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).''; + if (! empty($notabletag) && $notabletag == 1) $ret.=' : '; + if (! empty($notabletag) && $notabletag == 3) $ret.=' '; + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='
    '; + } - return $ret; - } + return $ret; + } - /** - * Output val field for an editable field - * - * @param string $text Text of label (not used in this function) - * @param string $htmlname Name of select field - * @param string $value Value to show/edit - * @param object $object Object - * @param boolean $perm Permission to allow button to edit parameter - * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...) - * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value - * @param object $extObject External object - * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') - * @param string $moreparam More param to add on a href URL - * @param int $notabletag Do no output table tags - * @return string HTML edit field - */ - function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0) - { - global $conf,$langs,$db; + /** + * Output value of a field for an editable field + * + * @param string $text Text of label (not used in this function) + * @param string $htmlname Name of select field + * @param string $value Value to show/edit + * @param object $object Object + * @param boolean $perm Permission to allow button to edit parameter + * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...) + * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value + * @param object $extObject External object + * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') + * @param string $moreparam More param to add on a href URL + * @param int $notabletag Do no output table tags + * @param string $formatfunc Call a specific function to output field + * @return string HTML edit field + */ + function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='') + { + global $conf,$langs,$db; - $ret=''; + $ret=''; - // Check parameters - if (empty($typeofdata)) return 'ErrorBadParameter'; + // Check parameters + if (empty($typeofdata)) return 'ErrorBadParameter'; - // When option to edit inline is activated - if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker - { - $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg); - } - else - { - if (GETPOST('action','aZ09') == 'edit'.$htmlname) - { - $ret.="\n"; - $ret.='
    '; - $ret.=''; - $ret.=''; - $ret.=''; - if (empty($notabletag)) $ret.=''; - if (empty($notabletag)) $ret.=''; + // When option to edit inline is activated + if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker + { + $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg); + } + else + { + if (GETPOST('action','aZ09') == 'edit'.$htmlname) + { + $ret.="\n"; + $ret.=''; + $ret.=''; + $ret.=''; + $ret.=''; + if (empty($notabletag)) $ret.='
    '; - if (preg_match('/^(string|email)/',$typeofdata)) - { - $tmp=explode(':',$typeofdata); - $ret.=''; - } - else if (preg_match('/^(numeric|amount)/',$typeofdata)) - { - $tmp=explode(':',$typeofdata); - $valuetoshow=price2num($editvalue?$editvalue:$value); - $ret.=''; - } - else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) - { - $tmp=explode(':',$typeofdata); - $cols=$tmp[2]; - $morealt=''; - if (preg_match('/%/',$cols)) - { - $morealt=' style="width: '.$cols.'"'; - $cols=''; - } - $ret.=''; - } - else if ($typeofdata == 'day' || $typeofdata == 'datepicker') - { - $ret.=$this->select_date($value,$htmlname,0,0,1,'form'.$htmlname,1,0,1); - } - else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') - { - $ret.=$this->select_date($value,$htmlname,1,1,1,'form'.$htmlname,1,0,1); - } - else if (preg_match('/^select;/',$typeofdata)) - { - $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata)); - foreach($arraydata as $val) - { - $tmp=explode(':',$val); - $arraylist[$tmp[0]]=$tmp[1]; - } - $ret.=$this->selectarray($htmlname,$arraylist,$value); - } - else if (preg_match('/^ckeditor/',$typeofdata)) - { - $tmp=explode(':',$typeofdata); - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100')); - $ret.=$doleditor->Create(1); - } - if (empty($notabletag)) $ret.='
    '; + if (empty($notabletag)) $ret.=''; - if (empty($notabletag)) $ret.=''; + if (empty($notabletag)) $ret.=''; - if (empty($notabletag)) $ret.='
    '; + if (preg_match('/^(string|email)/',$typeofdata)) + { + $tmp=explode(':',$typeofdata); + $ret.=''; + } + else if (preg_match('/^(numeric|amount)/',$typeofdata)) + { + $tmp=explode(':',$typeofdata); + $valuetoshow=price2num($editvalue?$editvalue:$value); + $ret.=''; + } + else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) + { + $tmp=explode(':',$typeofdata); + $cols=$tmp[2]; + $morealt=''; + if (preg_match('/%/',$cols)) + { + $morealt=' style="width: '.$cols.'"'; + $cols=''; + } + $ret.=''; + } + else if ($typeofdata == 'day' || $typeofdata == 'datepicker') + { + $ret.=$this->select_date($value,$htmlname,0,0,1,'form'.$htmlname,1,0,1); + } + else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') + { + $ret.=$this->select_date($value,$htmlname,1,1,1,'form'.$htmlname,1,0,1); + } + else if (preg_match('/^select;/',$typeofdata)) + { + $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata)); + foreach($arraydata as $val) + { + $tmp=explode(':',$val); + $arraylist[$tmp[0]]=$tmp[1]; + } + $ret.=$this->selectarray($htmlname,$arraylist,$value); + } + else if (preg_match('/^ckeditor/',$typeofdata)) + { + $tmp=explode(':',$typeofdata); + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100')); + $ret.=$doleditor->Create(1); + } + if (empty($notabletag)) $ret.=''; - //else $ret.='
    '; - $ret.=''; - if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='
    '."\n"; - $ret.=''; - if (empty($notabletag)) $ret.='
    '; + //else $ret.='
    '; + $ret.=''; + if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='
    '."\n"; + $ret.=''; + if (empty($notabletag)) $ret.='
    '."\n"; - $ret.='
    '."\n"; - } - else + if (empty($notabletag)) $ret.=''."\n"; + $ret.=''."\n"; + } + else { if (preg_match('/^(email)/',$typeofdata)) $ret.=dol_print_email($value,0,0,0,0,1); - elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : ''); - elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value); - elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day'); - elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour'); - else if (preg_match('/^select;/',$typeofdata)) - { - $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata)); - foreach($arraydata as $val) - { - $tmp=explode(':',$val); - $arraylist[$tmp[0]]=$tmp[1]; - } - $ret.=$arraylist[$value]; - } - else if (preg_match('/^ckeditor/',$typeofdata)) - { - $tmpcontent=dol_htmlentitiesbr($value); - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $firstline=preg_replace('/
    .*/','',$tmpcontent); - $firstline=preg_replace('/[\n\r].*/','',$firstline); - $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':''); - } - $ret.=$tmpcontent; - } - else $ret.=$value; - } - } - return $ret; - } + elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : ''); + elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value); + elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day'); + elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour'); + else if (preg_match('/^select;/',$typeofdata)) + { + $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata)); + foreach($arraydata as $val) + { + $tmp=explode(':',$val); + $arraylist[$tmp[0]]=$tmp[1]; + } + $ret.=$arraylist[$value]; + } + else if (preg_match('/^ckeditor/',$typeofdata)) + { + $tmpcontent=dol_htmlentitiesbr($value); + if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $firstline=preg_replace('/
    .*/','',$tmpcontent); + $firstline=preg_replace('/[\n\r].*/','',$firstline); + $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':''); + } + $ret.=$tmpcontent; + } + else $ret.=$value; - /** - * Output edit in place form - * - * @param object $object Object - * @param string $value Value to show/edit - * @param string $htmlname DIV ID (field name) - * @param int $condition Condition to edit - * @param string $inputType Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx') - * @param string $editvalue When in edit mode, use this value as $value instead of value - * @param object $extObject External object - * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') - * @return string HTML edit in place - */ - private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null) - { - global $conf; + if ($formatfunc && method_exists($object, $formatfunc)) + { + $ret=$object->$formatfunc($ret); + } + } + } + return $ret; + } - $out=''; + /** + * Output edit in place form + * + * @param object $object Object + * @param string $value Value to show/edit + * @param string $htmlname DIV ID (field name) + * @param int $condition Condition to edit + * @param string $inputType Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx') + * @param string $editvalue When in edit mode, use this value as $value instead of value + * @param object $extObject External object + * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') + * @return string HTML edit in place + */ + private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null) + { + global $conf; - // Check parameters - if ($inputType == 'textarea') $value = dol_nl2br($value); - else if (preg_match('/^numeric/',$inputType)) $value = price($value); - else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day'); + $out=''; - if ($condition) - { - $element = false; - $table_element = false; - $fk_element = false; - $loadmethod = false; - $savemethod = false; - $ext_element = false; - $button_only = false; - $inputOption = ''; + // Check parameters + if ($inputType == 'textarea') $value = dol_nl2br($value); + else if (preg_match('/^numeric/',$inputType)) $value = price($value); + else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day'); - if (is_object($object)) - { - $element = $object->element; - $table_element = $object->table_element; - $fk_element = $object->id; - } + if ($condition) + { + $element = false; + $table_element = false; + $fk_element = false; + $loadmethod = false; + $savemethod = false; + $ext_element = false; + $button_only = false; + $inputOption = ''; - if (is_object($extObject)) - { - $ext_element = $extObject->element; - } + if (is_object($object)) + { + $element = $object->element; + $table_element = $object->table_element; + $fk_element = $object->id; + } - if (preg_match('/^(string|email|numeric)/',$inputType)) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; - if (! empty($tmp[1])) $inputOption=$tmp[1]; - if (! empty($tmp[2])) $savemethod=$tmp[2]; + if (is_object($extObject)) + { + $ext_element = $extObject->element; + } + + if (preg_match('/^(string|email|numeric)/',$inputType)) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; + if (! empty($tmp[1])) $inputOption=$tmp[1]; + if (! empty($tmp[2])) $savemethod=$tmp[2]; $out.= ''."\n"; - } - else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType))) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; - if (! empty($tmp[1])) $inputOption=$tmp[1]; - if (! empty($tmp[2])) $savemethod=$tmp[2]; + } + else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType))) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; + if (! empty($tmp[1])) $inputOption=$tmp[1]; + if (! empty($tmp[2])) $savemethod=$tmp[2]; - $out.= ''."\n"; // Use for timestamp format - } - else if (preg_match('/^(select|autocomplete)/',$inputType)) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; $loadmethod=$tmp[1]; - if (! empty($tmp[2])) $savemethod=$tmp[2]; - if (! empty($tmp[3])) $button_only=true; - } - else if (preg_match('/^textarea/',$inputType)) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; - $rows=(empty($tmp[1])?'8':$tmp[1]); - $cols=(empty($tmp[2])?'80':$tmp[2]); - } - else if (preg_match('/^ckeditor/',$inputType)) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; $toolbar=$tmp[1]; - if (! empty($tmp[2])) $width=$tmp[2]; - if (! empty($tmp[3])) $heigth=$tmp[3]; - if (! empty($tmp[4])) $savemethod=$tmp[4]; + $out.= ''."\n"; // Use for timestamp format + } + else if (preg_match('/^(select|autocomplete)/',$inputType)) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; $loadmethod=$tmp[1]; + if (! empty($tmp[2])) $savemethod=$tmp[2]; + if (! empty($tmp[3])) $button_only=true; + } + else if (preg_match('/^textarea/',$inputType)) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; + $rows=(empty($tmp[1])?'8':$tmp[1]); + $cols=(empty($tmp[2])?'80':$tmp[2]); + } + else if (preg_match('/^ckeditor/',$inputType)) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; $toolbar=$tmp[1]; + if (! empty($tmp[2])) $width=$tmp[2]; + if (! empty($tmp[3])) $heigth=$tmp[3]; + if (! empty($tmp[4])) $savemethod=$tmp[4]; - if (! empty($conf->fckeditor->enabled)) - { - $out.= ''."\n"; - } - else - { - $inputType = 'textarea'; - } - } + if (! empty($conf->fckeditor->enabled)) + { + $out.= ''."\n"; + } + else + { + $inputType = 'textarea'; + } + } - $out.= ''."\n"; - $out.= ''."\n"; - $out.= ''."\n"; - $out.= ''."\n"; - if (! empty($savemethod)) $out.= ''."\n"; - if (! empty($ext_element)) $out.= ''."\n"; - if (! empty($custommsg)) - { - if (is_array($custommsg)) - { - if (!empty($custommsg['success'])) - $out.= ''."\n"; - if (!empty($custommsg['error'])) - $out.= ''."\n"; - } - else - $out.= ''."\n"; - } - if ($inputType == 'textarea') { - $out.= ''."\n"; - $out.= ''."\n"; - } - $out.= ''.$value.''."\n"; - $out.= ''.(! empty($editvalue) ? $editvalue : $value).''."\n"; - } - else - { - $out = $value; - } + $out.= ''."\n"; + $out.= ''."\n"; + $out.= ''."\n"; + $out.= ''."\n"; + if (! empty($savemethod)) $out.= ''."\n"; + if (! empty($ext_element)) $out.= ''."\n"; + if (! empty($custommsg)) + { + if (is_array($custommsg)) + { + if (!empty($custommsg['success'])) + $out.= ''."\n"; + if (!empty($custommsg['error'])) + $out.= ''."\n"; + } + else + $out.= ''."\n"; + } + if ($inputType == 'textarea') { + $out.= ''."\n"; + $out.= ''."\n"; + } + $out.= ''.$value.''."\n"; + $out.= ''.(! empty($editvalue) ? $editvalue : $value).''."\n"; + } + else + { + $out = $value; + } - return $out; - } + return $out; + } - /** - * Show a text and picto with tooltip on text or picto. - * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip - * - * @param string $text Text to show - * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded. - * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2 - * @param int $direction -1=image is before, 0=no image, 1=image is after - * @param string $img Html code for image (use img_xxx() function to get it) - * @param string $extracss Add a CSS style to td tags - * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span - * @param string $incbefore Include code before the text - * @param int $noencodehtmltext Do not encode into html entity the htmltext - * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key) - * @return string Code html du tooltip (texte+picto) - * @see Use function textwithpicto if you can. - * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip - */ - function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='') - { - global $conf; + /** + * Show a text and picto with tooltip on text or picto. + * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip + * + * @param string $text Text to show + * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded. + * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2 + * @param int $direction -1=image is before, 0=no image, 1=image is after + * @param string $img Html code for image (use img_xxx() function to get it) + * @param string $extracss Add a CSS style to td tags + * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span + * @param string $incbefore Include code before the text + * @param int $noencodehtmltext Do not encode into html entity the htmltext + * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key) + * @return string Code html du tooltip (texte+picto) + * @see Use function textwithpicto if you can. + * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip + */ + function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='') + { + global $conf; - if ($incbefore) $text = $incbefore.$text; - if (! $htmltext) return $text; + if ($incbefore) $text = $incbefore.$text; + if (! $htmltext) return $text; - $tag='td'; - if ($notabs == 2) $tag='div'; - if ($notabs == 3) $tag='span'; - // Sanitize tooltip - $htmltext=str_replace("\\","\\\\",$htmltext); - $htmltext=str_replace("\r","",$htmltext); - $htmltext=str_replace("\n","",$htmltext); + $tag='td'; + if ($notabs == 2) $tag='div'; + if ($notabs == 3) $tag='span'; + // Sanitize tooltip + $htmltext=str_replace("\\","\\\\",$htmltext); + $htmltext=str_replace("\r","",$htmltext); + $htmltext=str_replace("\n","",$htmltext); - $extrastyle=''; - if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; } - if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; } + $extrastyle=''; + if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; } + if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; } - $classfortooltip='classfortooltip'; + $classfortooltip='classfortooltip'; - $s='';$textfordialog=''; + $s='';$textfordialog=''; - $htmltext=str_replace('"',""",$htmltext); - if ($tooltiptrigger != '') - { - $classfortooltip='classfortooltiponclick'; - $textfordialog.=''; - } - if ($tooltipon == 2 || $tooltipon == 3) - { - $paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"'; - if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip - else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"'; - } - else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag - if ($tooltipon == 1 || $tooltipon == 3) - { - $paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" '; - if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip - else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"'; - } - else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag - if (empty($notabs)) $s.=''; - elseif ($notabs == 2) $s.='
    '; - // Define value if value is before - if ($direction < 0) { - $s.='<'.$tag.$paramfortooltipimg; - if ($tag == 'td') { - $s .= ' valign="top" width="14"'; - } - $s.= '>'.$textfordialog.$img.''; - } - // Use another method to help avoid having a space in value in order to use this value with jquery - // Define label - if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.''; - // Define value if value is after - if ($direction > 0) { - $s.='<'.$tag.$paramfortooltipimg; - if ($tag == 'td') $s .= ' valign="middle" width="14"'; - $s.= '>'.$textfordialog.$img.''; - } - if (empty($notabs)) $s.='
    '; + if ($tooltiptrigger == '') + { + $htmltext=str_replace('"',""",$htmltext); + } + else + { + $classfortooltip='classfortooltiponclick'; + $textfordialog.=''; + } + if ($tooltipon == 2 || $tooltipon == 3) + { + $paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"'; + if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip + else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"'; + } + else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag + if ($tooltipon == 1 || $tooltipon == 3) + { + $paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" '; + if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip + else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"'; + } + else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag + if (empty($notabs)) $s.=''; + elseif ($notabs == 2) $s.='
    '; + // Define value if value is before + if ($direction < 0) { + $s.='<'.$tag.$paramfortooltipimg; + if ($tag == 'td') { + $s .= ' valign="top" width="14"'; + } + $s.= '>'.$textfordialog.$img.''; + } + // Use another method to help avoid having a space in value in order to use this value with jquery + // Define label + if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.''; + // Define value if value is after + if ($direction > 0) { + $s.='<'.$tag.$paramfortooltipimg; + if ($tag == 'td') $s .= ' valign="middle" width="14"'; + $s.= '>'.$textfordialog.$img.''; + } + if (empty($notabs)) $s.='
    '; elseif ($notabs == 2) $s.='
    '; - return $s; - } + return $s; + } - /** - * Show a text with a picto and a tooltip on picto - * - * @param string $text Text to show - * @param string $htmltext Content of tooltip - * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon - * @param string $type Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath - * @param string $extracss Add a CSS style to td, div or span tag - * @param int $noencodehtmltext Do not encode into html entity the htmltext - * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span - * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key) - * @return string HTML code of text, picto, tooltip - */ - function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='') - { - global $conf, $langs; + /** + * Show a text with a picto and a tooltip on picto + * + * @param string $text Text to show + * @param string $htmltext Content of tooltip + * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon + * @param string $type Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath + * @param string $extracss Add a CSS style to td, div or span tag + * @param int $noencodehtmltext Do not encode into html entity the htmltext + * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span + * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key) + * @return string HTML code of text, picto, tooltip + */ + function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='') + { + global $conf, $langs; - $alt = ''; - if ($tooltiptrigger) $alt=$langs->trans("ClickToShowHelp"); + $alt = ''; + if ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv("ClickToShowHelp"); - //For backwards compatibility - if ($type == '0') $type = 'info'; - elseif ($type == '1') $type = 'help'; + //For backwards compatibility + if ($type == '0') $type = 'info'; + elseif ($type == '1') $type = 'help'; - // If info or help with no javascript, show only text - if (empty($conf->use_javascript_ajax)) - { - if ($type == 'info' || $type == 'help') return $text; - else - { - $alt = $htmltext; - $htmltext = ''; - } - } + // If info or help with no javascript, show only text + if (empty($conf->use_javascript_ajax)) + { + if ($type == 'info' || $type == 'help') return $text; + else + { + $alt = $htmltext; + $htmltext = ''; + } + } - // If info or help with smartphone, show only text (tooltip can't works) - if (! empty($conf->dol_no_mouse_hover)) - { - if ($type == 'info' || $type == 'help') return $text; - } + // If info or help with smartphone, show only text (tooltip can't works) + if (! empty($conf->dol_no_mouse_hover)) + { + if ($type == 'info' || $type == 'help') return $text; + } - if ($type == 'info') $img = img_help(0, $alt); - elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt); - elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar'); - elseif ($type == 'admin') $img = img_picto($alt, 'star'); - elseif ($type == 'warning') $img = img_warning($alt); + if ($type == 'info') $img = img_help(0, $alt); + elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt); + elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar'); + elseif ($type == 'admin') $img = img_picto($alt, 'star'); + elseif ($type == 'warning') $img = img_warning($alt); else $img = img_picto($alt, $type); - return $this->textwithtooltip($text, $htmltext, ($tooltiptrigger?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger); - } + return $this->textwithtooltip($text, $htmltext, ($tooltiptrigger?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger); + } - /** - * Generate select HTML to choose massaction - * - * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default. - * @param int $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action. - * @param int $alwaysvisible 1=select button always visible - * @return string Select list - */ - function selectMassAction($selected, $arrayofaction, $alwaysvisible=0) - { - global $conf,$langs,$hookmanager; + /** + * Generate select HTML to choose massaction + * + * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default. + * @param int $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action. + * @param int $alwaysvisible 1=select button always visible + * @return string Select list + */ + function selectMassAction($selected, $arrayofaction, $alwaysvisible=0) + { + global $conf,$langs,$hookmanager; - if (count($arrayofaction) == 0) return; + if (count($arrayofaction) == 0) return; - $disabled=0; - $ret='
    '; - $ret.=''; - // Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks. - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { - $ret.=''; - foreach($arrayofaction as $code => $label) - { - $ret.=''; - } - } - $ret.=$hookmanager->resPrint; + // Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks. + $parameters=array(); + $reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) + { + $ret.=''; + foreach($arrayofaction as $code => $label) + { + $ret.=''; + } + } + $ret.=$hookmanager->resPrint; - $ret.=''; - // Warning: if you set submit button to disabled, post using 'Enter' will no more work. - $ret.=''; - $ret.='
    '; + $ret.=''; + // Warning: if you set submit button to disabled, post using 'Enter' will no more work. + $ret.=''; + $ret.='
    '; - if (! empty($conf->use_javascript_ajax)) - { - $ret.=' + if (! empty($conf->use_javascript_ajax)) + { + $ret.=' '; - } + } - return $ret; - } + return $ret; + } - /** - * Return combo list of activated countries, into language of user - * - * @param string $selected Id or Code or Label of preselected country - * @param string $htmlname Name of html select object - * @param string $htmloption Options html on select object - * @param integer $maxlength Max length for labels (0=no limit) - * @param string $morecss More css class - * @return string HTML string with select - */ - function select_country($selected='',$htmlname='country_id',$htmloption='',$maxlength=0,$morecss='minwidth300') - { - global $conf,$langs; + /** + * Return combo list of activated countries, into language of user + * + * @param string $selected Id or Code or Label of preselected country + * @param string $htmlname Name of html select object + * @param string $htmloption Options html on select object + * @param integer $maxlength Max length for labels (0=no limit) + * @param string $morecss More css class + * @param string $usecodeaskey 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key + * @return string HTML string with select + */ + function select_country($selected='',$htmlname='country_id',$htmloption='',$maxlength=0,$morecss='minwidth300',$usecodeaskey='') + { + global $conf,$langs; - $langs->load("dict"); + $langs->load("dict"); - $out=''; - $countryArray=array(); + $out=''; + $countryArray=array(); $favorite=array(); - $label=array(); + $label=array(); $atleastonefavorite=0; - $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_country"; - $sql.= " WHERE active > 0"; - //$sql.= " ORDER BY code ASC"; + $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_country"; + $sql.= " WHERE active > 0"; + //$sql.= " ORDER BY code ASC"; - dol_syslog(get_class($this)."::select_country", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $out.= ''; + $num = $this->db->num_rows($resql); + $i = 0; + if ($num) + { + $foundselected=false; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $countryArray[$i]['rowid'] = $obj->rowid; - $countryArray[$i]['code_iso'] = $obj->code_iso; - $countryArray[$i]['code_iso3'] = $obj->code_iso3; - $countryArray[$i]['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:'')); - $countryArray[$i]['favorite'] = $obj->favorite; - $favorite[$i] = $obj->favorite; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $countryArray[$i]['rowid'] = $obj->rowid; + $countryArray[$i]['code_iso'] = $obj->code_iso; + $countryArray[$i]['code_iso3'] = $obj->code_iso3; + $countryArray[$i]['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:'')); + $countryArray[$i]['favorite'] = $obj->favorite; + $favorite[$i] = $obj->favorite; $label[$i] = dol_string_unaccent($countryArray[$i]['label']); - $i++; - } + $i++; + } - array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray); + array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray); - foreach ($countryArray as $row) - { - if ($row['favorite'] && $row['code_iso']) $atleastonefavorite++; + foreach ($countryArray as $row) + { + if ($row['favorite'] && $row['code_iso']) $atleastonefavorite++; if (empty($row['favorite']) && $atleastonefavorite) { $atleastonefavorite=0; $out.= ''; } - if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) ) - { - $foundselected=true; - $out.= ''; - } - } - $out.= ''; - } - else + $foundselected=true; + $out.= ''; + } + } + $out.= ''; + } + else { - dol_print_error($this->db); - } + dol_print_error($this->db); + } - // Make select dynamic - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out .= ajax_combobox('select'.$htmlname); + // Make select dynamic + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $out .= ajax_combobox('select'.$htmlname); - return $out; - } + return $out; + } /** - * Return select list of incoterms - * - * @param string $selected Id or Code of preselected incoterm - * @param string $location_incoterms Value of input location - * @param string $page Defined the form action - * @param string $htmlname Name of html select object - * @param string $htmloption Options html on select object - * @param int $forcecombo Force to use standard combo box (no ajax use) - * @param array $events Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @return string HTML string with select and input - */ - function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array()) - { - global $conf,$langs; + * Return select list of incoterms + * + * @param string $selected Id or Code of preselected incoterm + * @param string $location_incoterms Value of input location + * @param string $page Defined the form action + * @param string $htmlname Name of html select object + * @param string $htmloption Options html on select object + * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) + * @param array $events Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @return string HTML string with select and input + */ + function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array()) + { + global $conf,$langs; - $langs->load("dict"); + $langs->load("dict"); - $out=''; - $incotermArray=array(); + $out=''; + $incotermArray=array(); - $sql = "SELECT rowid, code"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms"; - $sql.= " WHERE active > 0"; - $sql.= " ORDER BY code ASC"; + $sql = "SELECT rowid, code"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms"; + $sql.= " WHERE active > 0"; + $sql.= " ORDER BY code ASC"; - dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($conf->use_javascript_ajax && ! $forcecombo) + dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($conf->use_javascript_ajax && ! $forcecombo) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; $out .= ajax_combobox($htmlname, $events); @@ -748,482 +758,483 @@ class Form if (!empty($page)) { $out .= '
    '; - $out .= ''; - $out .= ''; + $out .= ''; + $out .= ''; } - $out.= ''; $out.= ''; - $num = $this->db->num_rows($resql); - $i = 0; - if ($num) - { - $foundselected=false; + $num = $this->db->num_rows($resql); + $i = 0; + if ($num) + { + $foundselected=false; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $incotermArray[$i]['rowid'] = $obj->rowid; - $incotermArray[$i]['code'] = $obj->code; - $i++; - } + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $incotermArray[$i]['rowid'] = $obj->rowid; + $incotermArray[$i]['code'] = $obj->code; + $i++; + } - foreach ($incotermArray as $row) - { - if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) - { - $out.= ''; - } - } - $out.= ''; + } + } + $out.= ''; $out .= ''; if (!empty($page)) { - $out .= '
    '; + $out .= ''; } - } - else + } + else { - dol_print_error($this->db); - } + dol_print_error($this->db); + } - return $out; - } + return $out; + } - /** - * Return list of types of lines (product or service) - * Example: 0=product, 1=service, 9=other (for external module) - * - * @param string $selected Preselected type - * @param string $htmlname Name of field in html form - * @param int $showempty Add an empty field - * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select) - * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, -1=Force none (and set hidden field to 'service') - * @return void - */ - function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0) - { - global $db,$langs,$user,$conf; + /** + * Return list of types of lines (product or service) + * Example: 0=product, 1=service, 9=other (for external module) + * + * @param string $selected Preselected type + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select) + * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, -1=Force none (and set hidden field to 'service') + * @return void + */ + function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0) + { + global $db,$langs,$user,$conf; - // If product & services are enabled or both disabled. - if ($forceall > 0 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled)) - || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) ) - { - if (empty($hidetext)) print $langs->trans("Type").': '; - print ''; + if ($showempty) + { + print ''; + } - print ''; + } - foreach($this->cache_types_fees as $key => $value) - { - print ''; - } + foreach($this->cache_types_fees as $key => $value) + { + print ''; + } - print ''; - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } + print ''; + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } - /** - * Return HTML code to select a company. - * - * @param int $selected Preselected products - * @param string $htmlname Name of HTML select field (must be unique in page) - * @param int $filter Filter on thirdparty - * @param int $limit Limit on number of returned lines - * @param array $ajaxoptions Options for ajax_autocompleter - * @param int $forcecombo Force to use combo box - * @return string Return select box for thirdparty. + /** + * Return HTML code to select a company. + * + * @param int $selected Preselected products + * @param string $htmlname Name of HTML select field (must be unique in page) + * @param int $filter Filter on thirdparty + * @param int $limit Limit on number of returned lines + * @param array $ajaxoptions Options for ajax_autocompleter + * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) + * @return string Return select box for thirdparty. * @deprecated 3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0) - */ - function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0) - { - return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0,$limit); - } + */ + function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0) + { + return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit); + } - /** - * Output html form to select a third party - * - * @param string $selected Preselected type - * @param string $htmlname Name of field in form - * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)') - * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty') - * @param int $showtype Show third party type in combolist (customer, prospect or supplier) - * @param int $forcecombo Force to use combo box - * @param array $events Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @param int $limit Maximum number of elements - * @param string $morecss Add more css styles to the SELECT component - * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container + /** + * Output html form to select a third party + * + * @param string $selected Preselected type + * @param string $htmlname Name of field in form + * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)') + * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty') + * @param int $showtype Show third party type in combolist (customer, prospect or supplier) + * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) + * @param array $events Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @param int $limit Maximum number of elements + * @param string $morecss Add more css styles to the SELECT component + * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container * @param string $selected_input_value Value of preselected input text (for use with ajax) - * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) - * @param array $ajaxoptions Options for ajax_autocompleter - * @return string HTML string with select box for thirdparty. - */ - function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array()) - { - global $conf,$user,$langs; + * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) + * @param array $ajaxoptions Options for ajax_autocompleter + * @return string HTML string with select box for thirdparty. + */ + function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array()) + { + global $conf,$user,$langs; - $out=''; + $out=''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo) - { - // No immediate load of all database - $placeholder=''; - if ($selected && empty($selected_input_value)) - { - require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $societetmp = new Societe($this->db); - $societetmp->fetch($selected); - $selected_input_value=$societetmp->name; - unset($societetmp); - } - // mode 1 - $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:''); - $out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); - $out.=''; - if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : '; - else if ($hidelabel > 1) { - if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; - else $placeholder=' title="'.$langs->trans("RefOrLabel").'"'; - if ($hidelabel == 2) { - $out.= img_picto($langs->trans("Search"), 'search'); - } - } - $out.= 'global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; - if ($hidelabel == 3) { - $out.= img_picto($langs->trans("Search"), 'search'); - } - } - else - { - // Immediate load of all database - $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam); - } + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo) + { + // No immediate load of all database + $placeholder=''; + if ($selected && empty($selected_input_value)) + { + require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + $societetmp = new Societe($this->db); + $societetmp->fetch($selected); + $selected_input_value=$societetmp->name; + unset($societetmp); + } + // mode 1 + $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:''); + $out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); + $out.=''; + if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : '; + else if ($hidelabel > 1) { + $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; + if ($hidelabel == 2) { + $out.= img_picto($langs->trans("Search"), 'search'); + } + } + $out.= 'global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; + if ($hidelabel == 3) { + $out.= img_picto($langs->trans("Search"), 'search'); + } + } + else + { + // Immediate load of all database + $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam); + } - return $out; - } + return $out; + } - /** - * Output html form to select a third party. - * Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company. - * - * @param string $selected Preselected type - * @param string $htmlname Name of field in form - * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)') - * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty') - * @param int $showtype Show third party type in combolist (customer, prospect or supplier) - * @param int $forcecombo Force to use combo box - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @param string $filterkey Filter on key value - * @param int $outputmode 0=HTML select string, 1=Array - * @param int $limit Limit number of answers - * @param string $morecss Add more css styles to the SELECT component - * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container - * @return string HTML string with - */ - function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='') - { - global $conf,$user,$langs; + /** + * Output html form to select a third party. + * Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company. + * + * @param string $selected Preselected type + * @param string $htmlname Name of field in form + * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)') + * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty') + * @param int $showtype Show third party type in combolist (customer, prospect or supplier) + * @param int $forcecombo Force to use standard HTML select component without beautification + * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @param string $filterkey Filter on key value + * @param int $outputmode 0=HTML select string, 1=Array + * @param int $limit Limit number of answers + * @param string $morecss Add more css styles to the SELECT component + * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container + * @return string HTML string with + */ + function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='') + { + global $conf,$user,$langs; - $out=''; - $num=0; - $outarray=array(); + $out=''; + $num=0; + $outarray=array(); - // On recherche les societes - $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur"; - $sql.= " FROM ".MAIN_DB_PREFIX ."societe as s"; - if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE s.entity IN (".getEntity('societe').")"; - if (! empty($user->societe_id)) $sql.= " AND s.rowid = ".$user->societe_id; - if ($filter) $sql.= " AND (".$filter.")"; - if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0"; - // Add criteria - if ($filterkey && $filterkey != '') - { + // On recherche les societes + $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur"; + $sql.= " FROM ".MAIN_DB_PREFIX ."societe as s"; + if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql.= " WHERE s.entity IN (".getEntity('societe').")"; + if (! empty($user->societe_id)) $sql.= " AND s.rowid = ".$user->societe_id; + if ($filter) $sql.= " AND (".$filter.")"; + if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0"; + // Add criteria + if ($filterkey && $filterkey != '') + { $sql.=" AND ("; - $prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on - // For natural search - $scrit = explode(' ', $filterkey); - $i=0; - if (count($scrit) > 1) $sql.="("; - foreach ($scrit as $crit) { - if ($i > 0) $sql.=" AND "; - $sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')"; - $i++; - } - if (count($scrit) > 1) $sql.=")"; - if (! empty($conf->barcode->enabled)) - { - $sql .= " OR s.barcode LIKE '".$this->db->escape($filterkey)."%'"; - } - $sql.=")"; - } - $sql.=$this->db->order("nom","ASC"); - if ($limit > 0) $sql.=$this->db->plimit($limit); + $prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on + // For natural search + $scrit = explode(' ', $filterkey); + $i=0; + if (count($scrit) > 1) $sql.="("; + foreach ($scrit as $crit) { + if ($i > 0) $sql.=" AND "; + $sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')"; + $i++; + } + if (count($scrit) > 1) $sql.=")"; + if (! empty($conf->barcode->enabled)) + { + $sql .= " OR s.barcode LIKE '".$this->db->escape($filterkey)."%'"; + } + $sql.=")"; + } + $sql.=$this->db->order("nom","ASC"); + $sql.=$this->db->plimit($limit, 0); // Build output string - dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($conf->use_javascript_ajax && ! $forcecombo) - { + dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($conf->use_javascript_ajax && ! $forcecombo) + { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT); - $out.= $comboenhancement; - } + $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT); + $out.= $comboenhancement; + } - // Construct $out and $outarray - $out.= ''."\n"; - $textifempty=''; - // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. - //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; - if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) - { - if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); - else $textifempty.=$langs->trans("All"); - } - if ($showempty) $out.= ''."\n"; + $textifempty=''; + // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. + //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; + if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) + { + if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); + else $textifempty.=$langs->trans("All"); + } + if ($showempty) $out.= ''."\n"; $num = $this->db->num_rows($resql); - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $label=''; - if ($conf->global->SOCIETE_ADD_REF_IN_LIST) { - if (($obj->client) && (!empty($obj->code_client))) { - $label = $obj->code_client. ' - '; - } - if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) { - $label .= $obj->code_fournisseur. ' - '; - } - $label.=' '.$obj->name; - } - else - { - $label=$obj->name; - } + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $label=''; + if ($conf->global->SOCIETE_ADD_REF_IN_LIST) { + if (($obj->client) && (!empty($obj->code_client))) { + $label = $obj->code_client. ' - '; + } + if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) { + $label .= $obj->code_fournisseur. ' - '; + } + $label.=' '.$obj->name; + } + else + { + $label=$obj->name; + } if(!empty($obj->name_alias)) { $label.=' ('.$obj->name_alias.')'; } - if ($showtype) - { - if ($obj->client || $obj->fournisseur) $label.=' ('; - if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer"); - if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect"); - if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier"); - if ($obj->client || $obj->fournisseur) $label.=')'; - } - if ($selected > 0 && $selected == $obj->rowid) - { - $out.= ''; - } - else + if ($showtype) { - $out.= ''; - } + if ($obj->client || $obj->fournisseur) $label.=' ('; + if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer"); + if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect"); + if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier"); + if ($obj->client || $obj->fournisseur) $label.=')'; + } - array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label)); + if (empty($outputmode)) + { + if ($selected > 0 && $selected == $obj->rowid) + { + $out.= ''; + } + else + { + $out.= ''; + } + } + else + { + array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label)); + } - $i++; - if (($i % 10) == 0) $out.="\n"; - } - } - $out.= ''."\n"; - } - else - { - dol_print_error($this->db); - } + $i++; + if (($i % 10) == 0) $out.="\n"; + } + } + $out.= ''."\n"; + } + else + { + dol_print_error($this->db); + } - $this->result=array('nbofthirdparties'=>$num); + $this->result=array('nbofthirdparties'=>$num); - if ($outputmode) return $outarray; - return $out; - } + if ($outputmode) return $outarray; + return $out; + } - /** - * Return HTML combo list of absolute discounts - * - * @param string $selected Id remise fixe pre-selectionnee - * @param string $htmlname Nom champ formulaire - * @param string $filter Criteres optionnels de filtre - * @param int $socid Id of thirdparty - * @param int $maxvalue Max value for lines that can be selected - * @return int Return number of qualifed lines in list - */ - function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0) - { - global $langs,$conf; + /** + * Return HTML combo list of absolute discounts + * + * @param string $selected Id remise fixe pre-selectionnee + * @param string $htmlname Nom champ formulaire + * @param string $filter Criteres optionnels de filtre + * @param int $socid Id of thirdparty + * @param int $maxvalue Max value for lines that can be selected + * @return int Return number of qualifed lines in list + */ + function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0) + { + global $langs,$conf; - // On recherche les remises - $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql.= " re.description, re.fk_facture_source"; - $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re"; - $sql.= " WHERE re.fk_soc = ".(int) $socid; - $sql.= " AND re.entity = " . $conf->entity; - if ($filter) $sql.= " AND ".$filter; - $sql.= " ORDER BY re.description ASC"; + // On recherche les remises + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; + $sql.= " re.description, re.fk_facture_source"; + $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re"; + $sql.= " WHERE re.fk_soc = ".(int) $socid; + $sql.= " AND re.entity = " . $conf->entity; + if ($filter) $sql.= " AND ".$filter; + $sql.= " ORDER BY re.description ASC"; - dol_syslog(get_class($this)."::select_remises", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - print ''; + $num = $this->db->num_rows($resql); - $qualifiedlines=$num; + $qualifiedlines=$num; - $i = 0; - if ($num) - { - print ''; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $desc=dol_trunc($obj->description,40); - if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc); - if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc); - if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc); + $i = 0; + if ($num) + { + print ''; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $desc=dol_trunc($obj->description,40); + if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc); + if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc); + if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc); - $selectstring=''; - if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected'; + $selectstring=''; + if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected'; - $disabled=''; - if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) - { - $qualifiedlines--; - $disabled=' disabled'; - } + $disabled=''; + if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) + { + $qualifiedlines--; + $disabled=' disabled'; + } if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) { @@ -1231,222 +1242,224 @@ class Form if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref; } - print ''; - $i++; - } - } - print ''; - return $qualifiedlines; - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Return list of all contacts (for a third party or all) - * - * @param int $socid Id ot third party or 0 for all - * @param string $selected Id contact pre-selectionne - * @param string $htmlname Name of HTML field ('none' for a not editable field) - * @param int $showempty 0=no empty value, 1=add an empty value - * @param string $exclude List of contacts id to exclude - * @param string $limitto Disable answers that are not id in this array list - * @param integer $showfunction Add function into label - * @param string $moreclass Add more class to class style - * @param integer $showsoc Add company into label - * @param int $forcecombo Force to use combo box - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @param bool $options_only Return options only (for ajax treatment) - * @return int <0 if KO, Nb of contact in list if OK - */ - function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false) - { - print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events); - return $this->num; - } - - /** - * Return list of all contacts (for a third party or all) - * - * @param int $socid Id ot third party or 0 for all - * @param string $selected Id contact pre-selectionne - * @param string $htmlname Name of HTML field ('none' for a not editable field) - * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit) - * @param string $exclude List of contacts id to exclude - * @param string $limitto Disable answers that are not id in this array list - * @param integer $showfunction Add function into label - * @param string $moreclass Add more class to class style - * @param bool $options_only Return options only (for ajax treatment) - * @param integer $showsoc Add company into label - * @param int $forcecombo Force to use combo box - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @return int <0 if KO, Nb of contact in list if OK - */ - function selectcontacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array()) - { - global $conf,$langs; - - $langs->load('companies'); - - $out=''; - - // On recherche les societes - $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste"; - if ($showsoc > 0) $sql.= " , s.nom as company"; - $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp"; - if ($showsoc > 0) $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc"; - $sql.= " WHERE sp.entity IN (".getEntity('societe').")"; - if ($socid > 0) $sql.= " AND sp.fk_soc=".$socid; - if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0"; - $sql.= " ORDER BY sp.lastname ASC"; - - dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - - if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only) - { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $comboenhancement = ajax_combobox($htmlname, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT); - $out.= $comboenhancement; - } - - if ($htmlname != 'none' || $options_only) $out.= ''; + return $qualifiedlines; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Return list of all contacts (for a third party or all) + * + * @param int $socid Id ot third party or 0 for all + * @param string $selected Id contact pre-selectionne + * @param string $htmlname Name of HTML field ('none' for a not editable field) + * @param int $showempty 0=no empty value, 1=add an empty value + * @param string $exclude List of contacts id to exclude + * @param string $limitto Disable answers that are not id in this array list + * @param integer $showfunction Add function into label + * @param string $moreclass Add more class to class style + * @param integer $showsoc Add company into label + * @param int $forcecombo Force to use combo box + * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @param bool $options_only Return options only (for ajax treatment) + * @return int <0 if KO, Nb of contact in list if OK + * @deprected You can use selectcontacts directly (warning order of param was changed) + */ + function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false) + { + print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events); + return $this->num; + } + + /** + * Return HTML code of the SELECT of list of all contacts (for a third party or all). + * This also set the number of contacts found into $this->num + * + * @param int $socid Id ot third party or 0 for all + * @param string $selected Id contact pre-selectionne + * @param string $htmlname Name of HTML field ('none' for a not editable field) + * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit) + * @param string $exclude List of contacts id to exclude + * @param string $limitto Disable answers that are not id in this array list + * @param integer $showfunction Add function into label + * @param string $moreclass Add more class to class style + * @param bool $options_only Return options only (for ajax treatment) + * @param integer $showsoc Add company into label + * @param int $forcecombo Force to use combo box + * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @return int <0 if KO, Nb of contact in list if OK + */ + function selectcontacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array()) + { + global $conf,$langs; + + $langs->load('companies'); + + $out=''; + + // On recherche les societes + $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste"; + if ($showsoc > 0) $sql.= " , s.nom as company"; + $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp"; + if ($showsoc > 0) $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc"; + $sql.= " WHERE sp.entity IN (".getEntity('societe').")"; + if ($socid > 0) $sql.= " AND sp.fk_soc=".$socid; + if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0"; + $sql.= " ORDER BY sp.lastname ASC"; + + dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $num=$this->db->num_rows($resql); + + if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only) { - $out.= ''; - } - if ($htmlname != 'none' || $options_only) - { - $out.= ''; - } + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $comboenhancement = ajax_combobox($htmlname, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT); + $out.= $comboenhancement; + } - $this->num = $num; - return $out; - } - else - { - dol_print_error($this->db); - return -1; - } - } + if ($htmlname != 'none' || $options_only) $out.= ''; + } - // If no preselected user defined, we take current user - if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id; + $this->num = $num; + return $out; + } + else + { + dol_print_error($this->db); + return -1; + } + } - $excludeUsers=null; - $includeUsers=null; + /** + * Return select list of users + * + * @param string $selected Id user preselected + * @param string $htmlname Field name in form + * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue + * @param array $exclude Array list of users id to exclude + * @param int $disabled If select list must be disabled + * @param array $include Array list of users id to include + * @param int $enableonly Array list of users id to be enabled. All other must be disabled + * @param int $force_entity 0 or Id of environment to force + * @return void + * @deprecated Use select_dolusers instead + * @see select_dolusers() + */ + function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity=0) + { + print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity); + } - // Permettre l'exclusion d'utilisateurs - if (is_array($exclude)) $excludeUsers = implode(",",$exclude); - // Permettre l'inclusion d'utilisateurs - if (is_array($include)) $includeUsers = implode(",",$include); + /** + * Return select list of users + * + * @param string $selected User id or user object of user preselected. If -1, we use id of current user. + * @param string $htmlname Field name in form + * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list + * @param array $exclude Array list of users id to exclude + * @param int $disabled If select list must be disabled + * @param array|string $include Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me + * @param array $enableonly Array list of users id to be enabled. If defined, it means that other must be disabled + * @param int $force_entity 0 or Id of environment to force + * @param int $maxlength Maximum length of string into list (0=no limit) + * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status + * @param string $morefilter Add more filters into sql request + * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list + * @param string $enableonlytext If option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty. + * @param string $morecss More css + * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on). + * @return string HTML select string + * @see select_dolgroups + */ + function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0) + { + global $conf,$user,$langs; + + // If no preselected user defined, we take current user + if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id; + + $excludeUsers=null; + $includeUsers=null; + + // Permettre l'exclusion d'utilisateurs + if (is_array($exclude)) $excludeUsers = implode(",",$exclude); + // Permettre l'inclusion d'utilisateurs + if (is_array($include)) $includeUsers = implode(",",$include); else if ($include == 'hierarchy') { // Build list includeUsers to have only hierarchy @@ -1454,194 +1467,194 @@ class Form } else if ($include == 'hierarchyme') { - // Build list includeUsers to have only hierarchy and current user - $includeUsers = implode(",",$user->getAllChildIds(1)); + // Build list includeUsers to have only hierarchy and current user + $includeUsers = implode(",",$user->getAllChildIds(1)); } - $out=''; + $out=''; - // On recherche les utilisateurs - $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; - if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity) - { - $sql.= ", e.label"; - } - $sql.= " FROM ".MAIN_DB_PREFIX ."user as u"; - if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity"; - if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")"; - else $sql.= " WHERE u.entity IS NOT NULL"; - } - else - { - if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug"; - $sql.= " ON ug.fk_user = u.rowid"; - $sql.= " WHERE ug.entity = ".$conf->entity; - } - else - { - $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; - } - } - if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id; - if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")"; - if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")"; - if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0"; - if (! empty($morefilter)) $sql.=" ".$morefilter; + // On recherche les utilisateurs + $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; + if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity) + { + $sql.= ", e.label"; + } + $sql.= " FROM ".MAIN_DB_PREFIX ."user as u"; + if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity"; + if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")"; + else $sql.= " WHERE u.entity IS NOT NULL"; + } + else + { + if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug"; + $sql.= " ON ug.fk_user = u.rowid"; + $sql.= " WHERE ug.entity = ".$conf->entity; + } + else + { + $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; + } + } + if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id; + if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")"; + if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")"; + if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0"; + if (! empty($morefilter)) $sql.=" ".$morefilter; - if(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){ - $sql.= " ORDER BY u.firstname ASC"; - }else{ - $sql.= " ORDER BY u.lastname ASC"; - } + if(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){ + $sql.= " ORDER BY u.firstname ASC"; + }else{ + $sql.= " ORDER BY u.lastname ASC"; + } - dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - if ($num) - { - // Enhance with select2 - if ($conf->use_javascript_ajax) - { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $comboenhancement = ajax_combobox($htmlname); - $out.=$comboenhancement; - } + dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + if ($num) + { + // Enhance with select2 + if ($conf->use_javascript_ajax) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $comboenhancement = ajax_combobox($htmlname); + $out.=$comboenhancement; + } - // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined - $out.= ''; + if ($show_empty) $out.= ''."\n"; if ($show_every) $out.= ''."\n"; - $userstatic=new User($this->db); + $userstatic=new User($this->db); - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - $userstatic->id=$obj->rowid; - $userstatic->lastname=$obj->lastname; - $userstatic->firstname=$obj->firstname; + $userstatic->id=$obj->rowid; + $userstatic->lastname=$obj->lastname; + $userstatic->firstname=$obj->firstname; - $disableline=''; - if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1'); + $disableline=''; + if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1'); - if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid)) - { - $out.= ''; + $out.= ''; - $i++; - } - } - else - { - $out.= ''; - } - else - { - dol_print_error($this->db); - } + $i++; + } + } + else + { + $out.= ''; + } + else + { + dol_print_error($this->db); + } - return $out; - } + return $out; + } - /** - * Return select list of users. Selected users are stored into session. - * List of users are provided into $_SESSION['assignedtouser']. - * - * @param string $action Value for $action - * @param string $htmlname Field name in form - * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue - * @param array $exclude Array list of users id to exclude - * @param int $disabled If select list must be disabled - * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users - * @param array $enableonly Array list of users id to be enabled. All other must be disabled - * @param int $force_entity 0 or Id of environment to force - * @param int $maxlength Maximum length of string into list (0=no limit) - * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status - * @param string $morefilter Add more filters into sql request - * @return string HTML select string - * @see select_dolgroups - */ - function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='') - { - global $conf,$user,$langs; + /** + * Return select list of users. Selected users are stored into session. + * List of users are provided into $_SESSION['assignedtouser']. + * + * @param string $action Value for $action + * @param string $htmlname Field name in form + * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue + * @param array $exclude Array list of users id to exclude + * @param int $disabled If select list must be disabled + * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users + * @param array $enableonly Array list of users id to be enabled. All other must be disabled + * @param int $force_entity 0 or Id of environment to force + * @param int $maxlength Maximum length of string into list (0=no limit) + * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status + * @param string $morefilter Add more filters into sql request + * @return string HTML select string + * @see select_dolgroups + */ + function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='') + { + global $conf,$user,$langs; - $userstatic=new User($this->db); + $userstatic=new User($this->db); $out=''; - // Method with no ajax - //$out.='
    '; - if ($action == 'view') - { + // Method with no ajax + //$out.=''; + if ($action == 'view') + { $out.=''; - } + } else { $out.=''; @@ -1674,60 +1687,60 @@ class Form if ($nbassignetouser) $out.='
    '; //$out.=''; - return $out; - } + return $out; + } - /** - * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list - * - * @param int $selected Preselected products - * @param string $htmlname Name of HTML select field (must be unique in page) - * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service) - * @param int $limit Limit on number of returned lines - * @param int $price_level Level of price to show - * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell - * @param int $finished 2=all, 1=finished, 0=raw material - * @param string $selected_input_value Value of preselected input text (for use with ajax) - * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) - * @param array $ajaxoptions Options for ajax_autocompleter - * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. - * @param int $forcecombo Force to use combo box - * @param string $morecss Add more css on select - * @param int $hidepriceinlabel 1=Hide prices in label - * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used - * 'warehouseopen' = select products from open warehouses, + /** + * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list + * + * @param int $selected Preselected products + * @param string $htmlname Name of HTML select field (must be unique in page) + * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service) + * @param int $limit Limit on number of returned lines + * @param int $price_level Level of price to show + * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell + * @param int $finished 2=all, 1=finished, 0=raw material + * @param string $selected_input_value Value of preselected input text (for use with ajax) + * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) + * @param array $ajaxoptions Options for ajax_autocompleter + * @param int $socid Thirdparty Id (to get also price dedicated to this customer) + * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param int $forcecombo Force to use combo box + * @param string $morecss Add more css on select + * @param int $hidepriceinlabel 1=Hide prices in label + * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used + * 'warehouseopen' = select products from open warehouses, * 'warehouseclosed' = select products from closed warehouses, * 'warehouseinternal' = select products from warehouses for internal correct/transfer only - * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) - * @return void - */ - function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array()) - { - global $langs,$conf; + * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) + * @return void + */ + function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array()) + { + global $langs,$conf; - $price_level = (! empty($price_level) ? $price_level : 0); + $price_level = (! empty($price_level) ? $price_level : 0); - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) - { - $placeholder=''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + { + $placeholder=''; - if ($selected && empty($selected_input_value)) - { - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $producttmpselect = new Product($this->db); - $producttmpselect->fetch($selected); - $selected_input_value=$producttmpselect->ref; - unset($producttmpselect); - } - // mode=1 means customers products - $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&warehousestatus='.$warehouseStatus; - //Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { - $urloption.='&socid='.$socid; - } - print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); + if ($selected && empty($selected_input_value)) + { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + $producttmpselect = new Product($this->db); + $producttmpselect->fetch($selected); + $selected_input_value=$producttmpselect->ref; + unset($producttmpselect); + } + // mode=1 means customers products + $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus; + //Price by customer + if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { + $urloption.='&socid='.$socid; + } + print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); if (!empty($conf->variants->enabled)) { ?> @@ -1801,92 +1814,91 @@ class Form }); trans("RefOrLabel").' : '; - else if ($hidelabel > 1) { - if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; - else $placeholder=' title="'.$langs->trans("RefOrLabel").'"'; - if ($hidelabel == 2) { - print img_picto($langs->trans("Search"), 'search'); - } - } - print 'global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; - if ($hidelabel == 3) { - print img_picto($langs->trans("Search"), 'search'); - } - } - else + } + if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : '; + else if ($hidelabel > 1) { + $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; + if ($hidelabel == 2) { + print img_picto($langs->trans("Search"), 'search'); + } + } + print 'global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; + if ($hidelabel == 3) { + print img_picto($langs->trans("Search"), 'search'); + } + } + else { - print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus); - } - } + print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus); + } + } - /** - * Return list of products for a customer - * - * @param int $selected Preselected product - * @param string $htmlname Name of select html - * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) - * @param int $limit Limit on number of returned lines - * @param int $price_level Level of price to show - * @param string $filterkey Filter on product - * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell - * @param int $finished Filter on finished field: 2=No filter - * @param int $outputmode 0=HTML select string, 1=Array - * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. - * @param int $forcecombo Force to use combo box - * @param string $morecss Add more css on select - * @param int $hidepriceinlabel 1=Hide prices in label - * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used - * 'warehouseopen' = select products from open warehouses, + /** + * Return list of products for a customer + * + * @param int $selected Preselected product + * @param string $htmlname Name of select html + * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) + * @param int $limit Limit on number of returned lines + * @param int $price_level Level of price to show + * @param string $filterkey Filter on product + * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell + * @param int $finished Filter on finished field: 2=No filter + * @param int $outputmode 0=HTML select string, 1=Array + * @param int $socid Thirdparty Id (to get also price dedicated to this customer) + * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param int $forcecombo Force to use combo box + * @param string $morecss Add more css on select + * @param int $hidepriceinlabel 1=Hide prices in label + * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used + * 'warehouseopen' = select products from open warehouses, * 'warehouseclosed' = select products from closed warehouses, * 'warehouseinternal' = select products from warehouses for internal correct/transfer only - * @return array Array of keys for json - */ - function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='') - { - global $langs,$conf,$user,$db; + * @return array Array of keys for json + */ + function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='') + { + global $langs,$conf,$user,$db; - $out=''; - $outarray=array(); + $out=''; + $outarray=array(); - $warehouseStatusArray = array(); - if (! empty($warehouseStatus)) - { - require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; - if (preg_match('/warehouseclosed/', $warehouseStatus)) - { - $warehouseStatusArray[] = Entrepot::STATUS_CLOSED; - } - if (preg_match('/warehouseopen/', $warehouseStatus)) - { - $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL; - } - if (preg_match('/warehouseinternal/', $warehouseStatus)) - { - $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL; - } - } + $warehouseStatusArray = array(); + if (! empty($warehouseStatus)) + { + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; + if (preg_match('/warehouseclosed/', $warehouseStatus)) + { + $warehouseStatusArray[] = Entrepot::STATUS_CLOSED; + } + if (preg_match('/warehouseopen/', $warehouseStatus)) + { + $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL; + } + if (preg_match('/warehouseinternal/', $warehouseStatus)) + { + $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL; + } + } - $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression"; - (count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock"; + $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression"; + (count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock"; - $sql = "SELECT "; - $sql.= $selectFields . $selectFieldsGrouped; - //Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { - $sql.=' ,pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,'; - $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx'; - $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx"; - } + $sql = "SELECT "; + $sql.= $selectFields . $selectFieldsGrouped; + //Price by customer + if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { + $sql.=' ,pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,'; + $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx'; + $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx"; + } - // Multilang : we add translation - if (! empty($conf->global->MAIN_MULTILANGS)) - { - $sql.= ", pl.label as label_translated"; - $selectFields.= ", label_translated"; - } + // Multilang : we add translation + if (! empty($conf->global->MAIN_MULTILANGS)) + { + $sql.= ", pl.label as label_translated"; + $selectFields.= ", label_translated"; + } // Price by quantity if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { @@ -1898,115 +1910,115 @@ class Form if ($price_level >= 1 && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql.= " AND price_level=".$price_level; $sql.= " ORDER BY date_price"; $sql.= " DESC LIMIT 1) as price_by_qty"; - $selectFields.= ", price_rowid, price_by_qty"; + $selectFields.= ", price_rowid, price_by_qty"; + } + $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; + if (count($warehouseStatusArray)) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid"; } - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - if (count($warehouseStatusArray)) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid"; - } - //Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { - $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid"; - } - // Multilang : we add translation - 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() ."'"; - } + //Price by customer + if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { + $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid"; + } + // Multilang : we add translation + 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->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { - $sql .= " LEFT JOIN llx_product_attribute_combination pac ON pac.fk_product_child = p.rowid"; - } + if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { + $sql .= " LEFT JOIN llx_product_attribute_combination pac ON pac.fk_product_child = p.rowid"; + } - $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; - if (count($warehouseStatusArray)) - { - $sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))'; - } + $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; + if (count($warehouseStatusArray)) + { + $sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))'; + } - if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { - $sql .= " AND pac.rowid IS NULL"; - } + if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { + $sql .= " AND pac.rowid IS NULL"; + } - if ($finished == 0) - { - $sql.= " AND p.finished = ".$finished; - } - elseif ($finished == 1) - { - $sql.= " AND p.finished = ".$finished; - if ($status >= 0) $sql.= " AND p.tosell = ".$status; - } - elseif ($status >= 0) - { - $sql.= " AND p.tosell = ".$status; - } - if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype; - // Add criteria on ref/label - if ($filterkey != '') - { - $sql.=' AND ('; - $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on - // For natural search - $scrit = explode(' ', $filterkey); - $i=0; - if (count($scrit) > 1) $sql.="("; - foreach ($scrit as $crit) - { - if ($i > 0) $sql.=" AND "; - $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'"; - if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'"; - $sql.=")"; - $i++; - } - if (count($scrit) > 1) $sql.=")"; - if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'"; - $sql.=')'; - } - if (count($warehouseStatusArray)) - { - $sql.= ' GROUP BY'.$selectFields; - } - $sql.= $db->order("p.ref"); - $sql.= $db->plimit($limit); + if ($finished == 0) + { + $sql.= " AND p.finished = ".$finished; + } + elseif ($finished == 1) + { + $sql.= " AND p.finished = ".$finished; + if ($status >= 0) $sql.= " AND p.tosell = ".$status; + } + elseif ($status >= 0) + { + $sql.= " AND p.tosell = ".$status; + } + if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype; + // Add criteria on ref/label + if ($filterkey != '') + { + $sql.=' AND ('; + $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on + // For natural search + $scrit = explode(' ', $filterkey); + $i=0; + if (count($scrit) > 1) $sql.="("; + foreach ($scrit as $crit) + { + if ($i > 0) $sql.=" AND "; + $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'"; + if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'"; + $sql.=")"; + $i++; + } + if (count($scrit) > 1) $sql.=")"; + if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'"; + $sql.=')'; + } + if (count($warehouseStatusArray)) + { + $sql.= ' GROUP BY'.$selectFields; + } + $sql.= $db->order("p.ref"); + $sql.= $db->plimit($limit, 0); - // Build output string - dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; - $num = $this->db->num_rows($result); + // Build output string + dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; + $num = $this->db->num_rows($result); - $events=null; + $events=null; - if ($conf->use_javascript_ajax && ! $forcecombo) - { + if ($conf->use_javascript_ajax && ! $forcecombo) + { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT); - $out.= $comboenhancement; - } + $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT); + $out.= $comboenhancement; + } - $out.=''; - $textifempty=''; - // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. - //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; - if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) - { - if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); - else $textifempty.=$langs->trans("All"); - } - if ($showempty) $out.=''; + $textifempty=''; + // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. + //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; + if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + { + if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); + else $textifempty.=$langs->trans("All"); + } + if ($showempty) $out.=''; - $i = 0; - while ($num && $i < $num) - { - $opt = ''; + $i = 0; + while ($num && $i < $num) + { + $opt = ''; $optJson = array(); $objp = $this->db->fetch_object($result); @@ -2047,19 +2059,19 @@ class Form } else { - if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) { - $price_product = new Product($this->db); - $price_product->fetch($objp->rowid, '', '', 1); - $priceparser = new PriceParser($this->db); - $price_result = $priceparser->parseProduct($price_product); - if ($price_result >= 0) { - $objp->price = $price_result; - $objp->unitprice = $price_result; - //Calculate the VAT - $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100)); - $objp->price_ttc = price2num($objp->price_ttc,'MU'); - } - } + if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) { + $price_product = new Product($this->db); + $price_product->fetch($objp->rowid, '', '', 1); + $priceparser = new PriceParser($this->db); + $price_result = $priceparser->parseProduct($price_product); + if ($price_result >= 0) { + $objp->price = $price_result; + $objp->unitprice = $price_result; + //Calculate the VAT + $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100)); + $objp->price_ttc = price2num($objp->price_ttc,'MU'); + } + } $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel); // Add new entry // "key" value of json key array is used by jQuery automatically as selected value @@ -2068,128 +2080,128 @@ class Form array_push($outarray, $optJson); } - $i++; - } + $i++; + } - $out.=''; + $out.=''; - $this->db->free($result); + $this->db->free($result); - if (empty($outputmode)) return $out; - return $outarray; - } - else + if (empty($outputmode)) return $out; + return $outarray; + } + else { - dol_print_error($db); - } - } + dol_print_error($db); + } + } - /** - * constructProductListOption - * - * @param resultset $objp Resultset of fetch - * @param string $opt Option (var used for returned value in string option format) - * @param string $optJson Option (var used for returned value in json format) - * @param int $price_level Price level - * @param string $selected Preselected value - * @param int $hidepriceinlabel Hide price in label - * @return void - */ + /** + * constructProductListOption + * + * @param resultset $objp Resultset of fetch + * @param string $opt Option (var used for returned value in string option format) + * @param string $optJson Option (var used for returned value in json format) + * @param int $price_level Price level + * @param string $selected Preselected value + * @param int $hidepriceinlabel Hide price in label + * @return void + */ private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0) { global $langs,$conf,$user,$db; - $outkey=''; - $outval=''; - $outref=''; - $outlabel=''; - $outdesc=''; - $outbarcode=''; - $outtype=''; - $outprice_ht=''; - $outprice_ttc=''; - $outpricebasetype=''; - $outtva_tx=''; + $outkey=''; + $outval=''; + $outref=''; + $outlabel=''; + $outdesc=''; + $outbarcode=''; + $outtype=''; + $outprice_ht=''; + $outprice_ttc=''; + $outpricebasetype=''; + $outtva_tx=''; $outqty=1; $outdiscount=0; $maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO); - $label=$objp->label; - if (! empty($objp->label_translated)) $label=$objp->label_translated; - if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','$1',$label,1); + $label=$objp->label; + if (! empty($objp->label_translated)) $label=$objp->label_translated; + if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','$1',$label,1); - $outkey=$objp->rowid; - $outref=$objp->ref; - $outlabel=$objp->label; - $outdesc=$objp->description; - $outbarcode=$objp->barcode; + $outkey=$objp->rowid; + $outref=$objp->ref; + $outlabel=$objp->label; + $outdesc=$objp->description; + $outbarcode=$objp->barcode; - $outtype=$objp->fk_product_type; - $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):''; - $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):''; + $outtype=$objp->fk_product_type; + $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):''; + $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):''; - $opt = '\n"; + $opt.= "\n"; $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit); } - /** - * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list) - * - * @param int $socid Id third party - * @param string $selected Preselected product - * @param string $htmlname Name of HTML Select - * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) - * @param string $filtre For a SQL filter - * @param array $ajaxoptions Options for ajax_autocompleter + /** + * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list) + * + * @param int $socid Id third party + * @param string $selected Preselected product + * @param string $htmlname Name of HTML Select + * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) + * @param string $filtre For a SQL filter + * @param array $ajaxoptions Options for ajax_autocompleter * @param int $hidelabel Hide label (0=no, 1=yes) * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices - * @return void - */ - function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0) - { - global $langs,$conf; - global $price_level, $status, $finished; + * @return void + */ + function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0) + { + global $langs,$conf; + global $price_level, $status, $finished; - $selected_input_value=''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) - { - if ($selected > 0) - { - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $producttmpselect = new Product($this->db); - $producttmpselect->fetch($selected); - $selected_input_value=$producttmpselect->ref; - unset($producttmpselect); - } + $selected_input_value=''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + { + if ($selected > 0) + { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + $producttmpselect = new Product($this->db); + $producttmpselect->fetch($selected); + $selected_input_value=$producttmpselect->ref; + unset($producttmpselect); + } // mode=2 means suppliers products - $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice; - print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); - print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').''; - } - else - { - print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice); - } - } + $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice; + print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); + print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').''; + } + else + { + print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice); + } + } - /** - * Return list of suppliers products - * - * @param int $socid Id societe fournisseur (0 pour aucun filtre) - * @param int $selected Produit pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) - * @param string $filtre Pour filtre sql - * @param string $filterkey Filtre des produits - * @param int $statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request) - * @param int $outputmode 0=HTML select string, 1=Array - * @param int $limit Limit of line number + /** + * Return list of suppliers products + * + * @param int $socid Id societe fournisseur (0 pour aucun filtre) + * @param int $selected Produit pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) + * @param string $filtre Pour filtre sql + * @param string $filterkey Filtre des produits + * @param int $statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request) + * @param int $outputmode 0=HTML select string, 1=Array + * @param int $limit Limit of line number * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices - * @return array Array of keys for json - */ - function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0) - { - global $langs,$conf,$db; + * @return array Array of keys for json + */ + function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0) + { + global $langs,$conf,$db; - $out=''; - $outarray=array(); + $out=''; + $outarray=array(); - $langs->load('stocks'); + $langs->load('stocks'); - $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,"; - $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,"; - $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,"; - $sql.= " pfp.supplier_reputation"; - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; - if ($socid) $sql.= " AND pfp.fk_soc = ".$socid; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; - $sql.= " WHERE p.entity IN (".getEntity('product').")"; - $sql.= " AND p.tobuy = 1"; - if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype); - if (! empty($filtre)) $sql.=" ".$filtre; - // Add criteria on ref/label - if ($filterkey != '') - { - $sql.=' AND ('; - $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on - // For natural search - $scrit = explode(' ', $filterkey); - $i=0; - if (count($scrit) > 1) $sql.="("; - foreach ($scrit as $crit) - { - if ($i > 0) $sql.=" AND "; - $sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')"; - $i++; - } - if (count($scrit) > 1) $sql.=")"; - if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; - $sql.=')'; - } - $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC"; - $sql.= $db->plimit($limit); + $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,"; + $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,"; + $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,"; + $sql.= " pfp.supplier_reputation"; + $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; + if ($socid) $sql.= " AND pfp.fk_soc = ".$socid; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; + $sql.= " WHERE p.entity IN (".getEntity('product').")"; + $sql.= " AND p.tobuy = 1"; + if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype); + if (! empty($filtre)) $sql.=" ".$filtre; + // Add criteria on ref/label + if ($filterkey != '') + { + $sql.=' AND ('; + $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on + // For natural search + $scrit = explode(' ', $filterkey); + $i=0; + if (count($scrit) > 1) $sql.="("; + foreach ($scrit as $crit) + { + if ($i > 0) $sql.=" AND "; + $sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')"; + $i++; + } + if (count($scrit) > 1) $sql.=")"; + if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; + $sql.=')'; + } + $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC"; + $sql.= $db->plimit($limit, 0); - // Build output string + // Build output string - dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; + dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; - $num = $this->db->num_rows($result); + $num = $this->db->num_rows($result); - //$out.=''; - if (! $selected) $out.=''; - else $out.=''; + //$out.=''; + if (! $selected) $out.=''; + else $out.=''; - $i = 0; - while ($i < $num) - { - $objp = $this->db->fetch_object($result); + $i = 0; + while ($i < $num) + { + $objp = $this->db->fetch_object($result); - $outkey=$objp->idprodfournprice; // id in table of price - if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid; // id of product + $outkey=$objp->idprodfournprice; // id in table of price + if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid; // id of product - $outref=$objp->ref; - $outval=''; - $outqty=1; + $outref=$objp->ref; + $outval=''; + $outqty=1; $outdiscount=0; - $outtype=$objp->fk_product_type; - $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):''; - $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):''; + $outtype=$objp->fk_product_type; + $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):''; + $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):''; - $opt = '\n"; + $opt .= " - ".$reputations[$objp->supplier_reputation]; + $outval.=" - ".$reputations[$objp->supplier_reputation]; + } + } + else + { + if (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier + { + $opt.= $langs->trans("NoPriceDefinedForThisSupplier"); + $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier"); + } + else // No supplier price defined for product, even on other suppliers + { + $opt.= $langs->trans("NoPriceDefinedForThisSupplier"); + $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier"); + } + } + $opt .= "\n"; - // Add new entry - // "key" value of json key array is used by jQuery automatically as selected value - // "label" value of json key array is used by jQuery automatically as text for combo box - $out.=$opt; - array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false))); + // Add new entry + // "key" value of json key array is used by jQuery automatically as selected value + // "label" value of json key array is used by jQuery automatically as text for combo box + $out.=$opt; + array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false))); // Exemple of var_dump $outarray // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp" // ["label"]=>string(76) "ppp (fff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)" // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false) - //} - //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval)); - //$outval=array('label'=>'ppp (fff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)'); - //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval)); + //} + //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval)); + //$outval=array('label'=>'ppp (fff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)'); + //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval)); - $i++; - } - $out.=''; + $i++; + } + $out.=''; - $this->db->free($result); + $this->db->free($result); - if (empty($outputmode)) return $out; - return $outarray; - } - else - { - dol_print_error($this->db); - } - } + $out.=ajax_combobox($htmlname); - /** - * Return list of suppliers prices for a product - * - * @param int $productid Id of product - * @param string $htmlname Name of HTML field - * @param int $selected_supplier Pre-selected supplier if more than 1 result - * @return void - */ - function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='') - { - global $langs,$conf; + if (empty($outputmode)) return $out; + return $outarray; + } + else + { + dol_print_error($this->db); + } + } - $langs->load('stocks'); + /** + * Return list of suppliers prices for a product + * + * @param int $productid Id of product + * @param string $htmlname Name of HTML field + * @param int $selected_supplier Pre-selected supplier if more than 1 result + * @return void + */ + function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='') + { + global $langs,$conf; - $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,"; - $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,"; - $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name"; - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; - $sql.= " WHERE p.entity IN (".getEntity('productprice').")"; - $sql.= " AND p.tobuy = 1"; - $sql.= " AND s.fournisseur = 1"; - $sql.= " AND p.rowid = ".$productid; - $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC"; + $langs->load('stocks'); - dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG); - $result=$this->db->query($sql); + $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,"; + $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,"; + $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name"; + $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; + $sql.= " WHERE p.entity IN (".getEntity('productprice').")"; + $sql.= " AND p.tobuy = 1"; + $sql.= " AND s.fournisseur = 1"; + $sql.= " AND p.rowid = ".$productid; + $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC"; - if ($result) - { - $num = $this->db->num_rows($result); + dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG); + $result=$this->db->query($sql); - $form = ''; - $i = 0; - while ($i < $num) - { - $objp = $this->db->fetch_object($result); + if (! $num) + { + $form.= ''; + } + else + { + require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; + $form.= ''; - $opt = '\n"; + $opt.= $objp->quantity.' '; - $form.= $opt; - $i++; - } - } + if ($objp->quantity == 1) + { + $opt.= $langs->trans("Unit"); + } + else + { + $opt.= $langs->trans("Units"); + } + if ($objp->quantity > 1) + { + $opt.=" - "; + $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit"); + } + if ($objp->duration) $opt .= " - ".$objp->duration; + $opt .= "\n"; - $form.= ''; - $this->db->free($result); - return $form; - } - else - { - dol_print_error($this->db); - } - } + $form.= $opt; + $i++; + } + } - /** - * Return list of delivery address - * - * @param string $selected Id contact pre-selectionn - * @param int $socid Id of company - * @param string $htmlname Name of HTML field - * @param int $showempty Add an empty field - * @return integer|null - */ - function select_address($selected, $socid, $htmlname='address_id',$showempty=0) - { - // On recherche les utilisateurs - $sql = "SELECT a.rowid, a.label"; - $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a"; - $sql .= " WHERE a.fk_soc = ".$socid; - $sql .= " ORDER BY a.label ASC"; + $form.= ''; + $this->db->free($result); + return $form; + } + else + { + dol_print_error($this->db); + } + } - dol_syslog(get_class($this)."::select_address", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - print ''; - return $num; - } - else - { - dol_print_error($this->db); - } - } + dol_syslog(get_class($this)."::select_address", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + print ''; + return $num; + } + else + { + dol_print_error($this->db); + } + } - /** - * Load into cache list of payment terms - * - * @return int Nb of lines loaded, <0 if KO - */ - function load_cache_conditions_paiements() - { - global $langs; + /** + * Load into cache list of payment terms + * + * @return int Nb of lines loaded, <0 if KO + */ + function load_cache_conditions_paiements() + { + global $langs; - $num = count($this->cache_conditions_paiements); - if ($num > 0) return 0; // Cache already loaded + $num = count($this->cache_conditions_paiements); + if ($num > 0) return 0; // Cache already loaded - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); - $sql = "SELECT rowid, code, libelle as label"; - $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term'; - $sql.= " WHERE active > 0"; - $sql.= " ORDER BY sortorder"; + $sql = "SELECT rowid, code, libelle as label"; + $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term'; + $sql.= " WHERE entity = " . getEntity('c_payment_term'); + $sql.= " AND active > 0"; + $sql.= " ORDER BY sortorder"; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:'')); - $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code; - $this->cache_conditions_paiements[$obj->rowid]['label']=$label; - $i++; - } + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:'')); + $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code; + $this->cache_conditions_paiements[$obj->rowid]['label']=$label; + $i++; + } //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table - return $num; - } - else + return $num; + } + else { - dol_print_error($this->db); - return -1; - } - } + dol_print_error($this->db); + return -1; + } + } - /** - * Charge dans cache la liste des délais de livraison possibles - * - * @return int Nb of lines loaded, <0 if KO - */ - function load_cache_availability() - { - global $langs; + /** + * Charge dans cache la liste des délais de livraison possibles + * + * @return int Nb of lines loaded, <0 if KO + */ + function load_cache_availability() + { + global $langs; - $num = count($this->cache_availability); - if ($num > 0) return 0; // Cache already loaded + $num = count($this->cache_availability); + if ($num > 0) return 0; // Cache already loaded - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $langs->load('propal'); - $sql = "SELECT rowid, code, label"; - $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability'; - $sql.= " WHERE active > 0"; + $sql = "SELECT rowid, code, label"; + $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability'; + $sql.= " WHERE active > 0"; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:'')); - $this->cache_availability[$obj->rowid]['code'] =$obj->code; - $this->cache_availability[$obj->rowid]['label']=$label; - $i++; - } - - $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1); - - return $num; - } - else + $resql = $this->db->query($sql); + if ($resql) { - dol_print_error($this->db); - return -1; - } - } + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - /** - * Retourne la liste des types de delais de livraison possibles - * - * @param int $selected Id du type de delais pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $filtertype To add a filter - * @param int $addempty Add empty entry - * @return void - */ - function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0) - { - global $langs,$user; + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:'')); + $this->cache_availability[$obj->rowid]['code'] =$obj->code; + $this->cache_availability[$obj->rowid]['label']=$label; + $i++; + } - $this->load_cache_availability(); + $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1); - dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG); - - print ''; - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } - - /** - * Load into cache cache_demand_reason, array of input reasons - * - * @return int Nb of lines loaded, <0 if KO - */ - function loadCacheInputReason() - { - global $langs; - - $num = count($this->cache_demand_reason); - if ($num > 0) return 0; // Cache already loaded - - $sql = "SELECT rowid, code, label"; - $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason'; - $sql.= " WHERE active > 0"; - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - $tmparray=array(); - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label=($langs->trans("DemandReasonType".$obj->code)!=("DemandReasonType".$obj->code)?$langs->trans("DemandReasonType".$obj->code):($obj->label!='-'?$obj->label:'')); - $tmparray[$obj->rowid]['id'] =$obj->rowid; - $tmparray[$obj->rowid]['code'] =$obj->code; - $tmparray[$obj->rowid]['label']=$label; - $i++; - } - - $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1); - - unset($tmparray); - return $num; - } - else + return $num; + } + else { - dol_print_error($this->db); - return -1; - } - } + dol_print_error($this->db); + return -1; + } + } - /** + /** + * Retourne la liste des types de delais de livraison possibles + * + * @param int $selected Id du type de delais pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $filtertype To add a filter + * @param int $addempty Add empty entry + * @return void + */ + function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0) + { + global $langs,$user; + + $this->load_cache_availability(); + + dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG); + + print ''; + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } + + /** + * Load into cache cache_demand_reason, array of input reasons + * + * @return int Nb of lines loaded, <0 if KO + */ + function loadCacheInputReason() + { + global $langs; + + $num = count($this->cache_demand_reason); + if ($num > 0) return 0; // Cache already loaded + + $sql = "SELECT rowid, code, label"; + $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason'; + $sql.= " WHERE active > 0"; + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + $tmparray=array(); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label=($langs->trans("DemandReasonType".$obj->code)!=("DemandReasonType".$obj->code)?$langs->trans("DemandReasonType".$obj->code):($obj->label!='-'?$obj->label:'')); + $tmparray[$obj->rowid]['id'] =$obj->rowid; + $tmparray[$obj->rowid]['code'] =$obj->code; + $tmparray[$obj->rowid]['label']=$label; + $i++; + } + + $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1); + + unset($tmparray); + return $num; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...) * List found into table c_input_reason loaded by loadCacheInputReason - * - * @param int $selected Id or code of type origin to select by default - * @param string $htmlname Nom de la zone select - * @param string $exclude To exclude a code value (Example: SRC_PROP) - * @param int $addempty Add an empty entry - * @return void - */ - function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0) - { - global $langs,$user; + * + * @param int $selected Id or code of type origin to select by default + * @param string $htmlname Nom de la zone select + * @param string $exclude To exclude a code value (Example: SRC_PROP) + * @param int $addempty Add an empty entry + * @return void + */ + function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0) + { + global $langs,$user; - $this->loadCacheInputReason(); + $this->loadCacheInputReason(); - print ''; - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } - - /** - * Charge dans cache la liste des types de paiements possibles - * - * @return int Nb of lines loaded, <0 if KO - */ - function load_cache_types_paiements() - { - global $langs; - - $num=count($this->cache_types_paiements); - if ($num > 0) return $num; // Cache already loaded - - dol_syslog(__METHOD__, LOG_DEBUG); - - $this->cache_types_paiements = array(); - - $sql = "SELECT id, code, libelle as label, type, active"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement"; - //if ($active >= 0) $sql.= " WHERE active = ".$active; - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:'')); - $this->cache_types_paiements[$obj->id]['id'] =$obj->id; - $this->cache_types_paiements[$obj->id]['code'] =$obj->code; - $this->cache_types_paiements[$obj->id]['label']=$label; - $this->cache_types_paiements[$obj->id]['type'] =$obj->type; - $this->cache_types_paiements[$obj->id]['active'] =$obj->active; - $i++; - } - - $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1); - - return $num; - } - else + print ''; + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } + + /** + * Charge dans cache la liste des types de paiements possibles + * + * @return int Nb of lines loaded, <0 if KO + */ + function load_cache_types_paiements() + { + global $langs; + + $num=count($this->cache_types_paiements); + if ($num > 0) return $num; // Cache already loaded + + dol_syslog(__METHOD__, LOG_DEBUG); + + $this->cache_types_paiements = array(); + + $sql = "SELECT id, code, libelle as label, type, active"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement"; + $sql.= " WHERE entity = " . getEntity('c_paiement'); + //if ($active >= 0) $sql.= " AND active = ".$active; + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:'')); + $this->cache_types_paiements[$obj->id]['id'] =$obj->id; + $this->cache_types_paiements[$obj->id]['code'] =$obj->code; + $this->cache_types_paiements[$obj->id]['label']=$label; + $this->cache_types_paiements[$obj->id]['type'] =$obj->type; + $this->cache_types_paiements[$obj->id]['active'] =$obj->active; + $i++; + } + + $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1); + + return $num; + } + else + { + dol_print_error($this->db); + return -1; + } + } - /** - * Return list of payment modes. - * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want. - * See instead to force the default value by the caller. - * - * @param int $selected Id of payment term to preselect by default - * @param string $htmlname Nom de la zone select - * @param int $filtertype Not used - * @param int $addempty Add an empty entry - * @return void - */ - function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0) - { - global $langs, $user, $conf; + /** + * Return list of payment modes. + * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want. + * See instead to force the default value by the caller. + * + * @param int $selected Id of payment term to preselect by default + * @param string $htmlname Nom de la zone select + * @param int $filtertype Not used + * @param int $addempty Add an empty entry + * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info + * @param string $morecss Add more CSS on select tag + * @return void + */ + function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='') + { + global $langs, $user, $conf; - dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG); + dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG); - $this->load_cache_conditions_paiements(); + $this->load_cache_conditions_paiements(); - // Set default value if not already set by caller - if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID; + // Set default value if not already set by caller + if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID; - print ''; - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } + print ''; + if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } - /** - * Return list of payment methods - * - * @param string $selected Id du mode de paiement pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz)) - * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code - * @param int $empty 1=peut etre vide, 0 sinon - * @param int $noadmininfo 0=Add admin info, 1=Disable admin info - * @param int $maxlength Max length of label - * @param int $active Active or not, -1 = all - * @param string $morecss Add more css - * @return void - */ - function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1, $morecss='') - { - global $langs,$user; + /** + * Return list of payment methods + * + * @param string $selected Id du mode de paiement pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz)) + * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code + * @param int $empty 1=peut etre vide, 0 sinon + * @param int $noadmininfo 0=Add admin info, 1=Disable admin info + * @param int $maxlength Max length of label + * @param int $active Active or not, -1 = all + * @param string $morecss Add more CSS on select tag + * @return void + */ + function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1, $morecss='') + { + global $langs,$user; - dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG); + dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG); - $filterarray=array(); - if ($filtertype == 'CRDT') $filterarray=array(0,2,3); - elseif ($filtertype == 'DBIT') $filterarray=array(1,2,3); - elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype); + $filterarray=array(); + if ($filtertype == 'CRDT') $filterarray=array(0,2,3); + elseif ($filtertype == 'DBIT') $filterarray=array(1,2,3); + elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype); - $this->load_cache_types_paiements(); + $this->load_cache_types_paiements(); - print ''; + if ($empty) print ''; + foreach($this->cache_types_paiements as $id => $arraytypes) + { + // If not good status + if ($active >= 0 && $arraytypes['active'] != $active) continue; - // On passe si on a demande de filtrer sur des modes de paiments particuliers - if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue; + // On passe si on a demande de filtrer sur des modes de paiments particuliers + if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue; - // We discard empty line if showempty is on because an empty line has already been output. - if ($empty && empty($arraytypes['code'])) continue; + // We discard empty line if showempty is on because an empty line has already been output. + if ($empty && empty($arraytypes['code'])) continue; - if ($format == 0) print ''; - } - print ''; - if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } + if ($format == 0) print ''; + } + print ''; + if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } - /** - * Selection HT or TTC - * - * @param string $selected Id pre-selectionne - * @param string $htmlname Nom de la zone select - * @return string Code of HTML select to chose tax or not - */ - function selectPriceBaseType($selected='',$htmlname='price_base_type') - { - global $langs; + /** + * Selection HT or TTC + * + * @param string $selected Id pre-selectionne + * @param string $htmlname Nom de la zone select + * @return string Code of HTML select to chose tax or not + */ + function selectPriceBaseType($selected='',$htmlname='price_base_type') + { + global $langs; - $return=''; + $return=''; - $return.= ''; + $options = array( 'HT'=>$langs->trans("HT"), 'TTC'=>$langs->trans("TTC") - ); - foreach($options as $id => $value) - { - if ($selected == $id) - { - $return.= ''; - } - $return.= ''; + ); + foreach($options as $id => $value) + { + if ($selected == $id) + { + $return.= ''; + } + $return.= ''; - return $return; - } + return $return; + } - /** - * Return a HTML select list of shipping mode - * - * @param string $selected Id shipping mode pre-selected - * @param string $htmlname Name of select zone - * @param string $filtre To filter list - * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @param string $moreattrib To add more attribute on select - * @return void - */ - function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='') - { - global $langs, $conf, $user; + /** + * Return a HTML select list of shipping mode + * + * @param string $selected Id shipping mode pre-selected + * @param string $htmlname Name of select zone + * @param string $filtre To filter list + * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @param string $moreattrib To add more attribute on select + * @return void + */ + function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='') + { + global $langs, $conf, $user; - $langs->load("admin"); - $langs->load("deliveries"); + $langs->load("admin"); + $langs->load("deliveries"); - $sql = "SELECT rowid, code, libelle as label"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode"; - $sql.= " WHERE active > 0"; - if ($filtre) $sql.=" AND ".$filtre; - $sql.= " ORDER BY libelle ASC"; + $sql = "SELECT rowid, code, libelle as label"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode"; + $sql.= " WHERE active > 0"; + if ($filtre) $sql.=" AND ".$filtre; + $sql.= " ORDER BY libelle ASC"; - dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $i = 0; - if ($num) { - print '"; - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } else { - print $langs->trans("NoShippingMethodDefined"); - } - } else { - dol_print_error($this->db); - } - } + dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + if ($num) { + print '"; + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } else { + print $langs->trans("NoShippingMethodDefined"); + } + } else { + dol_print_error($this->db); + } + } - /** - * Display form to select shipping mode - * - * @param string $page Page - * @param int $selected Id of shipping mode - * @param string $htmlname Name of select html field - * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @return void - */ - function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0) - { - global $langs, $db; + /** + * Display form to select shipping mode + * + * @param string $page Page + * @param int $selected Id of shipping mode + * @param string $htmlname Name of select html field + * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @return void + */ + function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0) + { + global $langs, $db; - $langs->load("deliveries"); + $langs->load("deliveries"); - if ($htmlname != "none") { - print '
    '; - print ''; - print ''; - $this->selectShippingMethod($selected, $htmlname, '', $addempty); - print ''; - print '
    '; - } else { - if ($selected) { - $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code'); - print $langs->trans("SendingMethod".strtoupper($code)); - } else { - print " "; - } - } - } + if ($htmlname != "none") { + print '
    '; + print ''; + print ''; + $this->selectShippingMethod($selected, $htmlname, '', $addempty); + print ''; + print '
    '; + } else { + if ($selected) { + $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code'); + print $langs->trans("SendingMethod".strtoupper($code)); + } else { + print " "; + } + } + } /** * Creates HTML last in cycle situation invoices selector @@ -3264,355 +3282,360 @@ class Form return $opt; } - /** - * Creates HTML units selector (code => label) - * - * @param string $selected Preselected Unit ID - * @param string $htmlname Select name - * @param int $showempty Add a nempty line - * @return string HTML select - */ - function selectUnits($selected = '', $htmlname = 'units', $showempty=0) - { - global $langs; + /** + * Creates HTML units selector (code => label) + * + * @param string $selected Preselected Unit ID + * @param string $htmlname Select name + * @param int $showempty Add a nempty line + * @return string HTML select + */ + function selectUnits($selected = '', $htmlname = 'units', $showempty=0) + { + global $langs; - $langs->load('products'); + $langs->load('products'); - $return= ''; - $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units'; - $sql.= ' WHERE active > 0'; + $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units'; + $sql.= ' WHERE active > 0'; - $resql = $this->db->query($sql); - if($resql && $this->db->num_rows($resql) > 0) - { - if ($showempty) $return .= ''; + $resql = $this->db->query($sql); + if($resql && $this->db->num_rows($resql) > 0) + { + if ($showempty) $return .= ''; - while($res = $this->db->fetch_object($resql)) - { - if ($selected == $res->rowid) - { - $return.=''; - } - else - { - $return.=''; - } - } - $return.=''; - } - return $return; - } + while($res = $this->db->fetch_object($resql)) + { + if ($selected == $res->rowid) + { + $return.=''; + } + else + { + $return.=''; + } + } + $return.=''; + } + return $return; + } - /** - * Return a HTML select list of bank accounts - * - * @param string $selected Id account pre-selected - * @param string $htmlname Name of select zone - * @param int $statut Status of searched accounts (0=open, 1=closed, 2=both) - * @param string $filtre To filter list - * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @param string $moreattrib To add more attribute on select - * @return void - */ - function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='') - { - global $langs, $conf; + /** + * Return a HTML select list of bank accounts + * + * @param string $selected Id account pre-selected + * @param string $htmlname Name of select zone + * @param int $statut Status of searched accounts (0=open, 1=closed, 2=both) + * @param string $filtre To filter list + * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @param string $moreattrib To add more attribute on select + * @param int $showcurrency Show currency in label + * @return void + */ + function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0) + { + global $langs, $conf; - $langs->load("admin"); + $langs->load("admin"); - $sql = "SELECT rowid, label, bank, clos as status"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account"; - $sql.= " WHERE entity IN (".getEntity('bank_account').")"; - if ($statut != 2) $sql.= " AND clos = '".$statut."'"; - if ($filtre) $sql.=" AND ".$filtre; - $sql.= " ORDER BY label"; + $sql = "SELECT rowid, label, bank, clos as status, currency_code"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_account"; + $sql.= " WHERE entity IN (".getEntity('bank_account').")"; + if ($statut != 2) $sql.= " AND clos = '".$statut."'"; + if ($filtre) $sql.=" AND ".$filtre; + $sql.= " ORDER BY label"; - dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - if ($num) - { - print ''; + if ($useempty == 1 || ($useempty == 2 && $num > 1)) + { + print ''; + } - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - if ($selected == $obj->rowid) - { - print ''; - $i++; - } - print ""; - } - else - { - print $langs->trans("NoActiveBankAccountDefined"); - } - } - else { - dol_print_error($this->db); - } - } + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + if ($selected == $obj->rowid) + { + print ''; + $i++; + } + print ""; + } + else + { + print $langs->trans("NoActiveBankAccountDefined"); + } + } + else { + dol_print_error($this->db); + } + } - /** - * Display form to select bank account - * - * @param string $page Page - * @param int $selected Id of bank account - * @param string $htmlname Name of select html field - * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @return void - */ - function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0) - { - global $langs; - if ($htmlname != "none") { - print '
    '; - print ''; - print ''; - $this->select_comptes($selected, $htmlname, 0, '', $addempty); - print ''; - print '
    '; - } else { + /** + * Display form to select bank account + * + * @param string $page Page + * @param int $selected Id of bank account + * @param string $htmlname Name of select html field + * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @return void + */ + function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0) + { + global $langs; + if ($htmlname != "none") { + print '
    '; + print ''; + print ''; + $this->select_comptes($selected, $htmlname, 0, '', $addempty); + print ''; + print '
    '; + } else { - $langs->load('banks'); + $langs->load('banks'); - if ($selected) { - require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php'; - $bankstatic=new Account($this->db); - $bankstatic->fetch($selected); - print $this->textwithpicto($bankstatic->getNomUrl(1),$langs->trans("AccountCurrency").' '.$bankstatic->currency_code); - } else { - print " "; - } - } - } + if ($selected) { + require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php'; + $bankstatic=new Account($this->db); + $bankstatic->fetch($selected); + print $bankstatic->getNomUrl(1); + } else { + print " "; + } + } + } - /** - * Return list of categories having choosed type - * - * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. - * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element) - * @param string $htmlname HTML field name - * @param int $maxlength Maximum length for labels - * @param int $excludeafterid Exclude all categories after this leaf in category tree. - * @param int $outputmode 0=HTML select string, 1=Array - * @return string - * @see select_categories - */ - function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0) - { - global $conf, $langs; - $langs->load("categories"); + /** + * Return list of categories having choosed type + * + * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. + * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element) + * @param string $htmlname HTML field name + * @param int $maxlength Maximum length for labels + * @param int $excludeafterid Exclude all categories after this leaf in category tree. + * @param int $outputmode 0=HTML select string, 1=Array + * @return string + * @see select_categories + */ + function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0) + { + global $conf, $langs; + $langs->load("categories"); include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // For backward compatibility if (is_numeric($type)) { - dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); + dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); } if ($type === Categorie::TYPE_BANK_LINE) { - // TODO Move this into common category feature - $categids=array(); - $sql = "SELECT c.label, c.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c"; - $sql.= " WHERE entity = ".$conf->entity; - $sql.= " ORDER BY c.label"; - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) - { - $objp = $this->db->fetch_object($result); - if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label); - $i++; - } - $this->db->free($result); - } - else dol_print_error($this->db); + // TODO Move this into common category feature + $categids=array(); + $sql = "SELECT c.label, c.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c"; + $sql.= " WHERE entity = ".$conf->entity; + $sql.= " ORDER BY c.label"; + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $objp = $this->db->fetch_object($result); + if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label); + $i++; + } + $this->db->free($result); + } + else dol_print_error($this->db); } else { - $cat = new Categorie($this->db); - $cate_arbo = $cat->get_full_arbo($type,$excludeafterid); + $cat = new Categorie($this->db); + $cate_arbo = $cat->get_full_arbo($type, $excludeafterid); } - $output = ''; $outarray=array(); - if (is_array($cate_arbo)) - { - if (! count($cate_arbo)) $output.= ''; - else - { - $output.= ''; - foreach($cate_arbo as $key => $value) - { - if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1)) - { - $add = 'selected '; - } - else - { - $add = ''; - } - $output.= ''; + if (is_array($cate_arbo)) + { + if (! count($cate_arbo)) $output.= ''; + else + { + $output.= ''; + foreach($cate_arbo as $key => $value) + { + if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1)) + { + $add = 'selected '; + } + else + { + $add = ''; + } + $output.= ''; $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel']; - } - } - } - $output.= ''; - $output.= "\n"; + } + } + } + $output.= ''; + $output.= "\n"; if ($outputmode) return $outarray; return $output; - } + } - /** - * Show a confirmation HTML form or AJAX popup - * - * @param string $page Url of page to call if confirmation is OK - * @param string $title Title - * @param string $question Question - * @param string $action Action - * @param array $formquestion An array with forms complementary inputs - * @param string $selectedchoice "" or "no" or "yes" - * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx - * @param int $height Force height of box - * @param int $width Force width of box - * @return void - * @deprecated - * @see formconfirm() - */ - function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500) - { - print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width); - } + /** + * Show a confirmation HTML form or AJAX popup + * + * @param string $page Url of page to call if confirmation is OK + * @param string $title Title + * @param string $question Question + * @param string $action Action + * @param array $formquestion An array with forms complementary inputs + * @param string $selectedchoice "" or "no" or "yes" + * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx + * @param int $height Force height of box + * @param int $width Force width of box + * @return void + * @deprecated + * @see formconfirm() + */ + function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500) + { + print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width); + } - /** - * Show a confirmation HTML form or AJAX popup. - * Easiest way to use this is with useajax=1. - * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters) - * just after calling this method. For example: - * print ''."\n"; - * - * @param string $page Url of page to call if confirmation is OK - * @param string $title Title - * @param string $question Question - * @param string $action Action - * @param array $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , )) - * @param string $selectedchoice "" or "no" or "yes" - * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx - * @param int $height Force height of box - * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones. - * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form - */ - function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=200, $width=500) - { - global $langs,$conf; - global $useglobalvars; + /** + * Show a confirmation HTML form or AJAX popup. + * Easiest way to use this is with useajax=1. + * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters) + * just after calling this method. For example: + * print ''."\n"; + * + * @param string $page Url of page to call if confirmation is OK + * @param string $title Title + * @param string $question Question + * @param string $action Action + * @param array $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , )) + * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', ... + * @param string $selectedchoice "" or "no" or "yes" + * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx + * @param int $height Force height of box + * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones. + * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form + */ + function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=200, $width=500) + { + global $langs,$conf; + global $useglobalvars; - $more=''; - $formconfirm=''; - $inputok=array(); - $inputko=array(); + $more=''; + $formconfirm=''; + $inputok=array(); + $inputko=array(); - // Clean parameters - $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice; - if ($conf->browser->layout == 'phone') $width='95%'; + // Clean parameters + $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice; + if ($conf->browser->layout == 'phone') $width='95%'; - if (is_array($formquestion) && ! empty($formquestion)) - { - // First add hidden fields and value - foreach ($formquestion as $key => $input) - { - if (is_array($input) && ! empty($input)) - { - if ($input['type'] == 'hidden') - { - $more.=''."\n"; - } - } - } + if (is_array($formquestion) && ! empty($formquestion)) + { + // First add hidden fields and value + foreach ($formquestion as $key => $input) + { + if (is_array($input) && ! empty($input)) + { + if ($input['type'] == 'hidden') + { + $more.=''."\n"; + } + } + } - // Now add questions - $more.=''."\n"; - $more.=''."\n"; - foreach ($formquestion as $key => $input) - { - if (is_array($input) && ! empty($input)) - { - $size=(! empty($input['size'])?' size="'.$input['size'].'"':''); + // Now add questions + $more.='
    '.(! empty($formquestion['text'])?$formquestion['text']:'').'
    '."\n"; + $more.=''."\n"; + foreach ($formquestion as $key => $input) + { + if (is_array($input) && ! empty($input)) + { + $size=(! empty($input['size'])?' size="'.$input['size'].'"':''); + $moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:''); + $morecss=(! empty($input['morecss'])?' '.$input['morecss']:''); - if ($input['type'] == 'text') - { - $more.=''."\n"; - } - else if ($input['type'] == 'password') - { - $more.=''."\n"; - } - else if ($input['type'] == 'select') - { - $more.=''."\n"; - } - else if ($input['type'] == 'checkbox') - { - $more.=''; - $more.=''; - if ($i==0) $more.=''; - else $more.=''; - $more.=''."\n"; + } + else if ($input['type'] == 'password') + { + $more.=''."\n"; + } + else if ($input['type'] == 'select') + { + $more.=''."\n"; + } + else if ($input['type'] == 'checkbox') + { + $more.=''; + $more.=''; + if ($i==0) $more.=''; + else $more.=''; + $more.=''."\n"; - } - } - } - $more.='
    '.(! empty($formquestion['text'])?$formquestion['text']:'').'
    '.$input['label'].'
    '.$input['label'].'
    '; - if (! empty($input['label'])) $more.=$input['label'].''; - $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1); - $more.='
    '.$input['label'].' '; - $more.=' $selval) - { - $more.='
    '.$input['label'].' 
    '.$input['label'].'
    '; + if (! empty($input['label'])) $more.=$input['label'].''; + $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss); + $more.='
    '.$input['label'].' '; + $more.=' $selval) + { + $more.='
    '.$input['label'].' '; @@ -3625,71 +3648,78 @@ class Form $formquestion[] = array('name'=>$input['name'].'hour'); $formquestion[] = array('name'=>$input['name'].'min'); } - else if ($input['type'] == 'other') - { - $more.='
    '; - if (! empty($input['label'])) $more.=$input['label'].''; - $more.=$input['value']; - $more.='
    '."\n"; - } + else if ($input['type'] == 'other') + { + $more.=''; + if (! empty($input['label'])) $more.=$input['label'].''; + $more.=$input['value']; + $more.=''."\n"; + } + + else if ($input['type'] == 'onecolumn') + { + $more.=''; + $more.=$input['value']; + $more.=''."\n"; + } + } + } + $more.=''."\n"; + } // JQUI method dialog is broken with jmobile, we use standard HTML. // Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx // See page product/card.php for example - if (! empty($conf->dol_use_jmobile)) $useajax=0; + if (! empty($conf->dol_use_jmobile)) $useajax=0; if (empty($conf->use_javascript_ajax)) $useajax=0; - if ($useajax) - { - $autoOpen=true; - $dialogconfirm='dialog-confirm'; - $button=''; - if (! is_numeric($useajax)) - { - $button=$useajax; - $useajax=1; - $autoOpen=false; - $dialogconfirm.='-'.$button; - } - $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes'; - $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':''); - // Add input fields into list of fields to read during submit (inputok and inputko) - if (is_array($formquestion)) - { - foreach ($formquestion as $key => $input) - { - //print "xx ".$key." rr ".is_array($input)."
    \n"; - if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']); - if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']); - } - } + if ($useajax) + { + $autoOpen=true; + $dialogconfirm='dialog-confirm'; + $button=''; + if (! is_numeric($useajax)) + { + $button=$useajax; + $useajax=1; + $autoOpen=false; + $dialogconfirm.='-'.$button; + } + $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes'; + $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':''); + // Add input fields into list of fields to read during submit (inputok and inputko) + if (is_array($formquestion)) + { + foreach ($formquestion as $key => $input) + { + //print "xx ".$key." rr ".is_array($input)."
    \n"; + if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']); + if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']); + } + } // Show JQuery confirm box. Note that global var $useglobalvars is used inside this template - $formconfirm.= ''."\n"; + $formconfirm.= ''."\n"; - $formconfirm.= "\n\n"; - $formconfirm.= ''; - $formconfirm.= "\n"; - } - else - { - $formconfirm.= "\n\n"; + $formconfirm.= "\n"; + } + else + { + $formconfirm.= "\n\n"; - $formconfirm.= '
    '."\n"; - $formconfirm.= ''."\n"; - $formconfirm.= ''."\n"; + $formconfirm.= ''."\n"; + $formconfirm.= ''."\n"; + $formconfirm.= ''."\n"; - $formconfirm.= ''."\n"; + $formconfirm.= '
    '."\n"; - // Line title - $formconfirm.= ''."\n"; + // Line title + $formconfirm.= ''."\n"; - // Line form fields - if ($more) - { - $formconfirm.=''."\n"; - } + // Line form fields + if ($more) + { + $formconfirm.=''."\n"; + } - // Line with question - $formconfirm.= ''; - $formconfirm.= ''; - $formconfirm.= ''; - $formconfirm.= ''; - $formconfirm.= ''."\n"; + // Line with question + $formconfirm.= ''; + $formconfirm.= ''; + $formconfirm.= ''; + $formconfirm.= ''; + $formconfirm.= ''."\n"; - $formconfirm.= '
    '.img_picto('','recent').' '.$title.'
    '.img_picto('','recent').' '.$title.'
    '."\n"; - $formconfirm.=$more; - $formconfirm.='
    '."\n"; + $formconfirm.=$more; + $formconfirm.='
    '.$question.''; - $formconfirm.= $this->selectyesno("confirm",$newselectedchoice); - $formconfirm.= '
    '.$question.''; + $formconfirm.= $this->selectyesno("confirm",$newselectedchoice); + $formconfirm.= '
    '."\n"; + $formconfirm.= ''."\n"; - $formconfirm.= "
    \n"; - $formconfirm.= '
    '; + $formconfirm.= "\n"; + $formconfirm.= '
    '; - $formconfirm.= "\n"; - } + $formconfirm.= "\n"; + } - return $formconfirm; - } + return $formconfirm; + } - /** - * Show a form to select a project - * - * @param int $page Page - * @param int $socid Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id) - * @param int $selected Id pre-selected project - * @param string $htmlname Name of select field - * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable) - * @param int $maxlength Max length - * @param int $forcefocus Force focus on field (works with javascript only) - * @param int $nooutput No print is done. String is returned. - * @return string Return html content - */ - function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0) - { - global $langs; + /** + * Show a form to select a project + * + * @param int $page Page + * @param int $socid Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id) + * @param int $selected Id pre-selected project + * @param string $htmlname Name of select field + * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable) + * @param int $maxlength Max length + * @param int $forcefocus Force focus on field (works with javascript only) + * @param int $nooutput No print is done. String is returned. + * @return string Return html content + */ + function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0) + { + global $langs; - require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; - $out=''; + $out=''; - $formproject=new FormProjets($this->db); + $formproject=new FormProjets($this->db); - $langs->load("project"); - if ($htmlname != "none") - { - $out.="\n"; - $out.='
    '; - $out.=''; - $out.=''; - $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1); - $out.=''; - $out.='
    '; - } - else - { - if ($selected) - { - $projet = new Project($this->db); - $projet->fetch($selected); - //print ''.$projet->title.''; - $out.=$projet->getNomUrl(0,'',1); - } - else - { - $out.=" "; - } - } + $langs->load("project"); + if ($htmlname != "none") + { + $out.="\n"; + $out.='
    '; + $out.=''; + $out.=''; + $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1); + $out.=''; + $out.='
    '; + } + else + { + if ($selected) + { + $projet = new Project($this->db); + $projet->fetch($selected); + //print ''.$projet->title.''; + $out.=$projet->getNomUrl(0,'',1); + } + else + { + $out.=" "; + } + } - if (empty($nooutput)) - { - print $out; - return ''; - } - return $out; - } + if (empty($nooutput)) + { + print $out; + return ''; + } + return $out; + } - /** - * Show a form to select payment conditions - * - * @param int $page Page - * @param string $selected Id condition pre-selectionne - * @param string $htmlname Name of select html field - * @param int $addempty Add empty entry - * @return void - */ - function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0) - { - global $langs; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - $this->select_conditions_paiements($selected,$htmlname,-1,$addempty); - print ''; - print '
    '; - } - else - { - if ($selected) - { - $this->load_cache_conditions_paiements(); - print $this->cache_conditions_paiements[$selected]['label']; - } else { - print " "; - } - } - } + /** + * Show a form to select payment conditions + * + * @param int $page Page + * @param string $selected Id condition pre-selectionne + * @param string $htmlname Name of select html field + * @param int $addempty Add empty entry + * @return void + */ + function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0) + { + global $langs; + if ($htmlname != "none") + { + print '
    '; + print ''; + print ''; + $this->select_conditions_paiements($selected,$htmlname,-1,$addempty); + print ''; + print '
    '; + } + else + { + if ($selected) + { + $this->load_cache_conditions_paiements(); + print $this->cache_conditions_paiements[$selected]['label']; + } else { + print " "; + } + } + } - /** - * Show a form to select a delivery delay - * - * @param int $page Page - * @param string $selected Id condition pre-selectionne - * @param string $htmlname Name of select html field - * @param int $addempty Ajoute entree vide - * @return void - */ - function form_availability($page, $selected='', $htmlname='availability', $addempty=0) - { - global $langs; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty); - print ''; - print '
    '; - } - else - { - if ($selected) - { - $this->load_cache_availability(); - print $this->cache_availability[$selected]['label']; - } else { - print " "; - } - } - } + /** + * Show a form to select a delivery delay + * + * @param int $page Page + * @param string $selected Id condition pre-selectionne + * @param string $htmlname Name of select html field + * @param int $addempty Ajoute entree vide + * @return void + */ + function form_availability($page, $selected='', $htmlname='availability', $addempty=0) + { + global $langs; + if ($htmlname != "none") + { + print '
    '; + print ''; + print ''; + $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty); + print ''; + print '
    '; + } + else + { + if ($selected) + { + $this->load_cache_availability(); + print $this->cache_availability[$selected]['label']; + } else { + print " "; + } + } + } - /** + /** * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...) * List found into table c_input_reason loaded by loadCacheInputReason - * - * @param string $page Page - * @param string $selected Id condition pre-selectionne - * @param string $htmlname Name of select html field - * @param int $addempty Add empty entry - * @return void - */ - function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0) - { - global $langs; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - $this->selectInputReason($selected,$htmlname,-1,$addempty); - print ''; - print '
    '; - } - else - { - if ($selected) - { - $this->loadCacheInputReason(); - foreach ($this->cache_demand_reason as $key => $val) - { - if ($val['id'] == $selected) - { - print $val['label']; - break; - } - } - } else { - print " "; - } - } - } - - /** - * Show a form + html select a date - * - * @param string $page Page - * @param string $selected Date preselected - * @param string $htmlname Html name of date input fields or 'none' - * @param int $displayhour Display hour selector - * @param int $displaymin Display minutes selector - * @param int $nooutput 1=No print output, return string - * @return string - * @see select_date - */ - function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0) - { - global $langs; - - $ret=''; - - if ($htmlname != "none") - { - $ret.='
    '; - $ret.=''; - $ret.=''; - $ret.=''; - $ret.=''; - $ret.=''; - $ret.='
    '; - $ret.=$this->select_date($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0,1); - $ret.='
    '; - } - else - { - if ($displayhour) $ret.=dol_print_date($selected,'dayhour'); - else $ret.=dol_print_date($selected,'day'); - } - - if (empty($nooutput)) print $ret; - return $ret; - } - - - /** - * Show a select form to choose a user - * - * @param string $page Page - * @param string $selected Id of user preselected - * @param string $htmlname Name of input html field. If 'none', we just output the user link. - * @param array $exclude List of users id to exclude - * @param array $include List of users id to include - * @return void - */ - function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='') - { - global $langs; - - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include); - print ''; - print '
    '; - } - else + * + * @param string $page Page + * @param string $selected Id condition pre-selectionne + * @param string $htmlname Name of select html field + * @param int $addempty Add empty entry + * @return void + */ + function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0) + { + global $langs; + if ($htmlname != "none") { - if ($selected) - { - require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php'; - $theuser=new User($this->db); - $theuser->fetch($selected); - print $theuser->getNomUrl(1); - } else { - print " "; - } - } - } - - - /** - * Show form with payment mode - * - * @param string $page Page - * @param int $selected Id mode pre-selectionne - * @param string $htmlname Name of select html field - * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz)) - * @param int $active Active or not, -1 = all - * @return void - */ - function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1) - { - global $langs; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active); - print ''; - print '
    '; - } - else - { - if ($selected) - { - $this->load_cache_types_paiements(); - print $this->cache_types_paiements[$selected]['label']; - } else { - print " "; - } - } - } + print '
    '; + print ''; + print ''; + $this->selectInputReason($selected,$htmlname,-1,$addempty); + print ''; + print '
    '; + } + else + { + if ($selected) + { + $this->loadCacheInputReason(); + foreach ($this->cache_demand_reason as $key => $val) + { + if ($val['id'] == $selected) + { + print $val['label']; + break; + } + } + } else { + print " "; + } + } + } /** - * Show form with multicurrency code - * - * @param string $page Page - * @param string $selected code pre-selectionne - * @param string $htmlname Name of select html field - * @return void - */ - function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code') - { - global $langs; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - print $this->selectMultiCurrency($selected, $htmlname, 0); - print ''; - print '
    '; - } - else - { - dol_include_once('/core/lib/company.lib.php'); - print !empty($selected) ? currency_name($selected,1) : ' '; - } - } + * Show a form + html select a date + * + * @param string $page Page + * @param string $selected Date preselected + * @param string $htmlname Html name of date input fields or 'none' + * @param int $displayhour Display hour selector + * @param int $displaymin Display minutes selector + * @param int $nooutput 1=No print output, return string + * @return string + * @see select_date + */ + function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0) + { + global $langs; + + $ret=''; + + if ($htmlname != "none") + { + $ret.='
    '; + $ret.=''; + $ret.=''; + $ret.=''; + $ret.=''; + $ret.=''; + $ret.='
    '; + $ret.=$this->select_date($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0,1); + $ret.='
    '; + } + else + { + if ($displayhour) $ret.=dol_print_date($selected,'dayhour'); + else $ret.=dol_print_date($selected,'day'); + } + + if (empty($nooutput)) print $ret; + return $ret; + } + /** - * Show form with multicurrency rate - * - * @param string $page Page - * @param double $rate Current rate - * @param string $htmlname Name of select html field - * @param string $currency Currency code to explain the rate - * @return void - */ - function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='') - { - global $langs, $mysoc, $conf; + * Show a select form to choose a user + * + * @param string $page Page + * @param string $selected Id of user preselected + * @param string $htmlname Name of input html field. If 'none', we just output the user link. + * @param array $exclude List of users id to exclude + * @param array $include List of users id to include + * @return void + */ + function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='') + { + global $langs; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - print ' '; + if ($htmlname != "none") + { + print ''; + print ''; + print ''; + print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include); + print ''; + print '
    '; + } + else + { + if ($selected) + { + require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php'; + $theuser=new User($this->db); + $theuser->fetch($selected); + print $theuser->getNomUrl(1); + } else { + print " "; + } + } + } + + + /** + * Show form with payment mode + * + * @param string $page Page + * @param int $selected Id mode pre-selectionne + * @param string $htmlname Name of select html field + * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz)) + * @param int $active Active or not, -1 = all + * @return void + */ + function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1) + { + global $langs; + if ($htmlname != "none") + { + print '
    '; + print ''; + print ''; + $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active); + print ''; + print '
    '; + } + else + { + if ($selected) + { + $this->load_cache_types_paiements(); + print $this->cache_types_paiements[$selected]['label']; + } else { + print " "; + } + } + } + + /** + * Show form with multicurrency code + * + * @param string $page Page + * @param string $selected code pre-selectionne + * @param string $htmlname Name of select html field + * @return void + */ + function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code') + { + global $langs; + if ($htmlname != "none") + { + print '
    '; + print ''; + print ''; + print $this->selectMultiCurrency($selected, $htmlname, 0); + print ''; + print '
    '; + } + else + { + dol_include_once('/core/lib/company.lib.php'); + print !empty($selected) ? currency_name($selected,1) : ' '; + } + } + + /** + * Show form with multicurrency rate + * + * @param string $page Page + * @param double $rate Current rate + * @param string $htmlname Name of select html field + * @param string $currency Currency code to explain the rate + * @return void + */ + function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='') + { + global $langs, $mysoc, $conf; + + if ($htmlname != "none") + { + print '
    '; + print ''; + print ''; + print ' '; print ' '; - print ''; - print '
    '; - } - else - { - if (! empty($rate)) - { - print price($rate, 1, $langs, 1, 0); - if ($currency && $rate != 1) print '   ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')'; - } - else - { - print 1; - } - } - } + print ''; + print ''; + } + else + { + if (! empty($rate)) + { + print price($rate, 1, $langs, 1, 0); + if ($currency && $rate != 1) print '   ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')'; + } + else + { + print 1; + } + } + } - /** - * Show a select box with available absolute discounts - * - * @param string $page Page URL where form is shown - * @param int $selected Value pre-selected - * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'. - * @param int $socid Third party id - * @param float $amount Total amount available - * @param string $filter SQL filter on discounts - * @param int $maxvalue Max value for lines that can be selected - * @param string $more More string to add - * @param int $hidelist 1=Hide list - * @return void - */ - function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0) - { - global $conf,$langs; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - print '
    '; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) // Never use this option. - { - if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); - } - else - { - if (! $filter) - { - print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); - } - elseif ($filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%'))") - { - // Replace trans key with CompanyHasDownPaymentOrCommercialDiscount - print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); - } - else - { - print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); - } - } - if (empty($hidelist)) print ': '; - print '
    '; - if (empty($hidelist)) - { - print '
    '; - $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles - if ($filter) $newfilter.=' AND ('.$filter.')'; - $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue); - if ($nbqualifiedlines > 0) - { - print '   '; - } - print '
    '; - } - if ($more) - { - print '
    '; - print $more; - print '
    '; - } - print '
    '; - } - else - { - if ($selected) - { - print $selected; - } - else - { - print "0"; - } - } - } + /** + * Show a select box with available absolute discounts + * + * @param string $page Page URL where form is shown + * @param int $selected Value pre-selected + * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'. + * @param int $socid Third party id + * @param float $amount Total amount available + * @param string $filter SQL filter on discounts + * @param int $maxvalue Max value for lines that can be selected + * @param string $more More string to add + * @param int $hidelist 1=Hide list + * @return void + */ + function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0) + { + global $conf,$langs; + if ($htmlname != "none") + { + print '
    '; + print ''; + print ''; + print '
    '; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + { + if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + else + { + if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%'))") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + if (empty($hidelist)) print ': '; + print '
    '; + if (empty($hidelist)) + { + print '
    '; + $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles + if ($filter) $newfilter.=' AND ('.$filter.')'; + $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue); + if ($nbqualifiedlines > 0) + { + print '   '; + } + print '
    '; + } + if ($more) + { + print '
    '; + print $more; + print '
    '; + } + print '
    '; + } + else + { + if ($selected) + { + print $selected; + } + else + { + print "0"; + } + } + } - /** - * Show forms to select a contact - * - * @param string $page Page - * @param Societe $societe Filter on third party - * @param int $selected Id contact pre-selectionne - * @param string $htmlname Name of HTML select. If 'none', we just show contact link. - * @return void - */ - function form_contacts($page, $societe, $selected='', $htmlname='contactid') - { - global $langs, $conf; + /** + * Show forms to select a contact + * + * @param string $page Page + * @param Societe $societe Filter on third party + * @param int $selected Id contact pre-selectionne + * @param string $htmlname Name of HTML select. If 'none', we just show contact link. + * @return void + */ + function form_contacts($page, $societe, $selected='', $htmlname='contactid') + { + global $langs, $conf; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
    '; - $num=$this->select_contacts($societe->id, $selected, $htmlname); - if ($num==0) - { - $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); - print ''.$addcontact.''; - } - print '
    '; - } - else - { - if ($selected) - { - require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; - $contact=new Contact($this->db); - $contact->fetch($selected); - print $contact->getFullName($langs); - } else { - print " "; - } - } - } + if ($htmlname != "none") + { + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; + $num=$this->select_contacts($societe->id, $selected, $htmlname); + if ($num==0) + { + $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); + print ''.$addcontact.''; + } + print '
    '; + } + else + { + if ($selected) + { + require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; + $contact=new Contact($this->db); + $contact->fetch($selected); + print $contact->getFullName($langs); + } else { + print " "; + } + } + } - /** - * Output html select to select thirdparty - * - * @param string $page Page - * @param string $selected Id preselected - * @param string $htmlname Name of HTML select - * @param string $filter optional filters criteras - * @param int $showempty Add an empty field - * @param int $showtype Show third party type in combolist (customer, prospect or supplier) - * @param int $forcecombo Force to use combo box - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @return void - */ - function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array()) - { - global $langs; + /** + * Output html select to select thirdparty + * + * @param string $page Page + * @param string $selected Id preselected + * @param string $htmlname Name of HTML select + * @param string $filter optional filters criteras + * @param int $showempty Add an empty field + * @param int $showtype Show third party type in combolist (customer, prospect or supplier) + * @param int $forcecombo Force to use combo box + * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @return void + */ + function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array()) + { + global $langs; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - print $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events); - print ''; - print '
    '; - } - else - { - if ($selected) - { - require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; - $soc = new Societe($this->db); - $soc->fetch($selected); - print $soc->getNomUrl($langs); - } - else - { - print " "; - } - } - } + if ($htmlname != "none") + { + print '
    '; + print ''; + print ''; + print $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events); + print ''; + print '
    '; + } + else + { + if ($selected) + { + require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; + $soc = new Societe($this->db); + $soc->fetch($selected); + print $soc->getNomUrl($langs); + } + else + { + print " "; + } + } + } - /** - * Retourne la liste des devises, dans la langue de l'utilisateur - * - * @param string $selected preselected currency code - * @param string $htmlname name of HTML select list - * @return void - */ - function select_currency($selected='',$htmlname='currency_id') - { - print $this->selectCurrency($selected,$htmlname); - } + /** + * Retourne la liste des devises, dans la langue de l'utilisateur + * + * @param string $selected preselected currency code + * @param string $htmlname name of HTML select list + * @return void + */ + function select_currency($selected='',$htmlname='currency_id') + { + print $this->selectCurrency($selected,$htmlname); + } - /** - * Retourne la liste des devises, dans la langue de l'utilisateur - * - * @param string $selected preselected currency code - * @param string $htmlname name of HTML select list - * @return string - */ + /** + * Retourne la liste des devises, dans la langue de l'utilisateur + * + * @param string $selected preselected currency code + * @param string $htmlname name of HTML select list + * @return string + */ function selectCurrency($selected='',$htmlname='currency_id') { global $conf,$langs,$user; @@ -4359,18 +4378,18 @@ class Form } /** - * Return array of currencies in user language + * Return array of currencies in user language * - * @param string $selected preselected currency code - * @param string $htmlname name of HTML select list - * @param integer $useempty 1=Add empty line - * @return string - */ - function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0) - { - global $db,$conf,$langs,$user; + * @param string $selected preselected currency code + * @param string $htmlname name of HTML select list + * @param integer $useempty 1=Add empty line + * @return string + */ + function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0) + { + global $db,$conf,$langs,$user; - $langs->loadCacheCurrencies(''); // Load ->cache_currencies + $langs->loadCacheCurrencies(''); // Load ->cache_currencies $TCurrency = array(); @@ -4383,501 +4402,567 @@ class Form } $out=''; - $out.= ''; if ($useempty) $out .= ''; // If company current currency not in table, we add it into list. Should always be available. if (! in_array($conf->currency, $TCurrency)) { - $TCurrency[$conf->currency] = $conf->currency; + $TCurrency[$conf->currency] = $conf->currency; } if (count($TCurrency) > 0) { foreach ($langs->cache_currencies as $code_iso => $currency) - { - if (isset($TCurrency[$code_iso])) + { + if (isset($TCurrency[$code_iso])) { if (!empty($selected) && $selected == $code_iso) $out.= ''; + $out.= $currency['label']; + $out.= ' ('.$langs->getCurrencySymbol($code_iso).')'; + $out.= ''; } - } + } } - $out.= ''; + $out.= ''; // Make select dynamic include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; $out.= ajax_combobox($htmlname); - return $out; - } + return $out; + } - /** - * Load into the cache vat rates of a country - * - * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'") - * @return int Nb of loaded lines, 0 if already loaded, <0 if KO - */ - function load_cache_vatrates($country_code) - { - global $langs; + /** + * Load into the cache vat rates of a country + * + * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'") + * @return int Nb of loaded lines, 0 if already loaded, <0 if KO + */ + function load_cache_vatrates($country_code) + { + global $langs; - $num = count($this->cache_vatrates); - if ($num > 0) return $num; // Cache already loaded + $num = count($this->cache_vatrates); + if ($num > 0) return $num; // Cache already loaded - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); - $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE t.fk_pays = c.rowid"; - $sql.= " AND t.active > 0"; - $sql.= " AND c.code IN (".$country_code.")"; - $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC"; + $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql.= " WHERE t.fk_pays = c.rowid"; + $sql.= " AND t.active > 0"; + $sql.= " AND c.code IN (".$country_code.")"; + $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC"; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - for ($i = 0; $i < $num; $i++) - { - $obj = $this->db->fetch_object($resql); - $this->cache_vatrates[$i]['rowid'] = $obj->rowid; - $this->cache_vatrates[$i]['code'] = $obj->code; - $this->cache_vatrates[$i]['txtva'] = $obj->taux; - $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly; - $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1; - $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type; - $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2; - $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type; + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num) + { + for ($i = 0; $i < $num; $i++) + { + $obj = $this->db->fetch_object($resql); + $this->cache_vatrates[$i]['rowid'] = $obj->rowid; + $this->cache_vatrates[$i]['code'] = $obj->code; + $this->cache_vatrates[$i]['txtva'] = $obj->taux; + $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly; + $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1; + $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type; + $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2; + $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type; - $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or * - $this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label - $positiverates=''; - if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux; - if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1; - if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2; - if (empty($positiverates)) $positiverates='0'; - $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label - } + $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or * + $this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label + $positiverates=''; + if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux; + if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1; + if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2; + if (empty($positiverates)) $positiverates='0'; + $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label + } - return $num; - } - else - { - $this->error = ''.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).''; - return -1; - } - } - else - { - $this->error = ''.$this->db->error().''; - return -2; - } - } + return $num; + } + else + { + $this->error = ''.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).''; + return -1; + } + } + else + { + $this->error = ''.$this->db->error().''; + return -2; + } + } - /** - * Output an HTML select vat rate. - * The name of this function should be selectVat. We keep bad name for compatibility purpose. - * - * @param string $htmlname Name of HTML select field - * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing. - * @param Societe $societe_vendeuse Thirdparty seller - * @param Societe $societe_acheteuse Thirdparty buyer - * @param int $idprod Id product. O if unknown of NA. - * @param int $info_bits Miscellaneous information on line (1 for NPR) - * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined) - * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle. - * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle. - * Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle. + /** + * Output an HTML select vat rate. + * The name of this function should be selectVat. We keep bad name for compatibility purpose. + * + * @param string $htmlname Name of HTML select field + * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing. + * @param Societe $societe_vendeuse Thirdparty seller + * @param Societe $societe_acheteuse Thirdparty buyer + * @param int $idprod Id product. O if unknown of NA. + * @param int $info_bits Miscellaneous information on line (1 for NPR) + * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined) + * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle. + * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle. + * Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle. - * Sinon la TVA proposee par defaut=0. Fin de regle. - * @param bool $options_only Return HTML options lines only (for ajax treatment) - * @param int $mode 0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key - * @return string - */ - function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0) - { - global $langs,$conf,$mysoc; + * Sinon la TVA proposee par defaut=0. Fin de regle. + * @param bool $options_only Return HTML options lines only (for ajax treatment) + * @param int $mode 0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key + * @return string + */ + function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0) + { + global $langs,$conf,$mysoc; - $return=''; + $langs->load('errors'); - // Define defaultnpr, defaultttx and defaultcode - $defaultnpr=($info_bits & 0x01); - $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr); - $defaulttx=str_replace('*','',$selectedrate); - $defaultcode=''; - if (preg_match('/\((.*)\)/', $defaulttx, $reg)) - { - $defaultcode=$reg[1]; - $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx); - } - //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode); + $return=''; - // Check parameters - if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code) - { - if ($societe_vendeuse->id == $mysoc->id) - { - $return.= ''.$langs->trans("ErrorYourCountryIsNotDefined").'
    '; - } - else - { - $return.= ''.$langs->trans("ErrorSupplierCountryIsNotDefined").'
    '; - } - return $return; - } + // Define defaultnpr, defaultttx and defaultcode + $defaultnpr=($info_bits & 0x01); + $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr); + $defaulttx=str_replace('*','',$selectedrate); + $defaultcode=''; + if (preg_match('/\((.*)\)/', $defaulttx, $reg)) + { + $defaultcode=$reg[1]; + $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx); + } + //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode); - //var_dump($societe_acheteuse); - //print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->country_code." buyer=".$societe_acheteuse->country_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type"; - //exit; + // Check parameters + if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code) + { + if ($societe_vendeuse->id == $mysoc->id) + { + $return.= ''.$langs->trans("ErrorYourCountryIsNotDefined").''; + } + else + { + $return.= ''.$langs->trans("ErrorSupplierCountryIsNotDefined").''; + } + return $return; + } - // Define list of countries to use to search VAT rates to show - // First we defined code_country to use to find list - if (is_object($societe_vendeuse)) - { - $code_country="'".$societe_vendeuse->country_code."'"; - } - else - { - $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente - } - if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on - { - if (! $societe_vendeuse->isInEEC() && (! is_object($societe_acheteuse) || ($societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany()))) - { - // We also add the buyer - if (is_numeric($type)) - { - if ($type == 1) // We know product is a service - { - $code_country.=",'".$societe_acheteuse->country_code."'"; - } - } - else if (! $idprod) // We don't know type of product - { - $code_country.=",'".$societe_acheteuse->country_code."'"; - } - else - { - $prodstatic=new Product($this->db); - $prodstatic->fetch($idprod); - if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service - { - $code_country.=",'".$societe_acheteuse->country_code."'"; - } - } - } - } + //var_dump($societe_acheteuse); + //print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->country_code." buyer=".$societe_acheteuse->country_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type"; + //exit; - // Now we get list - $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error + // Define list of countries to use to search VAT rates to show + // First we defined code_country to use to find list + if (is_object($societe_vendeuse)) + { + $code_country="'".$societe_vendeuse->country_code."'"; + } + else + { + $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente + } + if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on + { + if (! $societe_vendeuse->isInEEC() && (! is_object($societe_acheteuse) || ($societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany()))) + { + // We also add the buyer + if (is_numeric($type)) + { + if ($type == 1) // We know product is a service + { + $code_country.=",'".$societe_acheteuse->country_code."'"; + } + } + else if (! $idprod) // We don't know type of product + { + $code_country.=",'".$societe_acheteuse->country_code."'"; + } + else + { + $prodstatic=new Product($this->db); + $prodstatic->fetch($idprod); + if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service + { + $code_country.=",'".$societe_acheteuse->country_code."'"; + } + } + } + } - if ($num > 0) - { - // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '') - if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) - { - $tmpthirdparty=new Societe($this->db); - $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); - $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); - if (empty($defaulttx)) $defaultnpr=0; - } + // Now we get list + $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error - // Si taux par defaut n'a pu etre determine, on prend dernier de la liste. - // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant - if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) - { - if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva']; - else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS); - } + if ($num > 0) + { + // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '') + if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) + { + $tmpthirdparty=new Societe($this->db); + $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); + $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); + if (empty($defaulttx)) $defaultnpr=0; + } - // Disabled if seller is not subject to VAT - $disabled=false; $title=''; - if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") - { - $title=' title="'.$langs->trans('VATIsNotUsed').'"'; - $disabled=true; - } + // Si taux par defaut n'a pu etre determine, on prend dernier de la liste. + // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant + if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) + { + if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva']; + else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS); + } - if (! $options_only) $return.= ''; - // Define key to use into select list - $key = $rate['txtva']; - $key.= $rate['nprtva'] ? '*': ''; - if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')'; - if ($mode < 0) $key = $rate['rowid']; + $selectedfound=false; + foreach ($this->cache_vatrates as $rate) + { + // Keep only 0 if seller is not subject to VAT + if ($disabled && $rate['txtva'] != 0) continue; - $return.= ''; - } + $return.= ''; + } - $this->num = $num; - return $return; - } + if (! $options_only) $return.= ''; + } + else + { + $return.= $this->error; + } + + $this->num = $num; + return $return; + } - /** - * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes. - * Fields are preselected with : - * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM') - * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location) - * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1) - * - * @param timestamp $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date (emptydate must be 0). - * @param string $prefix Prefix for fields name - * @param int $h 1=Show also hours - * @param int $m 1=Show also minutes - * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only - * @param string $form_name Not used - * @param int $d 1=Show days, month, years - * @param int $addnowlink Add a link "Now" - * @param int $nooutput Do not output html string but return it - * @param int $disabled Disable input fields - * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59 - * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field. - * @param datetime $adddateof Add a link "Date of invoice" using the following date. - * @return string|null Nothing or string if nooutput is 1 - * @see form_date - */ - function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='') - { - global $conf,$langs; + /** + * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes. + * Fields are preselected with : + * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM') + * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location) + * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1) + * + * @param timestamp $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date (emptydate must be 0). + * @param string $prefix Prefix for fields name + * @param int $h 1=Show also hours (-1 has same effect, but hour and minutes are prefilled with 23:59 if $set_time = -1) + * @param int $m 1=Show also minutes + * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only + * @param string $form_name Not used + * @param int $d 1=Show days, month, years + * @param int $addnowlink Add a link "Now" + * @param int $nooutput Do not output html string but return it + * @param int $disabled Disable input fields + * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59 + * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field. + * @param datetime $adddateof Add a link "Date of invoice" using the following date. + * @return string|null Nothing or string if nooutput is 1 + * @see form_date + */ + function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='') + { + global $conf,$langs; - $retstring=''; + $retstring=''; - if($prefix=='') $prefix='re'; - if($h == '') $h=0; - if($m == '') $m=0; - $emptydate=0; - $emptyhours=0; - if ($empty == 1) { $emptydate=1; $emptyhours=1; } - if ($empty == 2) { $emptydate=0; $emptyhours=1; } + if($prefix=='') $prefix='re'; + if($h == '') $h=0; + if($m == '') $m=0; + $emptydate=0; + $emptyhours=0; + if ($empty == 1) { $emptydate=1; $emptyhours=1; } + if ($empty == 2) { $emptydate=0; $emptyhours=1; } $orig_set_time=$set_time; - if ($set_time === '' && $emptydate == 0) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone - } + if ($set_time === '' && $emptydate == 0) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone + } - // Analysis of the pre-selection date - if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg)) - { - // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' - $syear = (! empty($reg[1])?$reg[1]:''); - $smonth = (! empty($reg[2])?$reg[2]:''); - $sday = (! empty($reg[3])?$reg[3]:''); - $shour = (! empty($reg[4])?$reg[4]:''); - $smin = (! empty($reg[5])?$reg[5]:''); - } - elseif (strval($set_time) != '' && $set_time != -1) - { - // set_time est un timestamps (0 possible) - $syear = dol_print_date($set_time, "%Y"); - $smonth = dol_print_date($set_time, "%m"); - $sday = dol_print_date($set_time, "%d"); - if ($orig_set_time != '') - { - $shour = dol_print_date($set_time, "%H"); - $smin = dol_print_date($set_time, "%M"); - } - } - else - { - // Date est '' ou vaut -1 - $syear = ''; - $smonth = ''; - $sday = ''; - $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? '' : $conf->global->MAIN_DEFAULT_DATE_HOUR; - $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? '' : $conf->global->MAIN_DEFAULT_DATE_MIN; - } - - $usecalendar='combo'; - if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) $usecalendar=empty($conf->global->MAIN_POPUP_CALENDAR)?'eldy':$conf->global->MAIN_POPUP_CALENDAR; - if ($conf->browser->phone) $usecalendar='combo'; - - if ($d) - { - // Show date with popup - if ($usecalendar != 'combo') - { - $formated_date=''; - //print "e".$set_time." t ".$conf->format_date_short; - if (strval($set_time) != '' && $set_time != -1) - { - //$formated_date=dol_print_date($set_time,$conf->format_date_short); - $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript - } - - // Calendrier popup version eldy - if ($usecalendar == "eldy") - { - // Zone de saisie manuelle de la date - $retstring.='trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript - $retstring.='>'; - - // Icone calendrier - if (! $disabled) - { - $retstring.=''; - } - else $retstring.=''; - - $retstring.=''."\n"; - $retstring.=''."\n"; - $retstring.=''."\n"; - } - else - { - print "Bad value of MAIN_POPUP_CALENDAR"; - } - } - // Show date with combo selects - else + // Analysis of the pre-selection date + if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg)) + { + // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' + $syear = (! empty($reg[1])?$reg[1]:''); + $smonth = (! empty($reg[2])?$reg[2]:''); + $sday = (! empty($reg[3])?$reg[3]:''); + $shour = (! empty($reg[4])?$reg[4]:''); + $smin = (! empty($reg[5])?$reg[5]:''); + } + elseif (strval($set_time) != '' && $set_time != -1) + { + // set_time est un timestamps (0 possible) + $syear = dol_print_date($set_time, "%Y"); + $smonth = dol_print_date($set_time, "%m"); + $sday = dol_print_date($set_time, "%d"); + if ($orig_set_time != '') { - //$retstring.='
    '; - // Day - $retstring.=''; + $shour = dol_print_date($set_time, "%H"); + $smin = dol_print_date($set_time, "%M"); + $ssec = dol_print_date($set_time, "%S"); + } + else + { + $shour = ''; + $smin = ''; + $ssec = ''; + } + } + else + { + // Date est '' ou vaut -1 + $syear = ''; + $smonth = ''; + $sday = ''; + $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR; + $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN; + $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC; + } - if ($emptydate || $set_time == -1) - { - $retstring.=''; - } + // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery' + $usecalendar='combo'; + if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) { + $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR); + } + //if (! empty($conf->browser->phone)) $usecalendar='combo'; - for ($day = 1 ; $day <= 31; $day++) - { - $retstring.=''; - } + if ($d) + { + // Show date with popup + if ($usecalendar != 'combo') + { + $formated_date=''; + //print "e".$set_time." t ".$conf->format_date_short; + if (strval($set_time) != '' && $set_time != -1) + { + //$formated_date=dol_print_date($set_time,$conf->format_date_short); + $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + } - $retstring.=""; + // Calendrier popup version eldy + if ($usecalendar == "eldy") + { + // Zone de saisie manuelle de la date + $retstring.='trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + $retstring.='>'; - $retstring.=''; - if ($emptydate || $set_time == -1) - { - $retstring.=''; - } + // Icone calendrier + if (! $disabled) + { + $retstring.=''; + } + else $retstring.=''; - // Month - for ($month = 1 ; $month <= 12 ; $month++) - { - $retstring.='"; - } - $retstring.=""; + $retstring.=''."\n"; + $retstring.=''."\n"; + $retstring.=''."\n"; + } + elseif ($usecalendar == 'jquery') + { + if (! $disabled) + { + $retstring.=""; + } - // Year - if ($emptydate || $set_time == -1) - { - $retstring.=''; - } - else - { - $retstring.=''; + // Zone de saisie manuelle de la date + $retstring.='trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + $retstring.='>'; - for ($year = $syear - 10; $year < $syear + 10 ; $year++) - { - $retstring.=''; - } - $retstring.="\n"; - } - //$retstring.='
    '; - } - } + // Icone calendrier + if (! $disabled) + { + /* Not required. Managed by option buttonImage of jquery + $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"'); + $retstring.="";*/ + } + else + { + $retstring.=''; + } - if ($d && $h) $retstring.=($h==2?'
    ':' '); + $retstring.=''."\n"; + $retstring.=''."\n"; + $retstring.=''."\n"; + } + else + { + $retstring.="Bad value of MAIN_POPUP_CALENDAR"; + } + } + // Show date with combo selects + else + { + //$retstring.='
    '; + // Day + $retstring.=''; - if ($h) - { - // Show hour - $retstring.=''; - if ($emptyhours) $retstring.=''; - for ($hour = 0; $hour < 24; $hour++) - { - if (strlen($hour) < 2) $hour = "0" . $hour; - $retstring.=''; - } - $retstring.=''; - if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":"; - } + if ($emptydate || $set_time == -1) + { + $retstring.=''; + } - if ($m) - { - // Show minutes - $retstring.=''; - if ($emptyhours) $retstring.=''; - for ($min = 0; $min < 60 ; $min++) - { - if (strlen($min) < 2) $min = "0" . $min; - $retstring.=''; - } - $retstring.=''; - } + for ($day = 1 ; $day <= 31; $day++) + { + $retstring.=''; + } - // Add a "Now" link - if ($conf->use_javascript_ajax && $addnowlink) - { - // Script which will be inserted in the onClick of the "Now" link - $reset_scripts = ""; + $retstring.=""; - // Generate the date part, depending on the use or not of the javascript calendar - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');'; - /*if ($usecalendar == "eldy") + $retstring.=''; + if ($emptydate || $set_time == -1) + { + $retstring.=''; + } + + // Month + for ($month = 1 ; $month <= 12 ; $month++) + { + $retstring.='"; + } + $retstring.=""; + + // Year + if ($emptydate || $set_time == -1) + { + $retstring.=''; + } + else + { + $retstring.=''; + + for ($year = $syear - 10; $year < $syear + 10 ; $year++) + { + $retstring.=''; + } + $retstring.="\n"; + } + //$retstring.='
    '; + } + } + + if ($d && $h) $retstring.=($h==2?'
    ':' '); + + if ($h) + { + // Show hour + $retstring.=''; + if ($emptyhours) $retstring.=''; + for ($hour = 0; $hour < 24; $hour++) + { + if (strlen($hour) < 2) $hour = "0" . $hour; + $retstring.=''; + } + $retstring.=''; + if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":"; + } + + if ($m) + { + // Show minutes + $retstring.=''; + if ($emptyhours) $retstring.=''; + for ($min = 0; $min < 60 ; $min++) + { + if (strlen($min) < 2) $min = "0" . $min; + $retstring.=''; + } + $retstring.=''; + + $retstring.=''; + } + + // Add a "Now" link + if ($conf->use_javascript_ajax && $addnowlink) + { + // Script which will be inserted in the onClick of the "Now" link + $reset_scripts = ""; + + // Generate the date part, depending on the use or not of the javascript calendar + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');'; + /*if ($usecalendar == "eldy") { $base=DOL_URL_ROOT.'/core/'; $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');'; @@ -4888,305 +4973,507 @@ class Form $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); '; $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); '; }*/ - // Update the hour part - if ($h) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); '; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');'; - if ($fullday) $reset_scripts .= ' } '; - } - // Update the minute part - if ($m) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); '; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');'; - if ($fullday) $reset_scripts .= ' } '; - } - // If reset_scripts is not empty, print the link with the reset_scripts in the onClick - if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) - { - $retstring.=' '; - } - } + // Update the hour part + if ($h) + { + if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); '; + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');'; + if ($fullday) $reset_scripts .= ' } '; + } + // Update the minute part + if ($m) + { + if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); '; + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');'; + if ($fullday) $reset_scripts .= ' } '; + } + // If reset_scripts is not empty, print the link with the reset_scripts in the onClick + if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) + { + $retstring.=' '; + } + } - // Add a "Plus one hour" link - if ($conf->use_javascript_ajax && $addplusone) - { - // Script which will be inserted in the onClick of the "Add plusone" link - $reset_scripts = ""; + // Add a "Plus one hour" link + if ($conf->use_javascript_ajax && $addplusone) + { + // Script which will be inserted in the onClick of the "Add plusone" link + $reset_scripts = ""; - // Generate the date part, depending on the use or not of the javascript calendar - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');'; - // Update the hour part - if ($h) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');'; - if ($fullday) $reset_scripts .= ' } '; - } - // Update the minute part - if ($m) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');'; - if ($fullday) $reset_scripts .= ' } '; - } - // If reset_scripts is not empty, print the link with the reset_scripts in the onClick - if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) - { - $retstring.=' '; - } - } + // Generate the date part, depending on the use or not of the javascript calendar + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');'; + // Update the hour part + if ($h) + { + if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');'; + if ($fullday) $reset_scripts .= ' } '; + } + // Update the minute part + if ($m) + { + if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');'; + if ($fullday) $reset_scripts .= ' } '; + } + // If reset_scripts is not empty, print the link with the reset_scripts in the onClick + if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) + { + $retstring.=' '; + } + } - // Add a "Plus one hour" link - if ($conf->use_javascript_ajax && $adddateof) - { - $tmparray=dol_getdate($adddateof); - $retstring.=' - + jsGanttImproved + + + + + + +
    +
    +
    +

    jsGanttImproved

    +

    latest v1.7.5.4

    + Download + View on GitHub +
    +
    +
    +
    + +

    +

    100% HTML + CSS + JavaScript Gantt Chart

    +
    + +

    +

    Completely FREE

    +
    + +

    +

    Open source

    +
    +
    + +
    +
    +
    +
    +
    + +
    +
    +
    + +
    +

    Demo

    +
    + + +
    +
    + +
    +
    + +
    +
    + +
    +

    Features

    +

    jsGanttImproved is a fully featured gantt chart component built entirely in Javascript, CSS and AJAX. It is lightweight and there is no need of external libraries or additional images.

    +
    +
    +

    Basic Features

    +
      +
    • Tasks & Collapsible Task Groups
    • +
    • Multiple Dependencies
    • +
    • Task Completion
    • +
    • Task Style
    • +
    • Milestones
    • +
    • Resources
    • +
    +
    +
    +

    Advanced Features

    +
      +
    • Dynamic Loading of Tasks
    • +
    • Dynamic change of format: Hour, Day, Week, Month, Quarter
    • +
    • + Load Gantt from: +
        +
      • External XML files (including experimental support for Microsoft Project XML files)
      • +
      • JavaScript strings
      • +
      +
    • +
    • Export Gantt as XML string
    • +
    • Support for internationalization
    • +
    +
    +
    +

    Current Known Issues:

    +
      +
    • If the browser is viewing the page at anything other than 100% zoom then bars may not be sized or positioned correctly.
    • +
    +

    Changelog:

    +

    Check the full list of changes on GitHub releases page.

    +

    v1.7.5.4:

    +
      +
    • Left part of the chart is now created first on JavaScript and establishes the left floating reference
    • +
    • Minimum width updated to 632px so that the left part of the chart has a fixed width of 532px and the right part fills out the rest with a minimum of 100px
    • +
    +

    v1.7.5.3:

    +
      +
    • Fixed group completion percentage that now is a weighted average
    • +
    • Start and end dates specified on standard group tasks will now be respected if they fall outside of the calculated group date range
    • +
    • Fixed problem that would occur if Tool Tips were disabled
    • +
    • Moved example dates forward so the current date marker is visible
    • +
    +

    v1.7.5:

    +
      +
    • Project Migrated to GitHub
    • +
    • Instantiating a new JSGantt.TaskItem will now also accept Date objects for start and end dates
    • +
    • Fixed old Internet Explorer compatibilty broken by v1.7
    • +
    • Fixed bug in Iso week date format
    • +
    • Changed to solid arrows on dependency lines to be more printer friendly
    • +
    • Code refactoring and clean up
    • +
    +

    v1.7:

    +
      +
    • + Fixed nasty long-standing bug where the first Gantt chart created must be stored in a javascript variable named "g" +
        +
      • NOTE: This required a change in the method to instatiate a JSGantt.TaskItem object to pass the related chart.
      • +
      • A temporary fix is included that still assumes the use of "g" for the chart if the chart object is not passed, this will be removed in v1.8
      • +
      +
    • +
    • Altered XML export functionality so that dates are output in the specified input format for the chart
    • +
    • Added method to read XML directly from an input string
    • +
    • Prevented creation of a task with a duplicate "unique" ID
    • +
    • Fixed bug where attempting to remove the first task defined would prevent the chart from redrawing
    • +
    • Some general code clean up
    • +
    +
    + +
    +

    Usage

    +

    Following the steps below you will be able to get create a basic Gantt Chart. If you notice any bugs, please post them to GitHub issues.

    +
      +
    1. + Include JSGantt CSS and Javascript +
      <link rel="stylesheet" type="text/css" href="jsgantt.css" />
      +<script language="javascript" src="jsgantt.js"></script>
      +
    2. +
    3. + Create a div element to hold the gantt chart +
      <div style="position:relative" class="gantt" id="GanttChartDIV"></div>
      +
    4. +
    5. + Start a <script> block +
      <script type="text/javascript">
      +
    6. +
    7. + Instantiate JSGantt using GanttChart() +
      var g = new JSGantt.GanttChart(document.getElementById('GanttChartDIV'), 'day');
      +

      Method definition: + GanttChart(pDiv, pFormat) +

      +

      + + + + + + + + +
      pDiv:(required) this is a DIV object created in HTML
      pFormat:(required) - used to indicate whether chart should be drawn in "hour", "day", "week", "month", or "quarter" format

      +
    8. +
    9. +

      Customize the look and feel using configuration methods (see Configuration Options)

      +
    10. +
    11. + Add Tasks +
        +
      • + using AddTaskItem() +
        g.AddTaskItem(new JSGantt.TaskItem(1, 'Define Chart API','',          '',          'ggroupblack','', 0, 'Brian', 0,  1,0,1,'','','Some Notes text',g));
        +g.AddTaskItem(new JSGantt.TaskItem(11,'Chart Object',    '2016-02-20','2016-02-20','gmilestone', '', 1, 'Shlomy',100,0,1,1,'','','',g));
        +                
        +

        Method definition: + TaskItem(pID, pName, pStart, pEnd, pColor, pLink, pMile, pRes, pComp, pGroup, pParent, pOpen, pDepend, pCaption, pNotes, pGantt) +

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        pID:(required) a unique numeric ID used to identify each row
        pName:(required) the task Label
        pStart:(required) the task start date, can enter empty date ('') for groups. You can also enter specific time (2016-02-20 12:00) for additional precision.
        pEnd:(required) the task end date, can enter empty date ('') for groups
        pClass:(required) the css class for this task
        pLink:(optional) any http link to be displayed in tool tip as the "More information" link.
        pMile:(optional) indicates whether this is a milestone task - Numeric; 1 = milestone, 0 = not milestone
        pRes:(optional) resource name
        pComp:(required) completion percent, numeric
        pGroup:(optional) indicates whether this is a group task (parent) - Numeric; 0 = normal task, 1 = standard group task, 2 = combined group task*
        pParent:(required) identifies a parent pID, this causes this task to be a child of identified task. Numeric, top level tasks should have pParent set to 0
        pOpen:(required) indicates whether a standard group task is open when chart is first drawn. Value must be set for all items but is only used by standard group tasks. Numeric, 1 = open, 0 = closed
        pDepend: + (optional) comma separated list of id's this task is dependent on. A line will be drawn from each listed task to this item
        Each id can optionally be followed by a dependency type suffix. Valid values are: +
        'FS' - Finish to Start (default if suffix is omitted)
        'SF' - Start to Finish
        'SS' - Start to Start
        'FF' - Finish to Finish
        + If present the suffix must be added directly to the id e.g. '123SS' +
        pCaption:(optional) caption that will be added after task bar if CaptionType set to "Caption"
        pNotes:(optional) Detailed task information that will be displayed in tool tip for this task
        pGantt:(required) javascript JSGantt.GanttChart object from which to take settings. Defaults to "g" for backwards compatibility
        +

        * Combined group tasks show all sub-tasks on one row. The information displayed in the task list and row caption are taken from the parent task. Tool tips are generated individually for each sub-task from its own information. Milestones are not valid as sub-tasks of a combined group task and will not be displayed. No bounds checking of start and end dates of sub-tasks is performed therefore it is possible for these task bars to overlap. Dependencies can be set to and from sub-tasks only.

        +
      • +
      • + using parseXML() with an external XML file +
        JSGantt.parseXML("project.xml",g);
        +

        Method definition: + JSGantt.parseXML(pFile, pGanttObj) +

        + + + + + + + + + +
        pFile:(required) this is the filename of the XML
        pGanttObj:(required) a GanttChart object returned by a call to JSGantt.GanttChart()
        +

        The structure of the native XML file:

        +
        <project>
        +  <task>
        +    <pID>25</pID>
        +    <pName>WCF Changes</pName>
        +    <pStart></pStart>
        +    <pEnd></pEnd>
        +    <pClass>gtaskred</pClass>
        +    <pLink></pLink>
        +    <pMile>0</pMile>
        +    <pRes></pRes>
        +    <pComp>0</pComp>
        +    <pGroup>1</pGroup>
        +    <pParent>2</pParent>
        +    <pOpen>1</pOpen>
        +    <pDepend>2,24</pDepend>
        +    <pCaption>A caption</pCaption>
        +    <pNotes>Text - can include limited HTML</pNotes>
        +  </task>
        +</project>
        +

        Field definitions are as described for the parameters to TaskItem above. The pClass element is optional in XML files and will default to "ggroupblack" for group tasks, "gtaskblue" for normal tasks and "gmilestone" for milestones. The pGantt element is not required for XML import.

        +

        JSGannt Improved will also test the provided XML file to see if it appears to be in Microsoft Project XML format. If so an attempt will be made to load up the project. This feature is experimental, the import is best effort and not guaranteed. Once loaded the project as interpreted by JSGantt Improved can be extracted using the XML Export methods provided.

        +
      • +
      • + using parseXMLString() with XML held in a javascript string object +
        JSGantt.parseXMLString("<project><task>...</task></project>",g);
        +

        Method definition: + JSGantt.parseXMLString(pStr, pGanttObj) +

        + + + + + + + + + +
        pStr:(required) this is a javascript String containing XML
        pGanttObj:(required) a GanttChart object returned by a call to JSGantt.GanttChart()
        +

        The XML provided will be parsed in exactly the same way as the contents of an external XML file and hence must match the format as described for JSGantt.parseXML() above

        +
      • +
      +
    12. +
    13. +

      Call Draw()

      +
      g.Draw();
      +
    14. +
    15. +

      Close the <script> block

      +
      </script>
      +
    16. +
    +

    It is possible to add items to the chart in realtime via javascript using either direct method calls or additional XML files. + It is also possible to delete tasks using RemoveTaskItem() method. +

    +
    g.RemoveTaskItem(11);
    +

    Method definition: + RemoveTaskItem(pID) +

    + + + + + +
    pID:(required) the unique numeric ID of the item to be removed
    +

    If the task removed is a group item, all child tasks will also be removed.

    +

    After adding or removing tasks a call to "g.Draw()" must be made to redraw the chart.

    +

    Configuration Options

    +

    Switches

    +

    Many of the features of jsGanttImproved can be customised through the use of setter methods available on the GanttChart object returned by a call to JSGantt.GanttChart()

    +

    The following options take a single numeric parameter; a value of 1 will enable the describe functionality, 0 will disable it

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    setUseToolTip():Controls the display of tool tip boxes, defaults to 1 (enabled)
    setUseFade():Controls use of the fade effect when showing/hiding tool tips, defaults to 1 (enabled)
    setUseMove():Controls use of the sliding effect when changing between different task tool tips, defaults to 1 (enabled)
    setUseRowHlt():Controls the use of row mouseover highlighting, defaults to 1 (enabled)
    setUseSort():Controls whether the task list is sorted into parent task / start time order or is simply displayed in the order created, defaults to 1 (sort enabled)
    setShowRes():Controls whether the Resource column is displayed in the task list, defaults to 1 (show column)
    setShowDur():Controls whether the Task Duration column is displayed in the task list, defaults to 1 (show column)
    setShowComp():Controls whether the Percentage Complete column is displayed in the task list, defaults to 1 (show column)
    setShowStartDate():Controls whether the Task Start Date column is displayed in the task list, defaults to 1 (show column)
    setShowEndDate():Controls whether the Task End Date column is displayed in the task list, defaults to 1 (show column)
    setShowTaskInfoRes():Controls whether the Resource information is displayed in the task tool tip, defaults to 1 (show information)
    setShowTaskInfoDur():Controls whether the Task Duration information is displayed in the task tool tip, defaults to 1 (show information)
    setShowTaskInfoComp():Controls whether the Percentage Complete information is displayed in the task tool tip, defaults to 1 (show information)
    setShowTaskInfoStartDate():Controls whether the Task Start Date information is displayed in the task tool tip, defaults to 1 (show information)
    setShowTaskInfoEndDate():Controls whether the Task End Date information is displayed in the task tool tip, defaults to 1 (show information)
    setShowTaskInfoLink():Controls whether the More Information link is displayed in the task tool tip, defaults to 0 (do NOT show link)
    setShowTaskInfoNotes():Controls whether the Additional Notes data is displayed in the task tool tip, defaults to 1 (show notes)
    setShowEndWeekDate():Controls whether the major heading in "Day" view displays the week end-date in the appropriate format (see below), defaults to 1 (show date)
    setShowDeps():Controls display of dependancy lines, defaults to 1 (show dependencies)
    +

    Key Values

    +

    The following options enable functionality using a set of specific key values

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    setShowSelector():Controls where the format selector is displayed, accepts multiple parameters.
    Valid parameter values are "Top", "Bottom".
    Defaults to "Top".
    setFormatArr():Controls which format options are shown in the format selector, accepts multiple parameters.
    Valid parameter values are "Hour", "Day", "Week", "Month", "Quarter".
    Defaults to all valid values.
    setCaptionType():Controls which task field to use as a caption on the Gantt Chart task bar, accepts a single parameter.
    Valid parameter values are "None", "Caption", "Resource", "Duration", "Complete".
    Defaults to "None"
    setDateInputFormat():Defines the input format used for dates in task creation, accepts a single parameter.
    Valid parameter values are "yyyy-mm-dd", "dd/mm/yyyy", "mm/dd/yyyy".
    Defaults to "yyyy-mm-dd"
    setScrollTo():Sets the date the Gantt Chart will be scrolled to, specified in the date input format set by setDateInputFormat() above. Also accepts the special value "today"
    Defaults to minimum display date
    setUseSingleCell():Sets the threshold total number of cells at which the task list will use a single table cell for each row rather than one cell per period. Useful to improve performance on large charts. A value of 0 disables this functionality (always use multiple cells), defaults to 25000
    setLang():Sets translation to use when drawing the chart. Defaults to "en" as this is the only language provided in the base installation (see internationalization below for details on how to add more translations.)
    +

    Layout

    +

    Most of the look and feel of the Gantt Chart can be controlled using CSS however, as the length of a task bar is determined by column width, the following methods take a single numeric parameter that defines the appropriate column width in pixels.

    +

    Note that the task bar sizing code assumes the use of collapsed table borders 1px wide.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    setHourColWidth():Width of Gantt Chart columns in pixels when drawn in "Hour" format. Defaults to 18.
    setDayColWidth():Width of Gantt Chart columns in pixels when drawn in "Day" format. Defaults to 18.
    setWeekColWidth():Width of Gantt Chart columns in pixels when drawn in "Week" format. Defaults to 36.
    setMonthColWidth():Width of Gantt Chart columns in pixels when drawn in "Month" format. Defaults to 36.
    setQuarterColWidth():Width of Gantt Chart columns in pixels when drawn in "Quarter" format, although not mandatory it is recommended that this be set to a value divisible by 3. Defaults to 18.
    setRowHeight():Height of Gantt Chart rows in pixels. Used to route dependency lines near end points. Defaults to 20.
    setMinGpLen():Group tasks have their task bars embellished with end points, this value specifies the width of one of these end points in pixels. A short task bar's length will be rounded up to display either a single or both endpoints correctly. Defaults to 8.
    +

    Display Date Formats

    +

    Date display formats can be individually controlled. The methods used to set these display formats each take a single format string parameter. The format string can be made up of the following components (case sensitive)

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    h:Hour (1-12)
    hh:Hour (01-12)
    pm:am/pm indicator
    PM:AM/PM indicator
    H:Hour (0-23)
    HH:Hour (01-23)
    mi:Minutes (1-59)
    MI:Minutes (01-59)
    d:Day (1-31)
    dd:Day (01-31)
    day:Abbreviated day of week
    DAY:Day of week
    m:Month (1-12)
    mm:Month (01-12)
    mon:Abbreviated month text
    month:Full month text
    yy:Year, excluding century
    yyyy:Year
    q:Quarter (1-4)
    qq:Quarter (Q1-Q4)
    w:ISO Week number (1-53)
    ww:ISO Week number (01-53)
    week:Full ISO Week date format
    +

    separated by one of the following characters: "/\-.,'<space>:

    +

    Any text between separators that does not match one of the components above will be checked using a case insensitive match for a valid internationalized string (see internationalization below). If the value is still not found the text will be output unchanged.

    +
    +

    The available date display methods are

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    setDateTaskTableDisplayFormat():Date format used for start and end dates in the main task list. Defaults to 'dd/mm/yyyy'.
    setDateTaskDisplayFormat():Date format used for start and end dates in task tool tips. Defaults to 'dd month yyyy'.
    setHourMajorDateDisplayFormat():Date format used for Gantt Chart major date headings displayed in "Hour" format. Defaults to 'day dd month yyyy'.
    setDayMajorDateDisplayFormat():Date format used for Gantt Chart major date headings displayed in "Day" format. Defaults to 'dd/mm/yyyy'.
    setWeekMajorDateDisplayFormat():Date format used for Gantt Chart major date headings displayed in "Week" format. Defaults to 'yyyy'.
    setMonthMajorDateDisplayFormat():Date format used for Gantt Chart major date headings displayed in "Month" format. Defaults to 'yyyy'.
    setQuarterMajorDateDisplayFormat():Date format used for Gantt Chart major date headings displayed in "Year" format. Defaults to 'yyyy'.
    setHourMinorDateDisplayFormat():Date format used for Gantt Chart minor date headings displayed in "Hour" format. Defaults to 'HH'.
    setDayMinorDateDisplayFormat():Date format used for Gantt Chart minor date headings displayed in "Day" format. Defaults to 'dd'.
    setWeekMinjorDateDisplayFormat():Date format used for Gantt Chart minor date headings displayed in "Week" format. Defaults to 'dd/mm'.
    setMonthMinorDateDisplayFormat():Date format used for Gantt Chart minor date headings displayed in "Month" format. Defaults to 'mon'.
    setQuarterMinorDateDisplayFormat():Date format used for Gantt Chart minor date headings displayed in "Year" format. Defaults to 'qq'.
    +

    Internationalization

    +

    jsGanttImproved only provides English text however all hard coded strings can be replaced by calling the addLang() method available on the GanttChart object returned by a call to JSGantt.GanttChart()

    +

    The addLang() method takes two parameters. The first is a string identifier for the language, the second is a javascript object containing all the replacement text pairs, the default English settings are:

    +
    + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    january:January
    february:February
    march:March
    april:April
    maylong:May
    june:June
    july:July
    august:August
    september:September
    october:October
    november:November
    december:December
    jan:Jan
    feb:Feb
    mar:Mar
    apr:Apr
    may:May
    jun:Jun
    jul:Jul
    aug:Aug
    sep:Sep
    oct:Oct
    nov:Nov
    dec:Dec
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    sunday:Sunday
    monday:Monday
    tuesday:Tuesday
    wednesday:Wednesday
    thursday:Thursday
    friday:Friday
    saturday:Saturday
    sun:Sun
    mon:Mon
    tue:Tue
    wed:Wed
    thu:Thu
    fri:Fri
    sat:Sat
    resource:Resource
    duration:Duration
    comp:% Comp.
    completion:Completion
    startdate:Start Date
    enddate:End Date
    moreinfo:More Information
    notes:Notes
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    format:Format
    hour:Hour
    day:Day
    week:Week
    month:Month
    quarter:Quarter
    hours:Hours
    days:Days
    weeks:Weeks
    months:Months
    quarters:Quarters
    hr:Hr
    dy:Day
    wk:Wk
    mth:Mth
    qtr:Qtr
    hrs:Hrs
    dys:Days
    wks:Wks
    mths:Mths
    qtrs:Qtrs
    +
    +
    +

    When adding a language any translations that are not provided will use the default English language value. This provides a simple way to override default strings e.g.

    +
    g.addLang('en2', {'format':'Select', 'comp':'Complete'});
    +

    would create a language called 'en2' where the text in the format selector was "Select" rather than "Format" and the header for the Percentage Complete column in the task list is "Complete" rather than "% Comp."

    +

    Once a translation has been added a call must be made to setLang() with the appropriate langage identifier before calling Draw().

    +

    Example Options

    +

    The configuration options used in the example chart above are:

    +
    g.setCaptionType('Complete');  // Set to Show Caption (None,Caption,Resource,Duration,Complete)
    +g.setQuarterColWidth(36);
    +g.setDateTaskDisplayFormat('day dd month yyyy'); // Shown in tool tip box
    +g.setDayMajorDateDisplayFormat('mon yyyy - Week ww'); // Set format to display dates in the "Major" header of the "Day" view
    +g.setWeekMinorDateDisplayFormat('dd mon'); // Set format to display dates in the "Minor" header of the "Week" view
    +g.setShowTaskInfoLink(1); //Show link in tool tip (0/1)
    +g.setShowEndWeekDate(0); // Show/Hide the date for the last day of the week in header for daily view (1/0)
    +g.setUseSingleCell(10000); // Set the threshold at which we will only use one cell per table row (0 disables).  Helps with rendering performance for large charts.
    +g.setFormatArr('Day', 'Week', 'Month', 'Quarter'); // Even with setUseSingleCell using Hour format on such a large chart can cause issues in some browsers
    +        
    +

    Putting all this information together the final code to produce the chart above is as follows:

    +
    <link rel="stylesheet" type="text/css" href="jsgantt.css" />
    +<script language="javascript" src="jsgantt.js"></script>
    +<div style="position:relative" class="gantt" id="GanttChartDIV"></div>
    +<script>
    +
    +var g = new JSGantt.GanttChart('g',document.getElementById('GanttChartDIV'), 'day');
    +
    +if( g.getDivId() != null ) {
    +g.setCaptionType('Complete');
    +g.setQuarterColWidth(36);
    +g.setDateTaskDisplayFormat('day dd month yyyy');
    +g.setDayMajorDateDisplayFormat('mon yyyy - Week ww');
    +g.setWeekMinorDateDisplayFormat('dd mon');
    +g.setShowTaskInfoLink(1);
    +g.setShowEndWeekDate(0);
    +g.setUseSingleCell(10000);
    +g.setFormatArr('Day', 'Week', 'Month', 'Quarter');
    +
    +g.AddTaskItem(new JSGantt.TaskItem(1,   'Define Chart API',     '',           '',          'ggroupblack',  '',       0, 'Brian',    0,   1, 0,  1, '',      '',      'Some Notes text', g ));
    +g.AddTaskItem(new JSGantt.TaskItem(11,  'Chart Object',         '2016-02-20','2016-02-20', 'gmilestone',   '',       1, 'Shlomy',   100, 0, 1,  1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(12,  'Task Objects',         '',           '',          'ggroupblack',  '',       0, 'Shlomy',   40,  1, 1,  1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(121, 'Constructor Proc',     '2016-02-21','2016-03-09', 'gtaskblue',    '',       0, 'Brian T.', 60,  0, 12, 1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(122, 'Task Variables',       '2016-03-06','2016-03-11', 'gtaskred',     '',       0, 'Brian',    60,  0, 12, 1, 121,     '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(123, 'Task by Minute/Hour',  '2016-03-09','2016-03-14 12:00', 'gtaskyellow', '',  0, 'Ilan',     60,  0, 12, 1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(124, 'Task Functions',       '2016-03-09','2016-03-29', 'gtaskred',     '',       0, 'Anyone',   60,  0, 12, 1, '123SS', 'This is a caption', null, g));
    +g.AddTaskItem(new JSGantt.TaskItem(2,   'Create HTML Shell',    '2016-03-24','2016-03-24', 'gtaskyellow',  '',       0, 'Brian',    20,  0, 0,  1, 122,     '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(3,   'Code Javascript',      '',           '',          'ggroupblack',  '',       0, 'Brian',    0,   1, 0,  1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(31,  'Define Variables',     '2016-02-25','2016-03-17', 'gtaskpurple',  '',       0, 'Brian',    30,  0, 3,  1, '',      'Caption 1','',   g));
    +g.AddTaskItem(new JSGantt.TaskItem(32,  'Calculate Chart Size', '2016-03-15','2016-03-24', 'gtaskgreen',   '',       0, 'Shlomy',   40,  0, 3,  1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(33,  'Draw Task Items',      '',           '',          'ggroupblack',  '',       0, 'Someone',  40,  2, 3,  1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(332, 'Task Label Table',     '2016-03-06','2016-03-09', 'gtaskblue',    '',       0, 'Brian',    60,  0, 33, 1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(333, 'Task Scrolling Grid',  '2016-03-11','2016-03-20', 'gtaskblue',    '',       0, 'Brian',    0,   0, 33, 1, '332',   '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(34,  'Draw Task Bars',       '',           '',          'ggroupblack',  '',       0, 'Anybody',  60,  1, 3,  0, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(341, 'Loop each Task',       '2016-03-26','2016-04-11', 'gtaskred',     '',       0, 'Brian',    60,  0, 34, 1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(342, 'Calculate Start/Stop', '2016-04-12','2016-05-18', 'gtaskpink',    '',       0, 'Brian',    60,  0, 34, 1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(343, 'Draw Task Div',        '2016-05-13','2016-05-17', 'gtaskred',     '',       0, 'Brian',    60,  0, 34, 1, '',      '',      '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(344, 'Draw Completion Div',  '2016-05-17','2016-06-04', 'gtaskred',     '',       0, 'Brian',    60,  0, 34, 1, "342,343",'',     '',      g));
    +g.AddTaskItem(new JSGantt.TaskItem(35,  'Make Updates',         '2016-07-17','2017-09-04', 'gtaskpurple',  '',       0, 'Brian',    30,  0, 3,  1, '333',   '',      '',      g));
    +
    +g.Draw();
    +}
    +else
    +{
    +alert("Error, unable to create Gantt Chart");
    +}
    +
    +</script>
    +

    XML Export

    +

    The following methods can be used to extract details of tasks in the project in XML format

    +

    Method definition: getXMLProject()

    +

    Returns a string containing the entire project in JSGantt Improved XML format. Dates will be exported in the currently defined input format as set by setDateInputFormat()

    +

    Method definition: getXMLTask(pID, pIdx)

    + + + + + + + + + +
    pID:(required) the numeric ID that identifies the task to extract
    pIdx:(optional) Boolean - if present and set to "true" the number passed in the pID parameter is treated as an array index for the task list rather than an ID
    +

    Returns a string containing the specified task item in JSGantt Improved XML format. Dates will be exported in the currently defined input format as set by setDateInputFormat()

    +
    + +
    +

    Credits

    +
    +
    + Eduardo Rodrigues +
    +

    Eduardo Rodrigues

    +

    Developer

    +
    + +
    +
    +
    +
    + Ricardo Cardoso +
    +

    Ricardo Cardoso

    +

    Developer

    +
    + +
    +
    +
    +
    +
    + + + + + + + diff --git a/htdocs/includes/jsgantt/jsgantt.css b/htdocs/includes/jsgantt/jsgantt.css index 78a7e83e971..f8f58017cca 100644 --- a/htdocs/includes/jsgantt/jsgantt.css +++ b/htdocs/includes/jsgantt/jsgantt.css @@ -1,5 +1,5 @@ -/* Sample CSS for jsGanttImproved v1.7.3 */ -div.gantt { font-family:tahoma, arial, verdana, Sans-serif; font-size:10px; color: #2F2F2F; } +/* Sample CSS for jsGanttImproved v1.7.5.4 */ +div.gantt { font-family:tahoma, arial, verdana, Sans-serif; font-size:10px; color: #656565; } .gantt table { border-collapse: collapse; } .gantt td { padding: 0px; } @@ -42,7 +42,7 @@ td.gspanning { border-left: none; border-right: none; } .genddate { text-align: center; min-width: 70px; max-width: 70px; width: 70px; font-size: 10px; } .gtaskheading { text-align: center; } .gtaskname div, /* needed for IE8 */ -.gtaskname { min-width: 170px; max-width: 170px; width: 170px;/* font-size: 9px;*/ border-left: none; } +.gtaskname { min-width: 170px; max-width: 170px; width: 170px; font-size: 9px; border-left: none; } .gselector { text-align: left; white-space: nowrap; min-width: 170px; max-width: 170px; width: 170px; } @@ -62,7 +62,7 @@ span.gfoldercollapse { color:#000000; cursor:pointer; font-weight:bold; font-si .glineitem { background-color: #ffffff; } /* highlight row (applied to row) */ -.gitemhighlight td { background-image: none; background-color: #fffaaa;} +.gitemhighlight td { background-image: none; background-color: #fffde5;} /* task bar caption text styles */ .gmilecaption, @@ -98,34 +98,34 @@ span.gfoldercollapse { color:#000000; cursor:pointer; font-weight:bold; font-si .ggroupblackendpointright { overflow: hidden; width:0px; height:0px; top: 2px; border-top: 4px solid black; border-left: 4px solid transparent; border-bottom: 4px solid transparent; border-right: 4px solid transparent; float: right; } .ggroupblackcomplete { float:left; overflow: hidden; height:3px; filter: alpha(opacity=80); opacity:0.8; background-color:#777777; margin-top:2px; margin-bottom: 2px; } .gtaskblue { - background: rgb(58,132,195); /* Old browsers */ - background: linear-gradient(to bottom, rgba(58,132,195,1) 0%,rgba(65,154,214,1) 20%,rgba(75,184,240,1) 40%,rgba(58,139,194,1) 70%,rgba(38,85,139,1) 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#4bb8f0', endColorstr='#3a84c3',GradientType=0 ); /* IE6-9 */ + background: rgb(58,132,195); /* Old browsers */ + background: linear-gradient(to bottom, rgba(58,132,195,1) 0%,rgba(65,154,214,1) 20%,rgba(75,184,240,1) 40%,rgba(58,139,194,1) 70%,rgba(38,85,139,1) 100%); /* W3C */ + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#4bb8f0', endColorstr='#3a84c3',GradientType=0 ); /* IE6-9 */ } .gtaskred { - background: rgb(196,58,58); /* Old browsers */ - background: linear-gradient(to bottom, rgba(196,58,58,1) 0%,rgba(211,65,65,1) 20%,rgba(239,76,76,1) 40%,rgba(196,58,58,1) 70%,rgba(135,37,37,1) 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ef4c4c', endColorstr='#c43a3a',GradientType=0 ); /* IE6-9 */ + background: rgb(196,58,58); /* Old browsers */ + background: linear-gradient(to bottom, rgba(196,58,58,1) 0%,rgba(211,65,65,1) 20%,rgba(239,76,76,1) 40%,rgba(196,58,58,1) 70%,rgba(135,37,37,1) 100%); /* W3C */ + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ef4c4c', endColorstr='#c43a3a',GradientType=0 ); /* IE6-9 */ } .gtaskgreen { - background: rgb(80,193,58); /* Old browsers */ - background: linear-gradient(to bottom, rgba(80,193,58,1) 0%,rgba(88,209,64,1) 20%,rgba(102,237,75,1) 40%,rgba(80,193,58,1) 70%,rgba(53,132,37,1) 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#66ED4B', endColorstr='#50c13a',GradientType=0 ); /* IE6-9 */ + background: rgb(80,193,58); /* Old browsers */ + background: linear-gradient(to bottom, rgba(80,193,58,1) 0%,rgba(88,209,64,1) 20%,rgba(102,237,75,1) 40%,rgba(80,193,58,1) 70%,rgba(53,132,37,1) 100%); /* W3C */ + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#66ED4B', endColorstr='#50c13a',GradientType=0 ); /* IE6-9 */ } .gtaskyellow { - background: rgb(247,228,56); /* Old browsers */ - background: linear-gradient(to bottom, rgba(247,228,56,1) 0%,rgba(239,239,55,1) 20%,rgba(255,255,58,1) 40%,rgba(242,236,55,1) 70%,rgba(241,218,54,1) 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffff3a', endColorstr='#f7e438',GradientType=0 ); /* IE6-9 */ + background: rgb(247,228,56); /* Old browsers */ + background: linear-gradient(to bottom, rgba(247,228,56,1) 0%,rgba(239,239,55,1) 20%,rgba(255,255,58,1) 40%,rgba(242,236,55,1) 70%,rgba(241,218,54,1) 100%); /* W3C */ + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffff3a', endColorstr='#f7e438',GradientType=0 ); /* IE6-9 */ } .gtaskpurple { - background: rgb(193,58,193); /* Old browsers */ - background: linear-gradient(to bottom, rgba(193,58,193,1) 0%,rgba(211,65,211,1) 20%,rgba(239,76,239,1) 40%,rgba(193,58,193,1) 70%,rgba(137,38,137,1) 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ef4cef', endColorstr='#892689',GradientType=0 ); /* IE6-9 */ + background: rgb(193,58,193); /* Old browsers */ + background: linear-gradient(to bottom, rgba(193,58,193,1) 0%,rgba(211,65,211,1) 20%,rgba(239,76,239,1) 40%,rgba(193,58,193,1) 70%,rgba(137,38,137,1) 100%); /* W3C */ + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ef4cef', endColorstr='#892689',GradientType=0 ); /* IE6-9 */ } .gtaskpink { - background: rgb(249,177,245); /* Old browsers */ - background: linear-gradient(to bottom, rgba(249,177,245,1) 0%,rgba(247,192,243,1) 20%,rgba(247,202,244,1) 40%,rgba(249,192,246,1) 70%,rgba(252,174,247,1) 100%); /* W3C */ - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7caf4', endColorstr='#fcaef7',GradientType=0 ); /* IE6-9 */ + background: rgb(249,177,245); /* Old browsers */ + background: linear-gradient(to bottom, rgba(249,177,245,1) 0%,rgba(247,192,243,1) 20%,rgba(247,202,244,1) 40%,rgba(249,192,246,1) 70%,rgba(252,174,247,1) 100%); /* W3C */ + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7caf4', endColorstr='#fcaef7',GradientType=0 ); /* IE6-9 */ } .gtaskbluecomplete, .gtaskredcomplete, @@ -137,21 +137,21 @@ span.gfoldercollapse { color:#000000; cursor:pointer; font-weight:bold; font-si /* Printer friendly styles - we could use these all the time but they are not as pretty! */ /* note that "@media print" is not supported in IE6 or 7. Fully patched IE8 should be OK */ @media print { - .ggroupblack { height:0px; border-top: 7px solid; border-color: #000000; } - .gtaskblue { height:0px; border-top: 13px solid; border-color: rgb(58,132,195); } - .gtaskred { height:0px; border-top: 13px solid; border-color: rgb(196,58,58); } - .gtaskgreen { height:0px; border-top: 13px solid; border-color: rgb(80,193,58); } - .gtaskyellow { height:0px; border-top: 13px solid; border-color: rgb(247,228,56); } - .gtaskpurple { height:0px; border-top: 13px solid; border-color: rgb(193,58,193); } - .gtaskpink { height:0px; border-top: 13px solid; border-color: rgb(249,177,245); } + .ggroupblack { height:0px; border-top: 7px solid; border-color: #000000; } + .gtaskblue { height:0px; border-top: 13px solid; border-color: rgb(58,132,195); } + .gtaskred { height:0px; border-top: 13px solid; border-color: rgb(196,58,58); } + .gtaskgreen { height:0px; border-top: 13px solid; border-color: rgb(80,193,58); } + .gtaskyellow { height:0px; border-top: 13px solid; border-color: rgb(247,228,56); } + .gtaskpurple { height:0px; border-top: 13px solid; border-color: rgb(193,58,193); } + .gtaskpink { height:0px; border-top: 13px solid; border-color: rgb(249,177,245); } - .gtaskbluecomplete, - .gtaskredcomplete, - .gtaskgreencomplete, - .gtaskyellowcomplete, - .gtaskpurplecomplete, - .gtaskpinkcomplete { height:0px; filter: alpha(opacity=40); opacity:0.4; margin-top: -9px; border-top: 5px solid; border-color: #000000; } - .ggroupblackcomplete { height: 0px; filter: alpha(opacity=80); opacity:0.8; margin-top:-5px; border-top:3px solid; border-color:#777777; } + .gtaskbluecomplete, + .gtaskredcomplete, + .gtaskgreencomplete, + .gtaskyellowcomplete, + .gtaskpurplecomplete, + .gtaskpinkcomplete { height:0px; filter: alpha(opacity=40); opacity:0.4; margin-top: -9px; border-top: 5px solid; border-color: #000000; } + .ggroupblackcomplete { height: 0px; filter: alpha(opacity=80); opacity:0.8; margin-top:-5px; border-top:3px solid; border-color:#777777; } } /* END Task bar styles */ @@ -161,11 +161,11 @@ span.gfoldercollapse { color:#000000; cursor:pointer; font-weight:bold; font-si .gDepFS, .gDepSS, .gDepSF, -.gDepFF { border-color: #26558b; } +.gDepFF { border-color: #ff0000; } .gDepFSArw, -.gDepSSArw { overflow: hidden; width:0px; height:0px; border-bottom: 4px solid transparent; border-left: 4px solid #26558b; border-top: 4px solid transparent; border-right: 4px solid transparent;} +.gDepSSArw { overflow: hidden; width:0px; height:0px; border-bottom: 4px solid transparent; border-left: 4px solid #ff0000; border-top: 4px solid transparent; border-right: 4px solid transparent;} .gDepFFArw, -.gDepSFArw { overflow: hidden; width:0px; height:0px; border-bottom: 4px solid transparent; border-left: 4px solid transparent; border-top: 4px solid transparent; border-right: 4px solid #26558b;} +.gDepSFArw { overflow: hidden; width:0px; height:0px; border-bottom: 4px solid transparent; border-left: 4px solid transparent; border-top: 4px solid transparent; border-right: 4px solid #ff0000;} .gCurDate { border-color: #0000ff; } @@ -180,29 +180,30 @@ div.gtaskbarcontainer { z-index: 1; position: absolute; top: 0px } .gTaskNotes {font-size: 11px; font-weight: normal; color: #323232; padding: 0 15px; display: block;} .gTIn {padding-top: 10px;} -.gantt { min-width: 1064px; /* 2x LC width */ } -.gchartcontainer { padding-left: 532px; /* LC width */ } -.gcontainercol { position: relative; float: left; } /* Add a max-height value here if wanted */ -.glistgrid { width: 532px; /* LC width */ margin-left: -100%; right: 532px; /* LC width */ padding-right: 0px; padding-left: 0px; padding-bottom: 0px; padding-top: 0px; background-color: #ffffff; overflow: hidden; } -.glistlbl { width: 532px; /* LC width */ margin-left: -100%; right: 532px; /* LC width */ padding-right: 0px; padding-left: 0px; padding-bottom: 0px; padding-top: 0px; background-color: #ffffff; overflow: hidden; } +.gantt { min-width: 632px; /* 2x LC width */ } +.gchartcontainer { /* padding-left: 532px; LC width */ line-height: 1; /* Overrides inherited CSS (e.g. from Bootstrap) */ } +.gcontainercol { position: relative; } /* Add a max-height value here if wanted */ +.glistgrid { width: 532px; /* LC width */ float: left; /* LC width */ padding-right: 0px; padding-left: 0px; padding-bottom: 0px; padding-top: 0px; background-color: #ffffff; overflow: hidden; } +.glistlbl { width: 532px; /* LC width */ float: left; /* LC width */ padding-right: 0px; padding-left: 0px; padding-bottom: 0px; padding-top: 0px; background-color: #ffffff; overflow: hidden; } .glabelfooter { clear: both; } .ggridfooter { clear: both; } -/*.rhscrpad { width: 150px; position: absolute; top: 0px; height: 1px; }*/ +.rhscrpad { width: 150px; position: absolute; top: 0px; height: 1px; } -.gchartgrid { width: 100%; padding-right: 0px; padding-left: 0px; padding-bottom: 0px; padding-top: 0px; background-color: #ffffff; position: relative; overflow: auto; min-height: 0%; } -.gchartlbl { width: 100%; padding-right: 0px; padding-left: 0px; padding-bottom: 0px; padding-top: 0px; background-color: #ffffff; position: relative; overflow: hidden; } +.gchartgrid { padding-right: 0px; padding-left: 0px; padding-bottom: 0px; padding-top: 0px; background-color: #ffffff; position: relative; overflow: auto; min-height: 0%; } +.gchartlbl { padding-right: 0px; padding-left: 0px; padding-bottom: 0px; padding-top: 0px; background-color: #ffffff; position: relative; overflow: hidden; } /* Old Internet Explorer version hacks */ .gantt { _height: 100% } /* otherwise the chart disappears! */ -div .gantt { _width: 1064px; } /* ie6 fixed width */ +div .gantt { /* _width: 1064px; ie6 fixed width */ } div.gchartlbl, -div.gchartgrid { _width: 532px; } /* ie6 fixed width */ +div.gchartgrid {/* _width: 532px; */} /* ie6 fixed width */ div.glistlbl, div.glistgrid { - *right: 0px; /* ie7 pulls the content too far left with the negative margin */ - _right: 532px; /* but ie6 fixed width needs this */ - _margin-left: -532px; /* ie6 fixed width */ + *right: 0px; /* ie7 pulls the content too far left with the negative margin */ + _right: 532px; /* but ie6 fixed width needs this */ + _margin-left: -532px; /* ie6 fixed width */ + float: left; } div.gchartgrid { *padding-bottom: 20px; *overflow-y: hidden; } /* variable height design, no need for vertical scroll */ td.gmajorheading div { *overflow: hidden; } /* stops resizing fixed width columns if the text is too wide */ diff --git a/htdocs/includes/jsgantt/jsgantt.js b/htdocs/includes/jsgantt/jsgantt.js index 3360d832ec6..7a26eecb9fc 100644 --- a/htdocs/includes/jsgantt/jsgantt.js +++ b/htdocs/includes/jsgantt/jsgantt.js @@ -1,68 +1,67 @@ /* - _ ___ _____ _ _____ ____ ____ - (_) / _ \ \_ \ / ||___ | ___| |___ \ - | |/ /_\/ / /\/ | | / /|___ \ __) | - | / /_\\/\/ /_ | |_ / /_ ___) | / __/ - _/ \____/\____/ |_(_)_/(_)____(_)_____| - |__/ - jsGanttImproved 1.7.5.2 - Copyright (c) 2013-2016, Paul Geldart All rights reserved. + _ ___ _ _ _____ _ + (_)___ / _ \__ _ _ __ | |_| |_ \_ \_ __ ___ _ __ _ __ _____ _____ __| | + | / __| / /_\/ _` | '_ \| __| __| / /\/ '_ ` _ \| '_ \| '__/ _ \ \ / / _ \/ _` | + | \__ \/ /_\\ (_| | | | | |_| |_/\/ /_ | | | | | | |_) | | | (_) \ V / __/ (_| | + _/ |___/\____/\__,_|_| |_|\__|\__\____/ |_| |_| |_| .__/|_| \___/ \_/ \___|\__,_| + |__/ |_| + jsGanttImproved 1.7.5.4 - The current version of this code can be found at https://code.google.com/p/jsgantt-improved/ + The current version of this code can be found at https://github.com/jsGanttImproved/jsgantt-improved/ - * Copyright (c) 2013-2016, Paul Geldart. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Paul Geldart nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY PAUL GELDART. ''AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL PAUL GELDART BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * Copyright (c) 2013-2017, Paul Geldart, Eduardo Rodrigues and Ricardo Cardoso. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Paul Geldart, Eduardo Rodrigues and Ricardo Cardoso nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY PAUL GELDART, EDUARDO RODRIGUES AND RICARDO CARDOSO ''AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL PAUL GELDART, EDUARDO RODRIGUES AND RICARDO CARDOSO BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - This project is based on jsGantt 1.2, (which can be obtained from - https://code.google.com/p/jsgantt/) and remains under the original BSD license. - The original project license follows: + This project is based on jsGantt 1.2, (which can be obtained from + https://code.google.com/p/jsgantt/) and remains under the original BSD license. + The original project license follows: - Copyright (c) 2009, Shlomy Gantz BlueBrick Inc. All rights reserved. + Copyright (c) 2009, Shlomy Gantz BlueBrick Inc. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Shlomy Gantz or BlueBrick Inc. nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY SHLOMY GANTZ/BLUEBRICK INC. ''AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL SHLOMY GANTZ/BLUEBRICK INC. BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Shlomy Gantz or BlueBrick Inc. nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY SHLOMY GANTZ/BLUEBRICK INC. ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL SHLOMY GANTZ/BLUEBRICK INC. BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ var JSGantt; if (!JSGantt) JSGantt={}; @@ -70,202 +69,205 @@ var vBenchTime=new Date().getTime(); JSGantt.isIE=function () { - if(typeof document.all!='undefined') - { - if ('pageXOffset' in window) return false; // give IE9 and above the benefit of the doubt! - else return true; - } - else return false; + if(typeof document.all!='undefined') + { + if ('pageXOffset' in window) return false; // give IE9 and above the benefit of the doubt! + else return true; + } + else return false; }; JSGantt.TaskItem=function(pID, pName, pStart, pEnd, pClass, pLink, pMile, pRes, pComp, pGroup, pParent, pOpen, pDepend, pCaption, pNotes, pGantt) { - var vID=parseInt(document.createTextNode(pID).data); - var vName=document.createTextNode(pName).data; - var vStart=new Date(0); - var vEnd=new Date(0); - var vGroupMinStart=null; - var vGroupMinEnd=null; - var vClass=document.createTextNode(pClass).data; - var vLink=document.createTextNode(pLink).data; - var vMile=parseInt(document.createTextNode(pMile).data); - var vRes=document.createTextNode(pRes).data; - var vComp=parseFloat(document.createTextNode(pComp).data); - var vGroup=parseInt(document.createTextNode(pGroup).data); - var vParent=document.createTextNode(pParent).data; - var vOpen=(vGroup==2)?1:parseInt(document.createTextNode(pOpen).data); - var vDepend=new Array(); - var vDependType=new Array(); - var vCaption=document.createTextNode(pCaption).data; - var vDuration=''; - var vLevel=0; - var vNumKid=0; - var vVisible=1; - var vSortIdx=0; - var vToDelete=false; - var x1, y1, x2, y2; - var vNotes; - var vParItem=null; - var vCellDiv=null; - var vGantt=(pGantt instanceof JSGantt.GanttChart)? pGantt : g; //hack for backwards compatibility - var vBarDiv=null; - var vTaskDiv=null; - var vListChildRow=null; - var vChildRow=null; - var vGroupSpan=null; + var vID=parseInt(document.createTextNode(pID).data); + var vName=document.createTextNode(pName).data; + var vStart=new Date(0); + var vEnd=new Date(0); + var vGroupMinStart=null; + var vGroupMinEnd=null; + var vClass=document.createTextNode(pClass).data; + var vLink=document.createTextNode(pLink).data; + var vMile=parseInt(document.createTextNode(pMile).data); + var vRes=document.createTextNode(pRes).data; + var vComp=parseFloat(document.createTextNode(pComp).data); + var vGroup=parseInt(document.createTextNode(pGroup).data); + var vParent=document.createTextNode(pParent).data; + var vOpen=(vGroup==2)?1:parseInt(document.createTextNode(pOpen).data); + var vDepend=new Array(); + var vDependType=new Array(); + var vCaption=document.createTextNode(pCaption).data; + var vDuration=''; + var vLevel=0; + var vNumKid=0; + var vWeight=0; + var vVisible=1; + var vSortIdx=0; + var vToDelete=false; + var x1, y1, x2, y2; + var vNotes; + var vParItem=null; + var vCellDiv=null; + var vGantt=(pGantt instanceof JSGantt.GanttChart)? pGantt : g; //hack for backwards compatibility + var vBarDiv=null; + var vTaskDiv=null; + var vListChildRow=null; + var vChildRow=null; + var vGroupSpan=null; - vNotes=document.createElement('span'); - vNotes.className='gTaskNotes'; - if (pNotes!=null) - { - vNotes.innerHTML=pNotes; - JSGantt.stripUnwanted(vNotes); - } + vNotes=document.createElement('span'); + vNotes.className='gTaskNotes'; + if (pNotes!=null) + { + vNotes.innerHTML=pNotes; + JSGantt.stripUnwanted(vNotes); + } - if (pStart!=null && pStart!='') - { - vStart=(pStart instanceof Date)?pStart:JSGantt.parseDateStr(document.createTextNode(pStart).data,vGantt.getDateInputFormat()); - vGroupMinStart=vStart; - } + if (pStart!=null && pStart!='') + { + vStart=(pStart instanceof Date)?pStart:JSGantt.parseDateStr(document.createTextNode(pStart).data,vGantt.getDateInputFormat()); + vGroupMinStart=vStart; + } - if (pEnd!=null && pEnd!='') - { - vEnd =(pEnd instanceof Date)?pEnd:JSGantt.parseDateStr(document.createTextNode(pEnd).data,vGantt.getDateInputFormat()); - vGroupMinEnd=vEnd; - } + if (pEnd!=null && pEnd!='') + { + vEnd =(pEnd instanceof Date)?pEnd:JSGantt.parseDateStr(document.createTextNode(pEnd).data,vGantt.getDateInputFormat()); + vGroupMinEnd=vEnd; + } - if (pDepend!=null) - { - var vDependStr=pDepend+''; - var vDepList=vDependStr.split(','); - var n=vDepList.length; + if (pDepend!=null) + { + var vDependStr=pDepend+''; + var vDepList=vDependStr.split(','); + var n=vDepList.length; - for(var k=0;k1) - { - vFormatArr[j++]=arguments[i].toLowerCase(); - var vRegExp=new RegExp('(?:^|\s)'+arguments[i]+'(?!\S)', 'g'); - vValidFormats=vValidFormats.replace(vRegExp, ''); - } - } - }; - this.setShowRes=function(pVal){vShowRes=pVal;}; - this.setShowDur=function(pVal){vShowDur=pVal;}; - this.setShowComp=function(pVal){vShowComp=pVal;}; - this.setShowStartDate=function(pVal){vShowStartDate=pVal;}; - this.setShowEndDate=function(pVal){vShowEndDate=pVal;}; - this.setShowTaskInfoRes=function(pVal){vShowTaskInfoRes=pVal;}; - this.setShowTaskInfoDur=function(pVal){vShowTaskInfoDur=pVal;}; - this.setShowTaskInfoComp=function(pVal){vShowTaskInfoComp=pVal;}; - this.setShowTaskInfoStartDate=function(pVal){vShowTaskInfoStartDate=pVal;}; - this.setShowTaskInfoEndDate=function(pVal){vShowTaskInfoEndDate=pVal;}; - this.setShowTaskInfoNotes=function(pVal){vShowTaskInfoNotes=pVal;}; - this.setShowTaskInfoLink=function(pVal){vShowTaskInfoLink=pVal;}; - this.setShowEndWeekDate=function(pVal){vShowEndWeekDate=pVal;}; - this.setShowSelector=function() - { - var vValidSelectors='top bottom'; - vShowSelector=new Array(); - for(var i=0, j=0; i1) - { - vShowSelector[j++]=arguments[i].toLowerCase(); - var vRegExp=new RegExp('(?:^|\s)'+arguments[i]+'(?!\S)', 'g'); - vValidSelectors=vValidSelectors.replace(vRegExp, ''); - } - } - }; - this.setShowDeps=function(pVal){vShowDeps=pVal;}; - this.setDateInputFormat=function(pVal){vDateInputFormat=pVal;}; - this.setDateTaskTableDisplayFormat=function(pVal){vDateTaskTableDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setDateTaskDisplayFormat=function(pVal){vDateTaskDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setHourMajorDateDisplayFormat=function(pVal){vHourMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setHourMinorDateDisplayFormat=function(pVal){vHourMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setDayMajorDateDisplayFormat=function(pVal){vDayMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setDayMinorDateDisplayFormat=function(pVal){vDayMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setWeekMajorDateDisplayFormat=function(pVal){vWeekMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setWeekMinorDateDisplayFormat=function(pVal){vWeekMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setMonthMajorDateDisplayFormat=function(pVal){vMonthMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setMonthMinorDateDisplayFormat=function(pVal){vMonthMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setQuarterMajorDateDisplayFormat=function(pVal){vQuarterMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setQuarterMinorDateDisplayFormat=function(pVal){vQuarterMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; - this.setCaptionType=function(pType){vCaptionType=pType;}; - this.setFormat=function(pFormat) - { - vFormat=pFormat; - this.Draw(); - }; - this.setMinGpLen=function(pMinGpLen){vMinGpLen=pMinGpLen;}; - this.setScrollTo=function(pDate){vScrollTo=pDate;}; - this.setHourColWidth=function(pWidth){vHourColWidth=pWidth;}; - this.setDayColWidth=function(pWidth){vDayColWidth=pWidth;}; - this.setWeekColWidth=function(pWidth){vWeekColWidth=pWidth;}; - this.setMonthColWidth=function(pWidth){vMonthColWidth=pWidth;}; - this.setQuarterColWidth=function(pWidth){vQuarterColWidth=pWidth;}; - this.setRowHeight=function(pHeight){vRowHeight=pHeight;}; - this.setLang=function(pLang){if(vLangs[pLang])vLang=pLang;}; - this.setChartBody=function(pDiv){if(typeof HTMLDivElement !== 'function' || pDiv instanceof HTMLDivElement)vChartBody=pDiv;}; - this.setChartHead=function(pDiv){if(typeof HTMLDivElement !== 'function' || pDiv instanceof HTMLDivElement)vChartHead=pDiv;}; - this.setListBody=function(pDiv){if(typeof HTMLDivElement !== 'function' || pDiv instanceof HTMLDivElement)vListBody=pDiv;}; - this.setChartTable=function(pTable){if(typeof HTMLTableElement !== 'function' || pTable instanceof HTMLTableElement)vChartTable=pTable;}; - this.setLines=function(pDiv){if(typeof HTMLDivElement !== 'function' || pDiv instanceof HTMLDivElement)vLines=pDiv;}; - this.setTimer=function(pVal){vTimer=pVal*1;}; - this.addLang=function(pLang, pVals){ - if(!vLangs[pLang]) - { - vLangs[pLang]=new Object(); - for(var vKey in vLangs['en'])vLangs[pLang][vKey]=(pVals[vKey])?document.createTextNode(pVals[vKey]).data:vLangs['en'][vKey]; - } - }; + this.setUseFade=function(pVal){vUseFade=pVal;}; + this.setUseMove=function(pVal){vUseMove=pVal;}; + this.setUseRowHlt=function(pVal){vUseRowHlt=pVal;}; + this.setUseToolTip=function(pVal){vUseToolTip=pVal;}; + this.setUseSort=function(pVal){vUseSort=pVal;}; + this.setUseSingleCell=function(pVal){vUseSingleCell=pVal*1;}; + this.setFormatArr=function() + { + var vValidFormats='hour day week month quarter'; + vFormatArr=new Array(); + for(var i=0, j=0; i1) + { + vFormatArr[j++]=arguments[i].toLowerCase(); + var vRegExp=new RegExp('(?:^|\s)'+arguments[i]+'(?!\S)', 'g'); + vValidFormats=vValidFormats.replace(vRegExp, ''); + } + } + }; + this.setShowRes=function(pVal){vShowRes=pVal;}; + this.setShowDur=function(pVal){vShowDur=pVal;}; + this.setShowComp=function(pVal){vShowComp=pVal;}; + this.setShowStartDate=function(pVal){vShowStartDate=pVal;}; + this.setShowEndDate=function(pVal){vShowEndDate=pVal;}; + this.setShowTaskInfoRes=function(pVal){vShowTaskInfoRes=pVal;}; + this.setShowTaskInfoDur=function(pVal){vShowTaskInfoDur=pVal;}; + this.setShowTaskInfoComp=function(pVal){vShowTaskInfoComp=pVal;}; + this.setShowTaskInfoStartDate=function(pVal){vShowTaskInfoStartDate=pVal;}; + this.setShowTaskInfoEndDate=function(pVal){vShowTaskInfoEndDate=pVal;}; + this.setShowTaskInfoNotes=function(pVal){vShowTaskInfoNotes=pVal;}; + this.setShowTaskInfoLink=function(pVal){vShowTaskInfoLink=pVal;}; + this.setShowEndWeekDate=function(pVal){vShowEndWeekDate=pVal;}; + this.setShowSelector=function() + { + var vValidSelectors='top bottom'; + vShowSelector=new Array(); + for(var i=0, j=0; i1) + { + vShowSelector[j++]=arguments[i].toLowerCase(); + var vRegExp=new RegExp('(?:^|\s)'+arguments[i]+'(?!\S)', 'g'); + vValidSelectors=vValidSelectors.replace(vRegExp, ''); + } + } + }; + this.setShowDeps=function(pVal){vShowDeps=pVal;}; + this.setDateInputFormat=function(pVal){vDateInputFormat=pVal;}; + this.setDateTaskTableDisplayFormat=function(pVal){vDateTaskTableDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setDateTaskDisplayFormat=function(pVal){vDateTaskDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setHourMajorDateDisplayFormat=function(pVal){vHourMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setHourMinorDateDisplayFormat=function(pVal){vHourMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setDayMajorDateDisplayFormat=function(pVal){vDayMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setDayMinorDateDisplayFormat=function(pVal){vDayMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setWeekMajorDateDisplayFormat=function(pVal){vWeekMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setWeekMinorDateDisplayFormat=function(pVal){vWeekMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setMonthMajorDateDisplayFormat=function(pVal){vMonthMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setMonthMinorDateDisplayFormat=function(pVal){vMonthMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setQuarterMajorDateDisplayFormat=function(pVal){vQuarterMajorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setQuarterMinorDateDisplayFormat=function(pVal){vQuarterMinorDateDisplayFormat=JSGantt.parseDateFormatStr(pVal);}; + this.setCaptionType=function(pType){vCaptionType=pType;}; + this.setFormat=function(pFormat) + { + vFormat=pFormat; + this.Draw(); + }; + this.setMinGpLen=function(pMinGpLen){vMinGpLen=pMinGpLen;}; + this.setScrollTo=function(pDate){vScrollTo=pDate;}; + this.setHourColWidth=function(pWidth){vHourColWidth=pWidth;}; + this.setDayColWidth=function(pWidth){vDayColWidth=pWidth;}; + this.setWeekColWidth=function(pWidth){vWeekColWidth=pWidth;}; + this.setMonthColWidth=function(pWidth){vMonthColWidth=pWidth;}; + this.setQuarterColWidth=function(pWidth){vQuarterColWidth=pWidth;}; + this.setRowHeight=function(pHeight){vRowHeight=pHeight;}; + this.setLang=function(pLang){if(vLangs[pLang])vLang=pLang;}; + this.setChartBody=function(pDiv){if(typeof HTMLDivElement !== 'function' || pDiv instanceof HTMLDivElement)vChartBody=pDiv;}; + this.setChartHead=function(pDiv){if(typeof HTMLDivElement !== 'function' || pDiv instanceof HTMLDivElement)vChartHead=pDiv;}; + this.setListBody=function(pDiv){if(typeof HTMLDivElement !== 'function' || pDiv instanceof HTMLDivElement)vListBody=pDiv;}; + this.setChartTable=function(pTable){if(typeof HTMLTableElement !== 'function' || pTable instanceof HTMLTableElement)vChartTable=pTable;}; + this.setLines=function(pDiv){if(typeof HTMLDivElement !== 'function' || pDiv instanceof HTMLDivElement)vLines=pDiv;}; + this.setTimer=function(pVal){vTimer=pVal*1;}; + this.addLang=function(pLang, pVals){ + if(!vLangs[pLang]) + { + vLangs[pLang]=new Object(); + for(var vKey in vLangs['en'])vLangs[pLang][vKey]=(pVals[vKey])?document.createTextNode(pVals[vKey]).data:vLangs['en'][vKey]; + } + }; - this.getDivId=function(){return vDivId;}; - this.getUseFade=function(){return vUseFade;}; - this.getUseMove=function(){return vUseMove;}; - this.getUseRowHlt=function(){return vUseRowHlt;}; - this.getUseToolTip=function(){return vUseToolTip;}; - this.getUseSort=function(){return vUseSort;}; - this.getUseSingleCell=function(){return vUseSingleCell;}; - this.getFormatArr=function(){return vFormatArr;}; - this.getShowRes=function(){return vShowRes;}; - this.getShowDur=function(){return vShowDur;}; - this.getShowComp=function(){return vShowComp;}; - this.getShowStartDate=function(){return vShowStartDate;}; - this.getShowEndDate=function(){return vShowEndDate;}; - this.getShowTaskInfoRes=function(){return vShowTaskInfoRes;}; - this.getShowTaskInfoDur=function(){return vShowTaskInfoDur;}; - this.getShowTaskInfoComp=function(){return vShowTaskInfoComp;}; - this.getShowTaskInfoStartDate=function(){return vShowTaskInfoStartDate;}; - this.getShowTaskInfoEndDate=function(){return vShowTaskInfoEndDate;}; - this.getShowTaskInfoNotes=function(){return vShowTaskInfoNotes;}; - this.getShowTaskInfoLink=function(){return vShowTaskInfoLink;}; - this.getShowEndWeekDate=function(){return vShowEndWeekDate;}; - this.getShowSelector=function(){return vShowSelector;}; - this.getShowDeps=function(){return vShowDeps;}; - this.getDateInputFormat=function(){return vDateInputFormat;}; - this.getDateTaskTableDisplayFormat=function(){return vDateTaskTableDisplayFormat;}; - this.getDateTaskDisplayFormat=function(){return vDateTaskDisplayFormat;}; - this.getHourMajorDateDisplayFormat=function(){return vHourMajorDateDisplayFormat;}; - this.getHourMinorDateDisplayFormat=function(){return vHourMinorDateDisplayFormat;}; - this.getDayMajorDateDisplayFormat=function(){return vDayMajorDateDisplayFormat;}; - this.getDayMinorDateDisplayFormat=function(){return vDayMinorDateDisplayFormat;}; - this.getWeekMajorDateDisplayFormat=function(){return vWeekMajorDateDisplayFormat;}; - this.getWeekMinorDateDisplayFormat=function(){return vWeekMinorDateDisplayFormat;}; - this.getMonthMajorDateDisplayFormat=function(){return vMonthMajorDateDisplayFormat;}; - this.getMonthMinorDateDisplayFormat=function(){return vMonthMinorDateDisplayFormat;}; - this.getQuarterMajorDateDisplayFormat=function(){return vQuarterMajorDateDisplayFormat;}; - this.getQuarterMinorDateDisplayFormat=function(){return vQuarterMinorDateDisplayFormat;}; - this.getCaptionType=function(){return vCaptionType;}; - this.getMinGpLen=function(){return vMinGpLen;}; - this.getScrollTo=function(){return vScrollTo;}; - this.getHourColWidth=function(){return vHourColWidth;}; - this.getDayColWidth=function(){return vDayColWidth;}; - this.getWeekColWidth=function(){return vWeekColWidth;}; - this.getMonthColWidth=function(){return vMonthColWidth;}; - this.getQuarterColWidth=function(){return vQuarterColWidth;}; - this.getRowHeight=function(){return vRowHeight;}; - this.getChartBody=function(){return vChartBody;}; - this.getChartHead=function(){return vChartHead;}; - this.getListBody=function(){return vListBody;}; - this.getChartTable=function(){return vChartTable;}; - this.getLines=function(){return vLines;}; - this.getTimer=function(){return vTimer;}; + this.getDivId=function(){return vDivId;}; + this.getUseFade=function(){return vUseFade;}; + this.getUseMove=function(){return vUseMove;}; + this.getUseRowHlt=function(){return vUseRowHlt;}; + this.getUseToolTip=function(){return vUseToolTip;}; + this.getUseSort=function(){return vUseSort;}; + this.getUseSingleCell=function(){return vUseSingleCell;}; + this.getFormatArr=function(){return vFormatArr;}; + this.getShowRes=function(){return vShowRes;}; + this.getShowDur=function(){return vShowDur;}; + this.getShowComp=function(){return vShowComp;}; + this.getShowStartDate=function(){return vShowStartDate;}; + this.getShowEndDate=function(){return vShowEndDate;}; + this.getShowTaskInfoRes=function(){return vShowTaskInfoRes;}; + this.getShowTaskInfoDur=function(){return vShowTaskInfoDur;}; + this.getShowTaskInfoComp=function(){return vShowTaskInfoComp;}; + this.getShowTaskInfoStartDate=function(){return vShowTaskInfoStartDate;}; + this.getShowTaskInfoEndDate=function(){return vShowTaskInfoEndDate;}; + this.getShowTaskInfoNotes=function(){return vShowTaskInfoNotes;}; + this.getShowTaskInfoLink=function(){return vShowTaskInfoLink;}; + this.getShowEndWeekDate=function(){return vShowEndWeekDate;}; + this.getShowSelector=function(){return vShowSelector;}; + this.getShowDeps=function(){return vShowDeps;}; + this.getDateInputFormat=function(){return vDateInputFormat;}; + this.getDateTaskTableDisplayFormat=function(){return vDateTaskTableDisplayFormat;}; + this.getDateTaskDisplayFormat=function(){return vDateTaskDisplayFormat;}; + this.getHourMajorDateDisplayFormat=function(){return vHourMajorDateDisplayFormat;}; + this.getHourMinorDateDisplayFormat=function(){return vHourMinorDateDisplayFormat;}; + this.getDayMajorDateDisplayFormat=function(){return vDayMajorDateDisplayFormat;}; + this.getDayMinorDateDisplayFormat=function(){return vDayMinorDateDisplayFormat;}; + this.getWeekMajorDateDisplayFormat=function(){return vWeekMajorDateDisplayFormat;}; + this.getWeekMinorDateDisplayFormat=function(){return vWeekMinorDateDisplayFormat;}; + this.getMonthMajorDateDisplayFormat=function(){return vMonthMajorDateDisplayFormat;}; + this.getMonthMinorDateDisplayFormat=function(){return vMonthMinorDateDisplayFormat;}; + this.getQuarterMajorDateDisplayFormat=function(){return vQuarterMajorDateDisplayFormat;}; + this.getQuarterMinorDateDisplayFormat=function(){return vQuarterMinorDateDisplayFormat;}; + this.getCaptionType=function(){return vCaptionType;}; + this.getMinGpLen=function(){return vMinGpLen;}; + this.getScrollTo=function(){return vScrollTo;}; + this.getHourColWidth=function(){return vHourColWidth;}; + this.getDayColWidth=function(){return vDayColWidth;}; + this.getWeekColWidth=function(){return vWeekColWidth;}; + this.getMonthColWidth=function(){return vMonthColWidth;}; + this.getQuarterColWidth=function(){return vQuarterColWidth;}; + this.getRowHeight=function(){return vRowHeight;}; + this.getChartBody=function(){return vChartBody;}; + this.getChartHead=function(){return vChartHead;}; + this.getListBody=function(){return vListBody;}; + this.getChartTable=function(){return vChartTable;}; + this.getLines=function(){return vLines;}; + this.getTimer=function(){return vTimer;}; - this.CalcTaskXY=function() - { - var vID; - var vList=this.getList(); - var vBarDiv; - var vTaskDiv; - var vParDiv; - var vLeft, vTop, vWidth; - var vHeight=Math.floor((this.getRowHeight()/2)); + this.CalcTaskXY=function() + { + var vID; + var vList=this.getList(); + var vBarDiv; + var vTaskDiv; + var vParDiv; + var vLeft, vTop, vWidth; + var vHeight=Math.floor((this.getRowHeight()/2)); - for(var i=0; i=x2 && y1!=y2) vBend=true; - break; - } + switch(pType) + { + case 'SF': + vShort*=-1; + if(x1-10<=x2 && y1!=y2) vBend=true; + vDir=-1; + break; + case 'SS': + if (x1=x2 && y1!=y2) vBend=true; + break; + } - if (vBend) - { - this.sLine(x1,y1,x1+vShort,y1,pClass); - this.sLine(x1+vShort,y1,x1+vShort,y2-vRow,pClass); - this.sLine(x1+vShort,y2-vRow,x2-(vShort*2),y2-vRow,pClass); - this.sLine(x2-(vShort*2),y2-vRow,x2-(vShort*2),y2,pClass); - this.sLine(x2-(vShort*2),y2,x2-(1*vDir),y2,pClass); - } - else if (y1!=y2) - { - this.sLine(x1,y1,x1+vShort,y1,pClass); - this.sLine(x1+vShort,y1,x1+vShort,y2,pClass); - this.sLine(x1+vShort,y2,x2-(1*vDir),y2,pClass); - } - else this.sLine(x1,y1,x2-(1*vDir),y2,pClass); + if (vBend) + { + this.sLine(x1,y1,x1+vShort,y1,pClass); + this.sLine(x1+vShort,y1,x1+vShort,y2-vRow,pClass); + this.sLine(x1+vShort,y2-vRow,x2-(vShort*2),y2-vRow,pClass); + this.sLine(x2-(vShort*2),y2-vRow,x2-(vShort*2),y2,pClass); + this.sLine(x2-(vShort*2),y2,x2-(1*vDir),y2,pClass); + } + else if (y1!=y2) + { + this.sLine(x1,y1,x1+vShort,y1,pClass); + this.sLine(x1+vShort,y1,x1+vShort,y2,pClass); + this.sLine(x1+vShort,y2,x2-(1*vDir),y2,pClass); + } + else this.sLine(x1,y1,x2-(1*vDir),y2,pClass); - var vTmpDiv=this.sLine(x2,y2,x2-3-((vDir<0)?1:0),y2-3-((vDir<0)?1:0),pClass+"Arw"); - vTmpDiv.style.width='0px'; - vTmpDiv.style.height='0px'; - }; + var vTmpDiv=this.sLine(x2,y2,x2-3-((vDir<0)?1:0),y2-3-((vDir<0)?1:0),pClass+"Arw"); + vTmpDiv.style.width='0px'; + vTmpDiv.style.height='0px'; + }; - this.DrawDependencies=function() - { - if (this.getShowDeps()==1) - { - //First recalculate the x,y - this.CalcTaskXY(); - this.clearDependencies(); + this.DrawDependencies=function() + { + if (this.getShowDeps()==1) + { + //First recalculate the x,y + this.CalcTaskXY(); + this.clearDependencies(); - var vList=this.getList(); - for(var i=0; i0 && vList[i].getVisible()==1) - { - for(var k=0;k=0 && vList[vTask].getGroup()!=2) - { - if(vList[vTask].getVisible()==1) - { - if(vDependType[k]=='SS')this.drawDependency(vList[vTask].getStartX()-1,vList[vTask].getStartY(),vList[i].getStartX()-1,vList[i].getStartY(),'SS','gDepSS'); - else if(vDependType[k]=='FF')this.drawDependency(vList[vTask].getEndX(),vList[vTask].getEndY(),vList[i].getEndX(),vList[i].getEndY(),'FF','gDepFF'); - else if(vDependType[k]=='SF')this.drawDependency(vList[vTask].getStartX()-1,vList[vTask].getStartY(),vList[i].getEndX(),vList[i].getEndY(),'SF','gDepSF'); - else if(vDependType[k]=='FS')this.drawDependency(vList[vTask].getEndX(),vList[vTask].getEndY(),vList[i].getStartX()-1,vList[i].getStartY(),'FS','gDepFS'); - } - } - } - } - } - } - // draw the current date line - if (vTodayPx>=0) this.sLine(vTodayPx, 0, vTodayPx, this.getChartTable().offsetHeight-1, 'gCurDate'); - }; + if(n>0 && vList[i].getVisible()==1) + { + for(var k=0;k=0 && vList[vTask].getGroup()!=2) + { + if(vList[vTask].getVisible()==1) + { + if(vDependType[k]=='SS')this.drawDependency(vList[vTask].getStartX()-1,vList[vTask].getStartY(),vList[i].getStartX()-1,vList[i].getStartY(),'SS','gDepSS'); + else if(vDependType[k]=='FF')this.drawDependency(vList[vTask].getEndX(),vList[vTask].getEndY(),vList[i].getEndX(),vList[i].getEndY(),'FF','gDepFF'); + else if(vDependType[k]=='SF')this.drawDependency(vList[vTask].getStartX()-1,vList[vTask].getStartY(),vList[i].getEndX(),vList[i].getEndY(),'SF','gDepSF'); + else if(vDependType[k]=='FS')this.drawDependency(vList[vTask].getEndX(),vList[vTask].getEndY(),vList[i].getStartX()-1,vList[i].getStartY(),'FS','gDepFS'); + } + } + } + } + } + } + // draw the current date line + if (vTodayPx>=0) this.sLine(vTodayPx, 0, vTodayPx, this.getChartTable().offsetHeight-1, 'gCurDate'); + }; - this.getArrayLocationByID=function(pId) - { - var vList=this.getList(); - for(var i=0; i0) - { - // Process all tasks, reset parent date and completion % if task list has altered - if (vProcessNeeded) JSGantt.processRows(vTaskList, 0, -1, 1, 1, this.getUseSort()); - vProcessNeeded=false; + if(vTaskList.length>0) + { + // Process all tasks, reset parent date and completion % if task list has altered + if (vProcessNeeded) JSGantt.processRows(vTaskList, 0, -1, 1, 1, this.getUseSort()); + vProcessNeeded=false; - // get overall min/max dates plus padding - vMinDate=JSGantt.getMinDate(vTaskList, vFormat); - vMaxDate=JSGantt.getMaxDate(vTaskList, vFormat); + // get overall min/max dates plus padding + vMinDate=JSGantt.getMinDate(vTaskList, vFormat); + vMaxDate=JSGantt.getMaxDate(vTaskList, vFormat); - // Calculate chart width variables. - if(vFormat=='day') vColWidth=vDayColWidth; - else if(vFormat=='week') vColWidth=vWeekColWidth; - else if(vFormat=='month') vColWidth=vMonthColWidth; - else if(vFormat=='quarter') vColWidth=vQuarterColWidth; - else if(vFormat=='hour') vColWidth=vHourColWidth; + // Calculate chart width variables. + if(vFormat=='day') vColWidth=vDayColWidth; + else if(vFormat=='week') vColWidth=vWeekColWidth; + else if(vFormat=='month') vColWidth=vMonthColWidth; + else if(vFormat=='quarter') vColWidth=vQuarterColWidth; + else if(vFormat=='hour') vColWidth=vHourColWidth; - // DRAW the Left-side of the chart (names, resources, comp%) - var vLeftHeader=document.createDocumentFragment(); + // DRAW the Left-side of the chart (names, resources, comp%) + var vLeftHeader=document.createDocumentFragment(); - var vTmpDiv=this.newNode(vLeftHeader, 'div', vDivId+'glisthead', 'glistlbl gcontainercol'); - var vTmpTab=this.newNode(vTmpDiv, 'table', null, 'gtasktableh'); - var vTmpTBody=this.newNode(vTmpTab, 'tbody'); - var vTmpRow=this.newNode(vTmpTBody, 'tr'); - this.newNode(vTmpRow, 'td', null, 'gtasklist', '\u00A0'); - var vTmpCell=this.newNode(vTmpRow, 'td', null, 'gspanning gtaskname'); - vTmpCell.appendChild(this.drawSelector('top')); - if(vShowRes==1)this.newNode(vTmpRow, 'td', null, 'gspanning gresource', '\u00A0'); - if(vShowDur==1)this.newNode(vTmpRow, 'td', null, 'gspanning gduration', '\u00A0'); - if(vShowComp==1)this.newNode(vTmpRow, 'td', null, 'gspanning gpccomplete', '\u00A0'); - if(vShowStartDate==1)this.newNode(vTmpRow, 'td', null, 'gspanning gstartdate', '\u00A0'); - if(vShowEndDate==1)this.newNode(vTmpRow, 'td', null, 'gspanning genddate', '\u00A0'); + var vTmpDiv=this.newNode(vLeftHeader, 'div', vDivId+'glisthead', 'glistlbl gcontainercol'); + var vTmpTab=this.newNode(vTmpDiv, 'table', null, 'gtasktableh'); + var vTmpTBody=this.newNode(vTmpTab, 'tbody'); + var vTmpRow=this.newNode(vTmpTBody, 'tr'); + this.newNode(vTmpRow, 'td', null, 'gtasklist', '\u00A0'); + var vTmpCell=this.newNode(vTmpRow, 'td', null, 'gspanning gtaskname'); + vTmpCell.appendChild(this.drawSelector('top')); + if(vShowRes==1)this.newNode(vTmpRow, 'td', null, 'gspanning gresource', '\u00A0'); + if(vShowDur==1)this.newNode(vTmpRow, 'td', null, 'gspanning gduration', '\u00A0'); + if(vShowComp==1)this.newNode(vTmpRow, 'td', null, 'gspanning gpccomplete', '\u00A0'); + if(vShowStartDate==1)this.newNode(vTmpRow, 'td', null, 'gspanning gstartdate', '\u00A0'); + if(vShowEndDate==1)this.newNode(vTmpRow, 'td', null, 'gspanning genddate', '\u00A0'); - vTmpRow=this.newNode(vTmpTBody, 'tr'); - this.newNode(vTmpRow, 'td', null, 'gtasklist', '\u00A0'); - this.newNode(vTmpRow, 'td', null, 'gtaskname', '\u00A0'); - if(vShowRes==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading gresource', vLangs[vLang]['resource']); - if(vShowDur==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading gduration', vLangs[vLang]['duration']); - if(vShowComp==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading gpccomplete', vLangs[vLang]['comp']); - if(vShowStartDate==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading gstartdate', vLangs[vLang]['startdate']); - if(vShowEndDate==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading genddate', vLangs[vLang]['enddate']); + vTmpRow=this.newNode(vTmpTBody, 'tr'); + this.newNode(vTmpRow, 'td', null, 'gtasklist', '\u00A0'); + this.newNode(vTmpRow, 'td', null, 'gtaskname', '\u00A0'); + if(vShowRes==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading gresource', vLangs[vLang]['resource']); + if(vShowDur==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading gduration', vLangs[vLang]['duration']); + if(vShowComp==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading gpccomplete', vLangs[vLang]['comp']); + if(vShowStartDate==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading gstartdate', vLangs[vLang]['startdate']); + if(vShowEndDate==1)this.newNode(vTmpRow, 'td', null, 'gtaskheading genddate', vLangs[vLang]['enddate']); - vTmpDiv=this.newNode(vLeftHeader, 'div', null, 'glabelfooter'); + var vLeftTable=document.createDocumentFragment(); + var vTmpDiv2=this.newNode(vLeftTable, 'div', vDivId+'glistbody', 'glistgrid gcontainercol'); + this.setListBody(vTmpDiv2); + vTmpTab=this.newNode(vTmpDiv2, 'table', null, 'gtasktable'); + vTmpTBody=this.newNode(vTmpTab, 'tbody'); - var vLeftTable=document.createDocumentFragment(); - var vTmpDiv2=this.newNode(vLeftTable, 'div', vDivId+'glistbody', 'glistgrid gcontainercol'); - this.setListBody(vTmpDiv2); - vTmpTab=this.newNode(vTmpDiv2, 'table', null, 'gtasktable'); - vTmpTBody=this.newNode(vTmpTab, 'tbody'); + for(i=0; i1) - { - vTmpDate.setDate(vTmpDate.getDate()+1); - } - } - else if(vFormat=='quarter') - { - if(vTmpDate<=vMaxDate) - { - vTmpCell=this.newNode(vTmpRow, 'td', null, vHeaderCellClass); - this.newNode(vTmpCell, 'div', null, null, JSGantt.formatDateStr(vTmpDate,vQuarterMinorDateDisplayFormat,vLangs[vLang]), vColWidth); - vNumCols++; - } + while(vTmpDate.getDate()>1) + { + vTmpDate.setDate(vTmpDate.getDate()+1); + } + } + else if(vFormat=='quarter') + { + if(vTmpDate<=vMaxDate) + { + vTmpCell=this.newNode(vTmpRow, 'td', null, vHeaderCellClass); + this.newNode(vTmpCell, 'div', null, null, JSGantt.formatDateStr(vTmpDate,vQuarterMinorDateDisplayFormat,vLangs[vLang]), vColWidth); + vNumCols++; + } - vTmpDate.setDate(vTmpDate.getDate()+81); + vTmpDate.setDate(vTmpDate.getDate()+81); - while(vTmpDate.getDate()>1) vTmpDate.setDate(vTmpDate.getDate()+1); - } - else if(vFormat=='hour') - { - for(i=vTmpDate.getHours();i<24;i++) - { - vTmpDate.setHours(i);//works around daylight savings but may look a little odd on days where the clock goes forward - if(vTmpDate<=vMaxDate) - { - vTmpCell=this.newNode(vTmpRow, 'td', null, vHeaderCellClass); - this.newNode(vTmpCell, 'div', null, null, JSGantt.formatDateStr(vTmpDate,vHourMinorDateDisplayFormat,vLangs[vLang]), vColWidth); - vNumCols++; - } - } - vTmpDate.setHours(0); - vTmpDate.setDate(vTmpDate.getDate()+1); - } - } - vDateRow=vTmpRow; + while(vTmpDate.getDate()>1) vTmpDate.setDate(vTmpDate.getDate()+1); + } + else if(vFormat=='hour') + { + for(i=vTmpDate.getHours();i<24;i++) + { + vTmpDate.setHours(i);//works around daylight savings but may look a little odd on days where the clock goes forward + if(vTmpDate<=vMaxDate) + { + vTmpCell=this.newNode(vTmpRow, 'td', null, vHeaderCellClass); + this.newNode(vTmpCell, 'div', null, null, JSGantt.formatDateStr(vTmpDate,vHourMinorDateDisplayFormat,vLangs[vLang]), vColWidth); + vNumCols++; + } + } + vTmpDate.setHours(0); + vTmpDate.setDate(vTmpDate.getDate()+1); + } + } + vDateRow=vTmpRow; - vTaskLeftPx=(vNumCols *(vColWidth+1))+1; + vTaskLeftPx=(vNumCols *(vColWidth+1))+1; - if(vUseSingleCell!=0 && vUseSingleCell<(vNumCols*vNumRows))vSingleCell=true; + if(vUseSingleCell!=0 && vUseSingleCell<(vNumCols*vNumRows))vSingleCell=true; - this.newNode(vTmpDiv, 'div', null, 'rhscrpad', null, null, vTaskLeftPx+1); + this.newNode(vTmpDiv, 'div', null, 'rhscrpad', null, null, vTaskLeftPx+1); - var vRightTable=document.createDocumentFragment(); - vTmpDiv=this.newNode(vRightTable, 'div', vDivId+'gchartbody', 'gchartgrid gcontainercol'); - this.setChartBody(vTmpDiv); - vTmpTab=this.newNode(vTmpDiv, 'table', vDivId+'chartTable', 'gcharttable', null, vTaskLeftPx); - this.setChartTable(vTmpTab); - this.newNode(vTmpDiv, 'div', null, 'rhscrpad', null, null, vTaskLeftPx+1); - vTmpTBody=this.newNode(vTmpTab, 'tbody'); + vTmpDiv=this.newNode(vRightHeader, 'div', null, 'glabelfooter'); - // Draw each row + var vRightTable=document.createDocumentFragment(); + vTmpDiv=this.newNode(vRightTable, 'div', vDivId+'gchartbody', 'gchartgrid gcontainercol'); + this.setChartBody(vTmpDiv); + vTmpTab=this.newNode(vTmpDiv, 'table', vDivId+'chartTable', 'gcharttable', null, vTaskLeftPx); + this.setChartTable(vTmpTab); + this.newNode(vTmpDiv, 'div', null, 'rhscrpad', null, null, vTaskLeftPx+1); + vTmpTBody=this.newNode(vTmpTab, 'tbody'); - var i=0; - var j=0; - for(i=0; ivMinGpLen && vTaskWidthvMinGpLen && vTaskWidth=vMinGpLen*2) this.newNode(vTmpDiv, 'div', null, vTaskList[i].getClass() +'endpointright'); + this.newNode(vTmpDiv2, 'div', vDivId+'complete_'+vID, vTaskList[i].getClass() +'complete', null, vTaskList[i].getCompStr()); - vCaptClass='ggroupcaption'; - } + this.newNode(vTmpDiv, 'div', null, vTaskList[i].getClass() +'endpointleft'); + if (vTaskWidth>=vMinGpLen*2) this.newNode(vTmpDiv, 'div', null, vTaskList[i].getClass() +'endpointright'); - if(!vSingleCell && !vComb) - { - vCellFormat=''; - for(j=0; j=(new Date()).getTime()) vTodayPx=JSGantt.getOffset(vMinDate, new Date(), vColWidth, vFormat); - else vTodayPx=-1; - this.DrawDependencies(); - } - }; //this.draw + if(vScrollTo.substr(0,2)=='px') + { + vScrollPx=parseInt(vScrollTo.substr(2)); + } + else + { + vScrollDate=JSGantt.parseDateStr(vScrollTo, this.getDateInputFormat()); + if(vFormat=='hour')vScrollDate.setMinutes(0,0,0); + else vScrollDate.setHours(0,0,0,0); + vScrollPx=JSGantt.getOffset(vMinDate, vScrollDate, vColWidth, vFormat); + } + this.getChartBody().scrollLeft=vScrollPx; + } - this.mouseOver=function(pObj1, pObj2) - { - if (this.getUseRowHlt()) - { - pObj1.className+=' gitemhighlight'; - pObj2.className+=' gitemhighlight'; - } - }; + if (vMinDate.getTime()<=(new Date()).getTime() && vMaxDate.getTime()>=(new Date()).getTime()) vTodayPx=JSGantt.getOffset(vMinDate, new Date(), vColWidth, vFormat); + else vTodayPx=-1; + this.DrawDependencies(); + } + }; //this.draw - this.mouseOut=function(pObj1, pObj2) - { - if (this.getUseRowHlt()) - { - pObj1.className=pObj1.className.replace(/(?:^|\s)gitemhighlight(?!\S)/g, ''); - pObj2.className=pObj2.className.replace(/(?:^|\s)gitemhighlight(?!\S)/g, ''); - } - }; + this.mouseOver=function(pObj1, pObj2) + { + if (this.getUseRowHlt()) + { + pObj1.className+=' gitemhighlight'; + pObj2.className+=' gitemhighlight'; + } + }; - this.drawSelector=function(pPos) - { - var vOutput=document.createDocumentFragment(); - var vDisplay=false; + this.mouseOut=function(pObj1, pObj2) + { + if (this.getUseRowHlt()) + { + pObj1.className=pObj1.className.replace(/(?:^|\s)gitemhighlight(?!\S)/g, ''); + pObj2.className=pObj2.className.replace(/(?:^|\s)gitemhighlight(?!\S)/g, ''); + } + }; - for (var i=0; i=0 && vIdx'; - vTask+=''+vTaskList[vIdx].getName()+''; - vTask+=''+JSGantt.formatDateStr(vTaskList[vIdx].getStart(),vOutFrmt,vLangs[vLang])+''; - vTask+=''+JSGantt.formatDateStr(vTaskList[vIdx].getEnd(),vOutFrmt,vLangs[vLang])+''; - vTask+=''+vTaskList[vIdx].getClass()+''; - vTask+=''+vTaskList[vIdx].getLink()+''; - vTask+=''+vTaskList[vIdx].getMile()+''; - if(vTaskList[vIdx].getResource()!='\u00A0') vTask+=''+vTaskList[vIdx].getResource()+''; - vTask+=''+vTaskList[vIdx].getCompVal()+''; - vTask+=''+vTaskList[vIdx].getGroup()+''; - vTask+=''+vTaskList[vIdx].getParent()+''; - vTask+=''+vTaskList[vIdx].getOpen()+''; - vTask+=''; - var vDepList=vTaskList[vIdx].getDepend(); - for (i=0;i0)vTask+=','; - if(vDepList[i]>0)vTask+=vDepList[i]+vTaskList[vIdx].getDepType()[i]; - } - vTask+=''; - vTask+=''+vTaskList[vIdx].getCaption()+''; + this.getXMLProject=function() + { + var vProject=''; + for (var i=0; i'; - vTask+=''; - } - return vTask; - }; - if (vDiv && vDiv.nodeName.toLowerCase()=='div') vDivId=vDiv.id; + this.getXMLTask=function(pID,pIdx) + { + var i=0; + var vIdx=-1; + var vTask=''; + var vOutFrmt=JSGantt.parseDateFormatStr(this.getDateInputFormat()+' HH:MI'); + if (pIdx===true)vIdx=pID; + else + { + for (i=0; i=0 && vIdx'; + vTask+=''+vTaskList[vIdx].getName()+''; + vTask+=''+JSGantt.formatDateStr(vTaskList[vIdx].getStart(),vOutFrmt,vLangs[vLang])+''; + vTask+=''+JSGantt.formatDateStr(vTaskList[vIdx].getEnd(),vOutFrmt,vLangs[vLang])+''; + vTask+=''+vTaskList[vIdx].getClass()+''; + vTask+=''+vTaskList[vIdx].getLink()+''; + vTask+=''+vTaskList[vIdx].getMile()+''; + if(vTaskList[vIdx].getResource()!='\u00A0') vTask+=''+vTaskList[vIdx].getResource()+''; + vTask+=''+vTaskList[vIdx].getCompVal()+''; + vTask+=''+vTaskList[vIdx].getGroup()+''; + vTask+=''+vTaskList[vIdx].getParent()+''; + vTask+=''+vTaskList[vIdx].getOpen()+''; + vTask+=''; + var vDepList=vTaskList[vIdx].getDepend(); + for (i=0;i0)vTask+=','; + if(vDepList[i]>0)vTask+=vDepList[i]+vTaskList[vIdx].getDepType()[i]; + } + vTask+=''; + vTask+=''+vTaskList[vIdx].getCaption()+''; + + var vTmpFrag=document.createDocumentFragment(); + var vTmpDiv=this.newNode(vTmpFrag, 'div', null, null,vTaskList[vIdx].getNotes().innerHTML); + vTask+=''+vTmpDiv.innerHTML+''; + vTask+=''; + } + return vTask; + }; + if (vDiv && vDiv.nodeName.toLowerCase()=='div') vDivId=vDiv.id; }; //GanttChart JSGantt.updateFlyingObj=function (e, pGanttChartObj, pTimer) { - var vCurTopBuf=3; - var vCurLeftBuf=5; - var vCurBotBuf=3; - var vCurRightBuf=15; - var vMouseX=(e)?e.clientX:window.event.clientX; - var vMouseY=(e)?e.clientY:window.event.clientY; - var vViewportX=document.documentElement.clientWidth||document.getElementsByTagName('body')[0].clientWidth; - var vViewportY=document.documentElement.clientHeight||document.getElementsByTagName('body')[0].clientHeight; - var vNewX=vMouseX; - var vNewY=vMouseY; + var vCurTopBuf=3; + var vCurLeftBuf=5; + var vCurBotBuf=3; + var vCurRightBuf=15; + var vMouseX=(e)?e.clientX:window.event.clientX; + var vMouseY=(e)?e.clientY:window.event.clientY; + var vViewportX=document.documentElement.clientWidth||document.getElementsByTagName('body')[0].clientWidth; + var vViewportY=document.documentElement.clientHeight||document.getElementsByTagName('body')[0].clientHeight; + var vNewX=vMouseX; + var vNewY=vMouseY; - if (navigator.appName.toLowerCase ()=='microsoft internet explorer') { - // the clientX and clientY properties include the left and top borders of the client area - vMouseX-=document.documentElement.clientLeft; - vMouseY-=document.documentElement.clientTop; + if (navigator.appName.toLowerCase ()=='microsoft internet explorer') { + // the clientX and clientY properties include the left and top borders of the client area + vMouseX-=document.documentElement.clientLeft; + vMouseY-=document.documentElement.clientTop; - var vZoomFactor=JSGantt.getZoomFactor (); - if (vZoomFactor!=1) {// IE 7 at non-default zoom level - vMouseX=Math.round (vMouseX / vZoomFactor); - vMouseY=Math.round (vMouseY / vZoomFactor); - } - } + var vZoomFactor=JSGantt.getZoomFactor (); + if (vZoomFactor!=1) {// IE 7 at non-default zoom level + vMouseX=Math.round (vMouseX / vZoomFactor); + vMouseY=Math.round (vMouseY / vZoomFactor); + } + } - var vScrollPos=JSGantt.getScrollPositions(); + var vScrollPos=JSGantt.getScrollPositions(); - /* Code for positioned right of the mouse by default*/ - /* - if (vMouseX+vCurRightBuf+pGanttChartObj.vTool.offsetWidth>vViewportX) - { - if (vMouseX-vCurLeftBuf-pGanttChartObj.vTool.offsetWidth<0) vNewX=vScrollPos.x; - else vNewX=vMouseX+vScrollPos.x-vCurLeftBuf-pGanttChartObj.vTool.offsetWidth; - } - else vNewX=vMouseX+vScrollPos.x+vCurRightBuf; - */ + /* Code for positioned right of the mouse by default*/ + /* + if (vMouseX+vCurRightBuf+pGanttChartObj.vTool.offsetWidth>vViewportX) + { + if (vMouseX-vCurLeftBuf-pGanttChartObj.vTool.offsetWidth<0) vNewX=vScrollPos.x; + else vNewX=vMouseX+vScrollPos.x-vCurLeftBuf-pGanttChartObj.vTool.offsetWidth; + } + else vNewX=vMouseX+vScrollPos.x+vCurRightBuf; + */ - /* Code for positioned left of the mouse by default */ - if (vMouseX-vCurLeftBuf-pGanttChartObj.vTool.offsetWidth<0) - { - if (vMouseX+vCurRightBuf+pGanttChartObj.vTool.offsetWidth>vViewportX) vNewX=vScrollPos.x; - else vNewX=vMouseX+vScrollPos.x+vCurRightBuf; - } - else vNewX=vMouseX+vScrollPos.x-vCurLeftBuf-pGanttChartObj.vTool.offsetWidth; + /* Code for positioned left of the mouse by default */ + if (vMouseX-vCurLeftBuf-pGanttChartObj.vTool.offsetWidth<0) + { + if (vMouseX+vCurRightBuf+pGanttChartObj.vTool.offsetWidth>vViewportX) vNewX=vScrollPos.x; + else vNewX=vMouseX+vScrollPos.x+vCurRightBuf; + } + else vNewX=vMouseX+vScrollPos.x-vCurLeftBuf-pGanttChartObj.vTool.offsetWidth; - /* Code for positioned below the mouse by default */ - if (vMouseY+vCurBotBuf+pGanttChartObj.vTool.offsetHeight>vViewportY) - { - if (vMouseY-vCurTopBuf-pGanttChartObj.vTool.offsetHeight<0) vNewY=vScrollPos.y; - else vNewY=vMouseY+vScrollPos.y-vCurTopBuf-pGanttChartObj.vTool.offsetHeight; - } - else vNewY=vMouseY+vScrollPos.y+vCurBotBuf; + /* Code for positioned below the mouse by default */ + if (vMouseY+vCurBotBuf+pGanttChartObj.vTool.offsetHeight>vViewportY) + { + if (vMouseY-vCurTopBuf-pGanttChartObj.vTool.offsetHeight<0) vNewY=vScrollPos.y; + else vNewY=vMouseY+vScrollPos.y-vCurTopBuf-pGanttChartObj.vTool.offsetHeight; + } + else vNewY=vMouseY+vScrollPos.y+vCurBotBuf; - /* Code for positioned above the mouse by default */ - /* - if (vMouseY-vCurTopBuf-pGanttChartObj.vTool.offsetHeight<0) - { - if (vMouseY+vCurBotBuf+pGanttChartObj.vTool.offsetHeight>vViewportY) vNewY=vScrollPos.y; - else vNewY=vMouseY+vScrollPos.y+vCurBotBuf; - } - else vNewY=vMouseY+vScrollPos.y-vCurTopBuf-pGanttChartObj.vTool.offsetHeight; - */ + /* Code for positioned above the mouse by default */ + /* + if (vMouseY-vCurTopBuf-pGanttChartObj.vTool.offsetHeight<0) + { + if (vMouseY+vCurBotBuf+pGanttChartObj.vTool.offsetHeight>vViewportY) vNewY=vScrollPos.y; + else vNewY=vMouseY+vScrollPos.y+vCurBotBuf; + } + else vNewY=vMouseY+vScrollPos.y-vCurTopBuf-pGanttChartObj.vTool.offsetHeight; + */ - if (pGanttChartObj.getUseMove()) - { - clearInterval(pGanttChartObj.vTool.moveInterval); - pGanttChartObj.vTool.moveInterval=setInterval(function(){JSGantt.moveToolTip(vNewX, vNewY, pGanttChartObj.vTool, pTimer);},pTimer); - } - else - { - pGanttChartObj.vTool.style.left=vNewX +'px'; - pGanttChartObj.vTool.style.top=vNewY +'px'; - } + if (pGanttChartObj.getUseMove()) + { + clearInterval(pGanttChartObj.vTool.moveInterval); + pGanttChartObj.vTool.moveInterval=setInterval(function(){JSGantt.moveToolTip(vNewX, vNewY, pGanttChartObj.vTool, pTimer);},pTimer); + } + else + { + pGanttChartObj.vTool.style.left=vNewX +'px'; + pGanttChartObj.vTool.style.top=vNewY +'px'; + } }; JSGantt.showToolTip=function(pGanttChartObj, e, pContents, pWidth, pTimer){ - var vTtDivId=pGanttChartObj.getDivId()+'JSGanttToolTip'; - var vMaxW=500; - var vMaxAlpha=100; - var vShowing=pContents.id; + var vTtDivId=pGanttChartObj.getDivId()+'JSGanttToolTip'; + var vMaxW=500; + var vMaxAlpha=100; + var vShowing=pContents.id; - if(pGanttChartObj.getUseToolTip()) - { - if(pGanttChartObj.vTool==null){ - pGanttChartObj.vTool=document.createElement('div'); - pGanttChartObj.vTool.id=vTtDivId; - pGanttChartObj.vTool.className='JSGanttToolTip'; - pGanttChartObj.vTool.vToolCont=document.createElement('div'); - pGanttChartObj.vTool.vToolCont.id=vTtDivId+'cont'; - pGanttChartObj.vTool.vToolCont.className='JSGanttToolTipcont'; - pGanttChartObj.vTool.vToolCont.setAttribute('showing',''); - pGanttChartObj.vTool.appendChild(pGanttChartObj.vTool.vToolCont); - document.body.appendChild(pGanttChartObj.vTool); - pGanttChartObj.vTool.style.opacity=0; - pGanttChartObj.vTool.setAttribute('currentOpacity',0); - pGanttChartObj.vTool.setAttribute('fadeIncrement',10); - pGanttChartObj.vTool.setAttribute('moveSpeed',10); - pGanttChartObj.vTool.style.filter='alpha(opacity=0)'; - pGanttChartObj.vTool.style.visibility='hidden'; - pGanttChartObj.vTool.style.left=Math.floor(((e)?e.clientX:window.event.clientX)/2)+'px'; - pGanttChartObj.vTool.style.top=Math.floor(((e)?e.clientY:window.event.clientY)/2)+'px'; - JSGantt.addListener('mouseover', function () {clearTimeout(pGanttChartObj.vTool.delayTimeout);}, pGanttChartObj.vTool); - JSGantt.addListener('mouseout', function () {JSGantt.delayedHide(pGanttChartObj, pGanttChartObj.vTool, pTimer);}, pGanttChartObj.vTool); - } - clearTimeout(pGanttChartObj.vTool.delayTimeout); - if(pGanttChartObj.vTool.vToolCont.getAttribute('showing')!=vShowing || pGanttChartObj.vTool.style.visibility!='visible') - { - if (pGanttChartObj.vTool.vToolCont.getAttribute('showing')!=vShowing) - { - pGanttChartObj.vTool.vToolCont.setAttribute('showing',vShowing); + if(pGanttChartObj.getUseToolTip()) + { + if(pGanttChartObj.vTool==null){ + pGanttChartObj.vTool=document.createElement('div'); + pGanttChartObj.vTool.id=vTtDivId; + pGanttChartObj.vTool.className='JSGanttToolTip'; + pGanttChartObj.vTool.vToolCont=document.createElement('div'); + pGanttChartObj.vTool.vToolCont.id=vTtDivId+'cont'; + pGanttChartObj.vTool.vToolCont.className='JSGanttToolTipcont'; + pGanttChartObj.vTool.vToolCont.setAttribute('showing',''); + pGanttChartObj.vTool.appendChild(pGanttChartObj.vTool.vToolCont); + document.body.appendChild(pGanttChartObj.vTool); + pGanttChartObj.vTool.style.opacity=0; + pGanttChartObj.vTool.setAttribute('currentOpacity',0); + pGanttChartObj.vTool.setAttribute('fadeIncrement',10); + pGanttChartObj.vTool.setAttribute('moveSpeed',10); + pGanttChartObj.vTool.style.filter='alpha(opacity=0)'; + pGanttChartObj.vTool.style.visibility='hidden'; + pGanttChartObj.vTool.style.left=Math.floor(((e)?e.clientX:window.event.clientX)/2)+'px'; + pGanttChartObj.vTool.style.top=Math.floor(((e)?e.clientY:window.event.clientY)/2)+'px'; + JSGantt.addListener('mouseover', function () {clearTimeout(pGanttChartObj.vTool.delayTimeout);}, pGanttChartObj.vTool); + JSGantt.addListener('mouseout', function () {JSGantt.delayedHide(pGanttChartObj, pGanttChartObj.vTool, pTimer);}, pGanttChartObj.vTool); + } + clearTimeout(pGanttChartObj.vTool.delayTimeout); + if(pGanttChartObj.vTool.vToolCont.getAttribute('showing')!=vShowing || pGanttChartObj.vTool.style.visibility!='visible') + { + if (pGanttChartObj.vTool.vToolCont.getAttribute('showing')!=vShowing) + { + pGanttChartObj.vTool.vToolCont.setAttribute('showing',vShowing); - pGanttChartObj.vTool.vToolCont.innerHTML=pContents.innerHTML; - // as we are allowing arbitrary HTML we should remove any tag ids to prevent duplication - JSGantt.stripIds(pGanttChartObj.vTool.vToolCont); - } + pGanttChartObj.vTool.vToolCont.innerHTML=pContents.innerHTML; + // as we are allowing arbitrary HTML we should remove any tag ids to prevent duplication + JSGantt.stripIds(pGanttChartObj.vTool.vToolCont); + } - pGanttChartObj.vTool.style.visibility='visible'; - // Rather than follow the mouse just have it stay put - JSGantt.updateFlyingObj(e, pGanttChartObj, pTimer); - pGanttChartObj.vTool.style.width=(pWidth)? pWidth+'px' : 'auto'; - if(!pWidth && JSGantt.isIE()){ - pGanttChartObj.vTool.style.width=pGanttChartObj.vTool.offsetWidth; - } - if(pGanttChartObj.vTool.offsetWidth>vMaxW){pGanttChartObj.vTool.style.width=vMaxW+'px';} - } + pGanttChartObj.vTool.style.visibility='visible'; + // Rather than follow the mouse just have it stay put + JSGantt.updateFlyingObj(e, pGanttChartObj, pTimer); + pGanttChartObj.vTool.style.width=(pWidth)? pWidth+'px' : 'auto'; + if(!pWidth && JSGantt.isIE()){ + pGanttChartObj.vTool.style.width=pGanttChartObj.vTool.offsetWidth; + } + if(pGanttChartObj.vTool.offsetWidth>vMaxW){pGanttChartObj.vTool.style.width=vMaxW+'px';} + } - if (pGanttChartObj.getUseFade()) - { - clearInterval(pGanttChartObj.vTool.fadeInterval); - pGanttChartObj.vTool.fadeInterval=setInterval(function(){JSGantt.fadeToolTip(1, pGanttChartObj.vTool, vMaxAlpha);},pTimer); - } - else - { - pGanttChartObj.vTool.style.opacity=vMaxAlpha * 0.01; - pGanttChartObj.vTool.style.filter='alpha(opacity='+vMaxAlpha+')'; - } - } + if (pGanttChartObj.getUseFade()) + { + clearInterval(pGanttChartObj.vTool.fadeInterval); + pGanttChartObj.vTool.fadeInterval=setInterval(function(){JSGantt.fadeToolTip(1, pGanttChartObj.vTool, vMaxAlpha);},pTimer); + } + else + { + pGanttChartObj.vTool.style.opacity=vMaxAlpha * 0.01; + pGanttChartObj.vTool.style.filter='alpha(opacity='+vMaxAlpha+')'; + } + } }; JSGantt.stripIds=function(pNode){ - for(var i=0; i=0 && pList[i].getID()==pID)vCurItem=pList[i]; - } + for(i=0; i=0 && pList[i].getID()==pID)vCurItem=pList[i]; + } - for(i=0; ivMaxDate) - { - vMaxDate=pList[i].getEnd(); - vMaxSet=1; - } + if(vMaxSet==0 || pList[i].getEnd()>vMaxDate) + { + vMaxDate=pList[i].getEnd(); + vMaxSet=1; + } - vCompSum+=pList[i].getCompVal(); - pList[i].setSortIdx(i*pList.length); - } - } + vNumKid++; + vWeight+=pList[i].getEnd()-pList[i].getStart()+1; + vCompSum+=pList[i].getCompVal()*(pList[i].getEnd()-pList[i].getStart()+1); + pList[i].setSortIdx(i*pList.length); + } + } - if(pRow>=0) - { - if(pList[pRow].getGroupMinStart()!=null && pList[pRow].getGroupMinStart()=0) + { + if(pList[pRow].getGroupMinStart()!=null && pList[pRow].getGroupMinStart()vMaxDate) - { - vMaxDate=pList[pRow].getGroupMinEnd(); - } - pList[pRow].setStart(vMinDate); - pList[pRow].setEnd(vMaxDate); - pList[pRow].setNumKid(vNumKid); - pList[pRow].setCompVal(Math.ceil(vCompSum/vNumKid)); - } + if(pList[pRow].getGroupMinEnd()!=null && pList[pRow].getGroupMinEnd()>vMaxDate) + { + vMaxDate=pList[pRow].getGroupMinEnd(); + } + pList[pRow].setStart(vMinDate); + pList[pRow].setEnd(vMaxDate); + pList[pRow].setNumKid(vNumKid); + pList[pRow].setWeight(vWeight); + pList[pRow].setCompVal(Math.ceil(vCompSum/vWeight)); + } - if (pID==0 && pUseSort==1) - { - JSGantt.sortTasks(pList, 0, 0); - pList.sort(function(a,b){return a.getSortIdx()-b.getSortIdx();}); - } - if (pID==0 && pUseSort!=1) // Need to sort combined tasks regardless - { - for(i=0; i0) - { - sortArr.sort(function(a,b){ var i=a.getStart().getTime()-b.getStart().getTime(); - if (i==0) i=a.getEnd().getTime()-b.getEnd().getTime(); - if (i==0) return a.getID()-b.getID(); - else return i; }); - } + if (sortArr.length>0) + { + sortArr.sort(function(a,b){ var i=a.getStart().getTime()-b.getStart().getTime(); + if (i==0) i=a.getEnd().getTime()-b.getEnd().getTime(); + if (i==0) return a.getID()-b.getID(); + else return i; }); + } - for (var j=0; j1) vDate.setDate(vDate.getDate()-1); - } - else if (pFormat=='quarter') - { - vDate.setDate(vDate.getDate()-31); - if(vDate.getMonth()==0 || vDate.getMonth()==1 || vDate.getMonth()==2) - vDate.setFullYear(vDate.getFullYear(), 0, 1); - else if(vDate.getMonth()==3 || vDate.getMonth()==4 || vDate.getMonth()==5) - vDate.setFullYear(vDate.getFullYear(), 3, 1); - else if(vDate.getMonth()==6 || vDate.getMonth()==7 || vDate.getMonth()==8) - vDate.setFullYear(vDate.getFullYear(), 6, 1); - else if(vDate.getMonth()==9 || vDate.getMonth()==10 || vDate.getMonth()==11) - vDate.setFullYear(vDate.getFullYear(), 9, 1); - } - else if (pFormat=='hour') - { - vDate.setHours(vDate.getHours()-1); - while(vDate.getHours()%6!=0) vDate.setHours(vDate.getHours()-1); - } + // Adjust min date to specific format boundaries (first of week or first of month) + if (pFormat=='day') + { + vDate.setDate(vDate.getDate()-1); + while(vDate.getDay()%7!=1) vDate.setDate(vDate.getDate()-1); + } + else if (pFormat=='week') + { + vDate.setDate(vDate.getDate()-1); + while(vDate.getDay()%7!=1) vDate.setDate(vDate.getDate()-1); + } + else if (pFormat=='month') + { + vDate.setDate(vDate.getDate()-15); + while(vDate.getDate()>1) vDate.setDate(vDate.getDate()-1); + } + else if (pFormat=='quarter') + { + vDate.setDate(vDate.getDate()-31); + if(vDate.getMonth()==0 || vDate.getMonth()==1 || vDate.getMonth()==2) + vDate.setFullYear(vDate.getFullYear(), 0, 1); + else if(vDate.getMonth()==3 || vDate.getMonth()==4 || vDate.getMonth()==5) + vDate.setFullYear(vDate.getFullYear(), 3, 1); + else if(vDate.getMonth()==6 || vDate.getMonth()==7 || vDate.getMonth()==8) + vDate.setFullYear(vDate.getFullYear(), 6, 1); + else if(vDate.getMonth()==9 || vDate.getMonth()==10 || vDate.getMonth()==11) + vDate.setFullYear(vDate.getFullYear(), 9, 1); + } + else if (pFormat=='hour') + { + vDate.setHours(vDate.getHours()-1); + while(vDate.getHours()%6!=0) vDate.setHours(vDate.getHours()-1); + } - if(pFormat=='hour')vDate.setMinutes(0,0); - else vDate.setHours(0,0,0); - return(vDate); + if(pFormat=='hour')vDate.setMinutes(0,0); + else vDate.setHours(0,0,0); + return(vDate); }; // Used to determine the maximum date of all tasks and set upper bound based on format JSGantt.getMaxDate=function (pList, pFormat) { - var vDate=new Date(); + var vDate=new Date(); - vDate.setTime(pList[0].getEnd().getTime()); + vDate.setTime(pList[0].getEnd().getTime()); - // Parse all Task End dates to find max - for(var i=0; ivDate.getTime()) vDate.setTime(pList[i].getEnd().getTime()); - } + // Parse all Task End dates to find max + for(var i=0; ivDate.getTime()) vDate.setTime(pList[i].getEnd().getTime()); + } - // Adjust max date to specific format boundaries (end of week or end of month) - if (pFormat=='day') - { - vDate.setDate(vDate.getDate()+1); + // Adjust max date to specific format boundaries (end of week or end of month) + if (pFormat=='day') + { + vDate.setDate(vDate.getDate()+1); - while(vDate.getDay()%7!=0) vDate.setDate(vDate.getDate()+1); - } - else if (pFormat=='week') - { - //For weeks, what is the last logical boundary? - vDate.setDate(vDate.getDate()+1); + while(vDate.getDay()%7!=0) vDate.setDate(vDate.getDate()+1); + } + else if (pFormat=='week') + { + //For weeks, what is the last logical boundary? + vDate.setDate(vDate.getDate()+1); - while(vDate.getDay()%7!=0) vDate.setDate(vDate.getDate()+1); - } - else if (pFormat=='month') - { - // Set to last day of current Month - while(vDate.getDate()>1) vDate.setDate(vDate.getDate()+1); - vDate.setDate(vDate.getDate()-1); - } - else if (pFormat=='quarter') - { - // Set to last day of current Quarter - if(vDate.getMonth()==0 || vDate.getMonth()==1 || vDate.getMonth()==2) - vDate.setFullYear(vDate.getFullYear(), 2, 31); - else if(vDate.getMonth()==3 || vDate.getMonth()==4 || vDate.getMonth()==5) - vDate.setFullYear(vDate.getFullYear(), 5, 30); - else if(vDate.getMonth()==6 || vDate.getMonth()==7 || vDate.getMonth()==8) - vDate.setFullYear(vDate.getFullYear(), 8, 30); - else if(vDate.getMonth()==9 || vDate.getMonth()==10 || vDate.getMonth()==11) - vDate.setFullYear(vDate.getFullYear(), 11, 31); - } - else if (pFormat=='hour') - { - if(vDate.getHours()==0)vDate.setDate(vDate.getDate()+1); - vDate.setHours(vDate.getHours()+1); + while(vDate.getDay()%7!=0) vDate.setDate(vDate.getDate()+1); + } + else if (pFormat=='month') + { + // Set to last day of current Month + while(vDate.getDate()>1) vDate.setDate(vDate.getDate()+1); + vDate.setDate(vDate.getDate()-1); + } + else if (pFormat=='quarter') + { + // Set to last day of current Quarter + if(vDate.getMonth()==0 || vDate.getMonth()==1 || vDate.getMonth()==2) + vDate.setFullYear(vDate.getFullYear(), 2, 31); + else if(vDate.getMonth()==3 || vDate.getMonth()==4 || vDate.getMonth()==5) + vDate.setFullYear(vDate.getFullYear(), 5, 30); + else if(vDate.getMonth()==6 || vDate.getMonth()==7 || vDate.getMonth()==8) + vDate.setFullYear(vDate.getFullYear(), 8, 30); + else if(vDate.getMonth()==9 || vDate.getMonth()==10 || vDate.getMonth()==11) + vDate.setFullYear(vDate.getFullYear(), 11, 31); + } + else if (pFormat=='hour') + { + if(vDate.getHours()==0)vDate.setDate(vDate.getDate()+1); + vDate.setHours(vDate.getHours()+1); - while(vDate.getHours()%6!=5) vDate.setHours(vDate.getHours()+1); - } - return(vDate); + while(vDate.getHours()%6!=5) vDate.setHours(vDate.getHours()+1); + } + return(vDate); }; // This function finds the document id of the specified object JSGantt.findObj=function (theObj, theDoc) { - var p, i, foundObj; - if(!theDoc) theDoc=document; - if(document.getElementById) foundObj=document.getElementById(theObj); - return foundObj; + var p, i, foundObj; + if(!theDoc) theDoc=document; + if(document.getElementById) foundObj=document.getElementById(theObj); + return foundObj; }; JSGantt.changeFormat=function(pFormat,ganttObj) { - if(ganttObj) ganttObj.setFormat(pFormat); - else alert('Chart undefined'); + if(ganttObj) ganttObj.setFormat(pFormat); + else alert('Chart undefined'); }; // Function to open/close and hide/show children of specified task JSGantt.folder=function (pID,ganttObj) { - var vList=ganttObj.getList(); - var vDivId=ganttObj.getDivId(); + var vList=ganttObj.getList(); + var vDivId=ganttObj.getDivId(); - ganttObj.clearDependencies(); // clear these first so slow rendering doesn't look odd + ganttObj.clearDependencies(); // clear these first so slow rendering doesn't look odd - for(var i=0; i=52 && vMonthStr==1) vYear--; + if (vWeekNum==1 && vMonthStr==12) vYear++; + if (vWeekNum<10) vWeekNum='0'+vWeekNum; - - for (var i=0; i=52 && vMonthStr==1) vYear--; - if (vWeekNum==1 && vMonthStr==12) vYear++; - if (vWeekNum<10) vWeekNum='0'+vWeekNum; - - vDateStr+=vYear+'-W'+vWeekNum+'-'+vDayOfWeek; - break; - default: - if (pL[pDateFormatArr[i].toLowerCase()]) vDateStr+=pL[pDateFormatArr[i].toLowerCase()]; - else vDateStr+=pDateFormatArr[i]; - break; - } - } - return vDateStr; + vDateStr+=vYear+'-W'+vWeekNum+'-'+vDayOfWeek; + break; + default: + if (pL[pDateFormatArr[i].toLowerCase()]) vDateStr+=pL[pDateFormatArr[i].toLowerCase()]; + else vDateStr+=pDateFormatArr[i]; + break; + } + } + return vDateStr; }; JSGantt.parseDateFormatStr=function(pFormatStr) { - var vDateStr=''; - var vComponantStr=''; - var vCurrChar=''; - var vSeparators=new RegExp('[\/\\ -.,\'":]'); - var vDateFormatArray=new Array(); + var vDateStr=''; + var vComponantStr=''; + var vCurrChar=''; + var vSeparators=new RegExp('[\/\\ -.,\'":]'); + var vDateFormatArray=new Array(); - for (var i=0; i0) project=projNode[0].getAttribute('xmlns'); + var projNode=JSGantt.findXMLNode(pXmlDoc,'Project'); + if (typeof projNode!='undefined' && projNode.length>0) project=projNode[0].getAttribute('xmlns'); - if(project=='http://schemas.microsoft.com/project') - { - vMSP=true; - pGanttVar.setDateInputFormat('yyyy-mm-dd'); - Task=JSGantt.findXMLNode(pXmlDoc,'Task'); - if (typeof Task=='undefined')n=0; - else n=Task.length; + if(project=='http://schemas.microsoft.com/project') + { + vMSP=true; + pGanttVar.setDateInputFormat('yyyy-mm-dd'); + Task=JSGantt.findXMLNode(pXmlDoc,'Task'); + if (typeof Task=='undefined')n=0; + else n=Task.length; - var resources=JSGantt.findXMLNode(pXmlDoc,'Resource'); - if (typeof resources=='undefined'){n=0; m=0;} - else m=resources.length; + var resources=JSGantt.findXMLNode(pXmlDoc,'Resource'); + if (typeof resources=='undefined'){n=0; m=0;} + else m=resources.length; - for(i=0;i0 && uid>0) res[uid]=resname; - } + if (resname.length>0 && uid>0) res[uid]=resname; + } - var assignments=JSGantt.findXMLNode(pXmlDoc,'Assignment'); - if (typeof assignments=='undefined') j=0; - else j=assignments.length; + var assignments=JSGantt.findXMLNode(pXmlDoc,'Assignment'); + if (typeof assignments=='undefined') j=0; + else j=assignments.length; - for(i=0;i0) - { - if (resUID>0) assRes[uid]=res[resUID]; - ass[uid]=assignments[i]; - } - } + if (uid>0) + { + if (resUID>0) assRes[uid]=res[resUID]; + ass[uid]=assignments[i]; + } + } - // Store information about parent UIDs in an easily searchable form - for(i=0;i0) pars[vOutlineNumber]=uid; - if (uid>maxPID)maxPID=uid; - } + if(uid!=0) var vOutlineNumber=JSGantt.getXMLNodeValue(Task[i],'OutlineNumber',2,'0'); + if (uid>0) pars[vOutlineNumber]=uid; + if (uid>maxPID)maxPID=uid; + } - for(i=0;i1) - { - vOutlineNumber=JSGantt.getXMLNodeValue(Task[i],'OutlineNumber',2,'0'); - pParent=pars[vOutlineNumber.substr(0, vOutlineNumber.lastIndexOf('.'))]; - } + var vOutlineLevel=JSGantt.getXMLNodeValue(Task[i],'OutlineLevel',1,0); + if (vOutlineLevel>1) + { + vOutlineNumber=JSGantt.getXMLNodeValue(Task[i],'OutlineNumber',2,'0'); + pParent=pars[vOutlineNumber.substr(0, vOutlineNumber.lastIndexOf('.'))]; + } - try {var pNotes=Task[i].getElementsByTagName('Notes')[0].childNodes[1].nodeValue; //this should be a CDATA node - } catch (error) - {pNotes ='';} + try {var pNotes=Task[i].getElementsByTagName('Notes')[0].childNodes[1].nodeValue; //this should be a CDATA node + } catch (error) + {pNotes ='';} - if(typeof assRes[pID]!='undefined') var pRes=assRes[pID]; - else pRes=''; + if(typeof assRes[pID]!='undefined') var pRes=assRes[pID]; + else pRes=''; - var predecessors=JSGantt.findXMLNode(Task[i],'PredecessorLink'); - if (typeof predecessors=='undefined') j=0; - else j=predecessors.length; - var pDepend=''; + var predecessors=JSGantt.findXMLNode(Task[i],'PredecessorLink'); + if (typeof predecessors=='undefined') j=0; + else j=predecessors.length; + var pDepend=''; - for(k=0;k0) - { - if (pDepend.length>0)pDepend+=','; - switch(depType) - { - case 0: pDepend+=depUID+'FF'; break; - case 1: pDepend+=depUID+'FS'; break; - case 2: pDepend+=depUID+'SF'; break; - case 3: pDepend+=depUID+'SS'; break; - default: pDepend+=depUID+'FS'; break; - } - } - } + if (depUID>0) + { + if (pDepend.length>0)pDepend+=','; + switch(depType) + { + case 0: pDepend+=depUID+'FF'; break; + case 1: pDepend+=depUID+'FS'; break; + case 2: pDepend+=depUID+'SF'; break; + case 3: pDepend+=depUID+'SS'; break; + default: pDepend+=depUID+'FS'; break; + } + } + } - var pOpen=1; - var pCaption=''; + var pOpen=1; + var pCaption=''; - if(pGroup>0) var pClass ='ggroupblack'; - else if(pMile>0) pClass ='gmilestone'; - else pClass ='gtaskblue'; + if(pGroup>0) var pClass ='ggroupblack'; + else if(pMile>0) pClass ='gmilestone'; + else pClass ='gtaskblue'; - // check for split tasks + // check for split tasks - var splits=JSGantt.findXMLNode(ass[pID],'TimephasedData'); - if (typeof splits=='undefined') j=0; - else j=splits.length; + var splits=JSGantt.findXMLNode(ass[pID],'TimephasedData'); + if (typeof splits=='undefined') j=0; + else j=splits.length; - var vSplitStart=pStart; - var vSplitEnd=pEnd; - var vSubCreated=false; - var vDepend=pDepend.replace(/,*[0-9]+[FS]F/g,''); + var vSplitStart=pStart; + var vSplitEnd=pEnd; + var vSubCreated=false; + var vDepend=pDepend.replace(/,*[0-9]+[FS]F/g,''); - for(k=0;k0) pClass ='ggroupblack'; - else if(pMile>0) pClass ='gmilestone'; - else pClass ='gtaskblue'; - } + if(pID!=0) + { + pName=JSGantt.getXMLNodeValue(Task[i],'pName',2,'No Task Name'); + pStart=JSGantt.getXMLNodeValue(Task[i],'pStart',2,''); + pEnd=JSGantt.getXMLNodeValue(Task[i],'pEnd',2,''); + pLink=JSGantt.getXMLNodeValue(Task[i],'pLink',2,''); + pMile=JSGantt.getXMLNodeValue(Task[i],'pMile',1,0); + pComp=JSGantt.getXMLNodeValue(Task[i],'pComp',1,0); + pGroup=JSGantt.getXMLNodeValue(Task[i],'pGroup',1,0); + pParent=JSGantt.getXMLNodeValue(Task[i],'pParent',1,0); + pRes=JSGantt.getXMLNodeValue(Task[i],'pRes',2,''); + pOpen=JSGantt.getXMLNodeValue(Task[i],'pOpen',1,1); + pDepend=JSGantt.getXMLNodeValue(Task[i],'pDepend',2,''); + pCaption=JSGantt.getXMLNodeValue(Task[i],'pCaption',2,''); + pNotes=JSGantt.getXMLNodeValue(Task[i],'pNotes',2,''); + pClass=JSGantt.getXMLNodeValue(Task[i],'pClass',2); + if (typeof pClass=='undefined') + { + if(pGroup>0) pClass ='ggroupblack'; + else if(pMile>0) pClass ='gmilestone'; + else pClass ='gtaskblue'; + } - // Finally add the task - pGanttVar.AddTaskItem(new JSGantt.TaskItem(pID, pName, pStart, pEnd, pClass, pLink, pMile, pRes, pComp, pGroup, pParent, pOpen, pDepend, pCaption, pNotes, pGanttVar)); - } - } - } + // Finally add the task + pGanttVar.AddTaskItem(new JSGantt.TaskItem(pID, pName, pStart, pEnd, pClass, pLink, pMile, pRes, pComp, pGroup, pParent, pOpen, pDepend, pCaption, pNotes, pGanttVar)); + } + } + } }; JSGantt.benchMark=function(pItem) { - var vEndTime=new Date().getTime(); - alert(pItem+': Elapsed time: '+((vEndTime-vBenchTime)/1000)+' seconds.'); - vBenchTime=new Date().getTime(); + var vEndTime=new Date().getTime(); + alert(pItem+': Elapsed time: '+((vEndTime-vBenchTime)/1000)+' seconds.'); + vBenchTime=new Date().getTime(); }; JSGantt.getIsoWeek=function(pDate){ - // We have to compare against the monday of the first week of the year containing 04 jan *not* 01/01 - // 60*60*24*1000=86400000 - var dayMiliseconds=86400000; - var keyDay=new Date(pDate.getFullYear(),0,4,0,0,0); - var keyDayOfWeek=(keyDay.getDay()==0) ? 6 : keyDay.getDay()-1; // define monday as 0 - var firstMondayYearTime=keyDay.getTime()-(keyDayOfWeek * dayMiliseconds); - var thisDate=new Date(pDate.getFullYear(), pDate.getMonth(),pDate.getDate(),0,0,0); // This at 00:00:00 - var thisTime=thisDate.getTime(); - var daysFromFirstMonday=Math.round(((thisTime-firstMondayYearTime) / dayMiliseconds)); - var lastWeek=99; - var thisWeek=99; + // We have to compare against the monday of the first week of the year containing 04 jan *not* 01/01 + // 60*60*24*1000=86400000 + var dayMiliseconds=86400000; + var keyDay=new Date(pDate.getFullYear(),0,4,0,0,0); + var keyDayOfWeek=(keyDay.getDay()==0) ? 6 : keyDay.getDay()-1; // define monday as 0 + var firstMondayYearTime=keyDay.getTime()-(keyDayOfWeek * dayMiliseconds); + var thisDate=new Date(pDate.getFullYear(), pDate.getMonth(),pDate.getDate(),0,0,0); // This at 00:00:00 + var thisTime=thisDate.getTime(); + var daysFromFirstMonday=Math.round(((thisTime-firstMondayYearTime) / dayMiliseconds)); + var lastWeek=99; + var thisWeek=99; - var firstMondayYear=new Date(firstMondayYearTime); + var firstMondayYear=new Date(firstMondayYearTime); - thisWeek=Math.ceil((daysFromFirstMonday+1)/7); + thisWeek=Math.ceil((daysFromFirstMonday+1)/7); - if (thisWeek<=0) thisWeek=JSGantt.getIsoWeek(new Date(pDate.getFullYear()-1,11,31,0,0,0)); - else if (thisWeek==53 && (new Date(pDate.getFullYear(),0,1,0,0,0)).getDay()!=4 && (new Date(pDate.getFullYear(),11,31,0,0,0)).getDay()!=4) thisWeek=1; - return thisWeek; + if (thisWeek<=0) thisWeek=JSGantt.getIsoWeek(new Date(pDate.getFullYear()-1,11,31,0,0,0)); + else if (thisWeek==53 && (new Date(pDate.getFullYear(),0,1,0,0,0)).getDay()!=4 && (new Date(pDate.getFullYear(),11,31,0,0,0)).getDay()!=4) thisWeek=1; + return thisWeek; }; JSGantt.addListener=function (eventName, handler, control) { - // Check if control is a string - if (control===String(control)) control=JSGantt.findObj(control); + // Check if control is a string + if (control===String(control)) control=JSGantt.findObj(control); - if(control.addEventListener) //Standard W3C - { - return control.addEventListener(eventName, handler, false); - } - else if (control.attachEvent) //IExplore - { - return control.attachEvent('on'+eventName, handler); - } - else - { - return false; - } + if(control.addEventListener) //Standard W3C + { + return control.addEventListener(eventName, handler, false); + } + else if (control.attachEvent) //IExplore + { + return control.attachEvent('on'+eventName, handler); + } + else + { + return false; + } }; JSGantt.addTooltipListeners=function(pGanttChart, pObj1, pObj2) { - JSGantt.addListener('mouseover', function (e) {JSGantt.showToolTip(pGanttChart, e, pObj2, null, pGanttChart.getTimer());}, pObj1); - JSGantt.addListener('mouseout', function (e) {JSGantt.delayedHide(pGanttChart, pGanttChart.vTool, pGanttChart.getTimer());}, pObj1); + JSGantt.addListener('mouseover', function (e) {JSGantt.showToolTip(pGanttChart, e, pObj2, null, pGanttChart.getTimer());}, pObj1); + JSGantt.addListener('mouseout', function (e) {JSGantt.delayedHide(pGanttChart, pGanttChart.vTool, pGanttChart.getTimer());}, pObj1); }; JSGantt.addThisRowListeners=function(pGanttChart, pObj1, pObj2) { - JSGantt.addListener('mouseover', function () {pGanttChart.mouseOver(pObj1, pObj2);}, pObj1); - JSGantt.addListener('mouseover', function () {pGanttChart.mouseOver(pObj1, pObj2);}, pObj2); - JSGantt.addListener('mouseout', function () {pGanttChart.mouseOut(pObj1, pObj2);}, pObj1); - JSGantt.addListener('mouseout', function () {pGanttChart.mouseOut(pObj1, pObj2);}, pObj2); + JSGantt.addListener('mouseover', function () {pGanttChart.mouseOver(pObj1, pObj2);}, pObj1); + JSGantt.addListener('mouseover', function () {pGanttChart.mouseOver(pObj1, pObj2);}, pObj2); + JSGantt.addListener('mouseout', function () {pGanttChart.mouseOut(pObj1, pObj2);}, pObj1); + JSGantt.addListener('mouseout', function () {pGanttChart.mouseOut(pObj1, pObj2);}, pObj2); }; JSGantt.addFolderListeners=function(pGanttChart, pObj, pID) { - JSGantt.addListener('click', function () {JSGantt.folder(pID, pGanttChart);}, pObj); + JSGantt.addListener('click', function () {JSGantt.folder(pID, pGanttChart);}, pObj); }; JSGantt.addFormatListeners=function(pGanttChart, pFormat, pObj) { - JSGantt.addListener('click', function () {JSGantt.changeFormat(pFormat, pGanttChart);}, pObj); + JSGantt.addListener('click', function () {JSGantt.changeFormat(pFormat, pGanttChart);}, pObj); }; JSGantt.addScrollListeners=function(pGanttChart) { - JSGantt.addListener('scroll', function () {pGanttChart.getChartBody().scrollTop=pGanttChart.getListBody().scrollTop;}, pGanttChart.getListBody()); - JSGantt.addListener('scroll', function () {pGanttChart.getListBody().scrollTop=pGanttChart.getChartBody().scrollTop;}, pGanttChart.getChartBody()); - JSGantt.addListener('scroll', function () {pGanttChart.getChartHead().scrollLeft=pGanttChart.getChartBody().scrollLeft;}, pGanttChart.getChartBody()); - JSGantt.addListener('scroll', function () {pGanttChart.getChartBody().scrollLeft=pGanttChart.getChartHead().scrollLeft;}, pGanttChart.getChartHead()); - JSGantt.addListener('resize', function () {pGanttChart.getChartHead().scrollLeft=pGanttChart.getChartBody().scrollLeft;}, window); - JSGantt.addListener('resize', function () {pGanttChart.getListBody().scrollTop=pGanttChart.getChartBody().scrollTop;}, window); + JSGantt.addListener('scroll', function () {pGanttChart.getChartBody().scrollTop=pGanttChart.getListBody().scrollTop;}, pGanttChart.getListBody()); + JSGantt.addListener('scroll', function () {pGanttChart.getListBody().scrollTop=pGanttChart.getChartBody().scrollTop;}, pGanttChart.getChartBody()); + JSGantt.addListener('scroll', function () {pGanttChart.getChartHead().scrollLeft=pGanttChart.getChartBody().scrollLeft;}, pGanttChart.getChartBody()); + JSGantt.addListener('scroll', function () {pGanttChart.getChartBody().scrollLeft=pGanttChart.getChartHead().scrollLeft;}, pGanttChart.getChartHead()); + JSGantt.addListener('resize', function () {pGanttChart.getChartHead().scrollLeft=pGanttChart.getChartBody().scrollLeft;}, window); + JSGantt.addListener('resize', function () {pGanttChart.getListBody().scrollTop=pGanttChart.getChartBody().scrollTop;}, window); }; diff --git a/htdocs/includes/jsgantt/jsgantt.min.js b/htdocs/includes/jsgantt/jsgantt.min.js deleted file mode 100644 index 9ec44995993..00000000000 --- a/htdocs/includes/jsgantt/jsgantt.min.js +++ /dev/null @@ -1,2 +0,0 @@ -var JSGantt;JSGantt||(JSGantt={});var vBenchTime=(new Date).getTime();JSGantt.isIE=function(){return"undefined"!=typeof document.all?"pageXOffset"in window?!1:!0:!1},JSGantt.TaskItem=function(t,e,n,a,o,i,s,r,l,d,u,h,c,f,p,m){var v,S,w,D,T,y=parseInt(document.createTextNode(t).data),L=document.createTextNode(e).data,N=new Date(0),G=new Date(0),M=null,J=null,k=document.createTextNode(o).data,C=document.createTextNode(i).data,I=parseInt(document.createTextNode(s).data),F=document.createTextNode(r).data,b=parseFloat(document.createTextNode(l).data),H=parseInt(document.createTextNode(d).data),x=document.createTextNode(u).data,E=2==H?1:parseInt(document.createTextNode(h).data),X=new Array,Y=new Array,O=document.createTextNode(f).data,R="",A=0,V=0,P=1,B=0,U=!1,j=null,W=null,q=m instanceof JSGantt.GanttChart?m:g,_=null,Q=null,z=null,K=null,Z=null;if(T=document.createElement("span"),T.className="gTaskNotes",null!=p&&(T.innerHTML=p,JSGantt.stripUnwanted(T)),null!=n&&""!=n&&(N=n instanceof Date?n:JSGantt.parseDateStr(document.createTextNode(n).data,q.getDateInputFormat()),M=N),null!=a&&""!=a&&(G=a instanceof Date?a:JSGantt.parseDateStr(document.createTextNode(a).data,q.getDateInputFormat()),J=G),null!=c)for(var $=c+"",tt=$.split(","),et=tt.length,nt=0;et>nt;nt++)-1!=tt[nt].toUpperCase().indexOf("SS")?(X[nt]=tt[nt].substring(0,tt[nt].toUpperCase().indexOf("SS")),Y[nt]="SS"):-1!=tt[nt].toUpperCase().indexOf("FF")?(X[nt]=tt[nt].substring(0,tt[nt].toUpperCase().indexOf("FF")),Y[nt]="FF"):-1!=tt[nt].toUpperCase().indexOf("SF")?(X[nt]=tt[nt].substring(0,tt[nt].toUpperCase().indexOf("SF")),Y[nt]="SF"):-1!=tt[nt].toUpperCase().indexOf("FS")?(X[nt]=tt[nt].substring(0,tt[nt].toUpperCase().indexOf("FS")),Y[nt]="FS"):(X[nt]=tt[nt],Y[nt]="FS");this.getID=function(){return y},this.getName=function(){return L},this.getStart=function(){return N},this.getEnd=function(){return G},this.getGroupMinStart=function(){return M},this.getGroupMinEnd=function(){return J},this.getClass=function(){return k},this.getLink=function(){return C},this.getMile=function(){return I},this.getDepend=function(){return X?X:null},this.getDepType=function(){return Y?Y:null},this.getCaption=function(){return O?O:""},this.getResource=function(){return F?F:" "},this.getCompVal=function(){return b?b:0},this.getCompStr=function(){return b?b+"%":""},this.getNotes=function(){return T},this.getSortIdx=function(){return B},this.getToDelete=function(){return U},this.getDuration=function(t,e){if(I)R="-";else{var n=new Date(this.getEnd().getTime()),a=null;switch(t){case"week":a="day";break;case"month":a="week";break;case"quarter":a="month";break;default:a=t}(n.getTime()-6e4*n.getTimezoneOffset())%864e5==0&&(n=new Date(n.getFullYear(),n.getMonth(),n.getDate()+1,n.getHours(),n.getMinutes(),n.getSeconds()));var o=JSGantt.getOffset(this.getStart(),n,999,a)/1e3;switch(Math.floor(o)!=o&&(o=Math.round(10*o)/10),a){case"hour":R=o+" "+(1!=o?e.hrs:e.hr);break;case"day":R=o+" "+(1!=o?e.dys:e.dy);break;case"week":R=o+" "+(1!=o?e.wks:e.wk);break;case"month":R=o+" "+(1!=o?e.mths:e.mth);break;case"quarter":R=o+" "+(1!=o?e.qtrs:e.qtr)}}return R},this.getParent=function(){return x},this.getGroup=function(){return H},this.getOpen=function(){return E},this.getLevel=function(){return A},this.getNumKids=function(){return V},this.getStartX=function(){return v},this.getStartY=function(){return S},this.getEndX=function(){return w},this.getEndY=function(){return D},this.getVisible=function(){return P},this.getParItem=function(){return j},this.getCellDiv=function(){return W},this.getBarDiv=function(){return _},this.getTaskDiv=function(){return Q},this.getChildRow=function(){return K},this.getListChildRow=function(){return z},this.getGroupSpan=function(){return Z},this.setStart=function(t){t instanceof Date&&(N=t)},this.setEnd=function(t){t instanceof Date&&(G=t)},this.setGroupMinStart=function(t){t instanceof Date&&(M=t)},this.setGroupMinEnd=function(t){t instanceof Date&&(J=t)},this.setLevel=function(t){A=parseInt(document.createTextNode(t).data)},this.setNumKid=function(t){V=parseInt(document.createTextNode(t).data)},this.setCompVal=function(t){b=parseFloat(document.createTextNode(t).data)},this.setStartX=function(t){v=parseInt(document.createTextNode(t).data)},this.setStartY=function(t){S=parseInt(document.createTextNode(t).data)},this.setEndX=function(t){w=parseInt(document.createTextNode(t).data)},this.setEndY=function(t){D=parseInt(document.createTextNode(t).data)},this.setOpen=function(t){E=parseInt(document.createTextNode(t).data)},this.setVisible=function(t){P=parseInt(document.createTextNode(t).data)},this.setSortIdx=function(t){B=parseInt(document.createTextNode(t).data)},this.setToDelete=function(t){U=t?!0:!1},this.setParItem=function(t){t instanceof JSGantt.TaskItem&&(j=t)},this.setCellDiv=function(t){("function"!=typeof HTMLDivElement||t instanceof HTMLDivElement)&&(W=t)},this.setGroup=function(t){H=parseInt(document.createTextNode(t).data)},this.setBarDiv=function(t){("function"!=typeof HTMLDivElement||t instanceof HTMLDivElement)&&(_=t)},this.setTaskDiv=function(t){("function"!=typeof HTMLDivElement||t instanceof HTMLDivElement)&&(Q=t)},this.setChildRow=function(t){("function"!=typeof HTMLTableRowElement||t instanceof HTMLTableRowElement)&&(K=t)},this.setListChildRow=function(t){("function"!=typeof HTMLTableRowElement||t instanceof HTMLTableRowElement)&&(z=t)},this.setGroupSpan=function(t){("function"!=typeof HTMLSpanElement||t instanceof HTMLSpanElement)&&(Z=t)}},JSGantt.GanttChart=function(t,e){var n,a=t,o=e,i=null,s=1,r=1,l=1,g=1,d=1,u=25e3,h=1,c=1,f=1,p=1,m=1,v=1,S=1,w=1,D=1,T=1,y=1,L=1,N=1,G=1,M=new Array("top"),J="yyyy-mm-dd",k=JSGantt.parseDateFormatStr("dd/mm/yyyy"),C=JSGantt.parseDateFormatStr("dd month yyyy"),I=JSGantt.parseDateFormatStr("day dd month yyyy"),F=JSGantt.parseDateFormatStr("HH"),b=JSGantt.parseDateFormatStr("dd/mm/yyyy"),H=JSGantt.parseDateFormatStr("dd"),x=JSGantt.parseDateFormatStr("yyyy"),E=JSGantt.parseDateFormatStr("dd/mm"),X=JSGantt.parseDateFormatStr("yyyy"),Y=JSGantt.parseDateFormatStr("mon"),O=JSGantt.parseDateFormatStr("yyyy"),R=JSGantt.parseDateFormatStr("qq"),A=(JSGantt.parseDateFormatStr("dd/mm/yyyy"),1),V=new Array,P=new Array("hour","day","week","month","quarter"),B=(new Array(31,28,31,30,31,30,31,31,30,31,30,31),!0),U=8,j="",W=18,q=18,_=36,Q=36,z=18,K=20,Z=-1,$=null,tt=null,et=null,nt=null,at=null,ot=20;this.setUseFade=function(t){s=t},this.setUseMove=function(t){r=t},this.setUseRowHlt=function(t){l=t},this.setUseToolTip=function(t){g=t},this.setUseSort=function(t){d=t},this.setUseSingleCell=function(t){u=1*t},this.setFormatArr=function(){var t="hour day week month quarter";P=new Array;for(var e=0,n=0;e1){P[n++]=arguments[e].toLowerCase();var a=new RegExp("(?:^|s)"+arguments[e]+"(?!S)","g");t=t.replace(a,"")}},this.setShowRes=function(t){h=t},this.setShowDur=function(t){c=t},this.setShowComp=function(t){f=t},this.setShowStartDate=function(t){p=t},this.setShowEndDate=function(t){m=t},this.setShowTaskInfoRes=function(t){S=t},this.setShowTaskInfoDur=function(t){w=t},this.setShowTaskInfoComp=function(t){D=t},this.setShowTaskInfoStartDate=function(t){T=t},this.setShowTaskInfoEndDate=function(t){y=t},this.setShowTaskInfoNotes=function(t){L=t},this.setShowTaskInfoLink=function(t){N=t},this.setShowEndWeekDate=function(t){v=t},this.setShowSelector=function(){var t="top bottom";M=new Array;for(var e=0,n=0;e1){M[n++]=arguments[e].toLowerCase();var a=new RegExp("(?:^|s)"+arguments[e]+"(?!S)","g");t=t.replace(a,"")}},this.setShowDeps=function(t){G=t},this.setDateInputFormat=function(t){J=t},this.setDateTaskTableDisplayFormat=function(t){k=JSGantt.parseDateFormatStr(t)},this.setDateTaskDisplayFormat=function(t){C=JSGantt.parseDateFormatStr(t)},this.setHourMajorDateDisplayFormat=function(t){I=JSGantt.parseDateFormatStr(t)},this.setHourMinorDateDisplayFormat=function(t){F=JSGantt.parseDateFormatStr(t)},this.setDayMajorDateDisplayFormat=function(t){b=JSGantt.parseDateFormatStr(t)},this.setDayMinorDateDisplayFormat=function(t){H=JSGantt.parseDateFormatStr(t)},this.setWeekMajorDateDisplayFormat=function(t){x=JSGantt.parseDateFormatStr(t)},this.setWeekMinorDateDisplayFormat=function(t){E=JSGantt.parseDateFormatStr(t)},this.setMonthMajorDateDisplayFormat=function(t){X=JSGantt.parseDateFormatStr(t)},this.setMonthMinorDateDisplayFormat=function(t){Y=JSGantt.parseDateFormatStr(t)},this.setQuarterMajorDateDisplayFormat=function(t){O=JSGantt.parseDateFormatStr(t)},this.setQuarterMinorDateDisplayFormat=function(t){R=JSGantt.parseDateFormatStr(t)},this.setCaptionType=function(t){n=t},this.setFormat=function(t){o=t,this.Draw()},this.setMinGpLen=function(t){U=t},this.setScrollTo=function(t){j=t},this.setHourColWidth=function(t){W=t},this.setDayColWidth=function(t){q=t},this.setWeekColWidth=function(t){_=t},this.setMonthColWidth=function(t){Q=t},this.setQuarterColWidth=function(t){z=t},this.setRowHeight=function(t){K=t},this.setLang=function(t){vLangs[t]&&(vLang=t)},this.setChartBody=function(t){("function"!=typeof HTMLDivElement||t instanceof HTMLDivElement)&&($=t)},this.setChartHead=function(t){("function"!=typeof HTMLDivElement||t instanceof HTMLDivElement)&&(tt=t)},this.setListBody=function(t){("function"!=typeof HTMLDivElement||t instanceof HTMLDivElement)&&(et=t)},this.setChartTable=function(t){("function"!=typeof HTMLTableElement||t instanceof HTMLTableElement)&&(nt=t)},this.setLines=function(t){("function"!=typeof HTMLDivElement||t instanceof HTMLDivElement)&&(at=t)},this.setTimer=function(t){ot=1*t},this.addLang=function(t,e){if(!vLangs[t]){vLangs[t]=new Object;for(var n in vLangs.en)vLangs[t][n]=e[n]?document.createTextNode(e[n]).data:vLangs.en[n]}},this.getDivId=function(){return i},this.getUseFade=function(){return s},this.getUseMove=function(){return r},this.getUseRowHlt=function(){return l},this.getUseToolTip=function(){return g},this.getUseSort=function(){return d},this.getUseSingleCell=function(){return u},this.getFormatArr=function(){return P},this.getShowRes=function(){return h},this.getShowDur=function(){return c},this.getShowComp=function(){return f},this.getShowStartDate=function(){return p},this.getShowEndDate=function(){return m},this.getShowTaskInfoRes=function(){return S},this.getShowTaskInfoDur=function(){return w},this.getShowTaskInfoComp=function(){return D},this.getShowTaskInfoStartDate=function(){return T},this.getShowTaskInfoEndDate=function(){return y},this.getShowTaskInfoNotes=function(){return L},this.getShowTaskInfoLink=function(){return N},this.getShowEndWeekDate=function(){return v},this.getShowSelector=function(){return M},this.getShowDeps=function(){return G},this.getDateInputFormat=function(){return J},this.getDateTaskTableDisplayFormat=function(){return k},this.getDateTaskDisplayFormat=function(){return C},this.getHourMajorDateDisplayFormat=function(){return I},this.getHourMinorDateDisplayFormat=function(){return F},this.getDayMajorDateDisplayFormat=function(){return b},this.getDayMinorDateDisplayFormat=function(){return H},this.getWeekMajorDateDisplayFormat=function(){return x},this.getWeekMinorDateDisplayFormat=function(){return E},this.getMonthMajorDateDisplayFormat=function(){return X},this.getMonthMinorDateDisplayFormat=function(){return Y},this.getQuarterMajorDateDisplayFormat=function(){return O},this.getQuarterMinorDateDisplayFormat=function(){return R},this.getCaptionType=function(){return n},this.getMinGpLen=function(){return U},this.getScrollTo=function(){return j},this.getHourColWidth=function(){return W},this.getDayColWidth=function(){return q},this.getWeekColWidth=function(){return _},this.getMonthColWidth=function(){return Q},this.getQuarterColWidth=function(){return z},this.getRowHeight=function(){return K},this.getChartBody=function(){return $},this.getChartHead=function(){return tt},this.getListBody=function(){return et},this.getChartTable=function(){return nt},this.getLines=function(){return at},this.getTimer=function(){return ot},this.CalcTaskXY=function(){for(var t,e,n,a,o=this.getList(),i=Math.floor(this.getRowHeight()/2),s=0;sa&&(g*=-1),o){case"SF":l*=-1,n>=t-10&&e!=a&&(r=!0),s=-1;break;case"SS":n>t?l*=-1:l=n-t-2*l;break;case"FF":n>=t&&(l=n-t+2*l),s=-1;break;default:t+10>=n&&e!=a&&(r=!0)}r?(this.sLine(t,e,t+l,e,i),this.sLine(t+l,e,t+l,a-g,i),this.sLine(t+l,a-g,n-2*l,a-g,i),this.sLine(n-2*l,a-g,n-2*l,a,i),this.sLine(n-2*l,a,n-1*s,a,i)):e!=a?(this.sLine(t,e,t+l,e,i),this.sLine(t+l,e,t+l,a,i),this.sLine(t+l,a,n-1*s,a,i)):this.sLine(t,e,n-1*s,a,i);var d=this.sLine(n,a,n-3-(0>s?1:0),a-3-(0>s?1:0),i+"Arw");d.style.width="0px",d.style.height="0px"},this.DrawDependencies=function(){if(1==this.getShowDeps()){this.CalcTaskXY(),this.clearDependencies();for(var t=this.getList(),e=0;e0&&1==t[e].getVisible())for(var i=0;o>i;i++){var s=this.getArrayLocationByID(n[i]);s>=0&&2!=t[s].getGroup()&&1==t[s].getVisible()&&("SS"==a[i]?this.drawDependency(t[s].getStartX()-1,t[s].getStartY(),t[e].getStartX()-1,t[e].getStartY(),"SS","gDepSS"):"FF"==a[i]?this.drawDependency(t[s].getEndX(),t[s].getEndY(),t[e].getEndX(),t[e].getEndY(),"FF","gDepFF"):"SF"==a[i]?this.drawDependency(t[s].getStartX()-1,t[s].getStartY(),t[e].getEndX(),t[e].getEndY(),"SF","gDepSF"):"FS"==a[i]&&this.drawDependency(t[s].getEndX(),t[s].getEndY(),t[e].getStartX()-1,t[e].getStartY(),"FS","gDepFS"))}}}Z>=0&&this.sLine(Z,0,Z,this.getChartTable().offsetHeight-1,"gCurDate")},this.getArrayLocationByID=function(t){for(var e=this.getList(),n=0;n0){B&&JSGantt.processRows(V,0,-1,1,1,this.getUseSort()),B=!1,e=JSGantt.getMinDate(V,o),t=JSGantt.getMaxDate(V,o),"day"==o?T=q:"week"==o?T=_:"month"==o?T=Q:"quarter"==o?T=z:"hour"==o&&(T=W);var y=document.createDocumentFragment(),L=this.newNode(y,"div",i+"glisthead","glistlbl gcontainercol"),N=this.newNode(L,"table",null,"gtasktableh"),G=this.newNode(N,"tbody"),M=this.newNode(G,"tr");this.newNode(M,"td",null,"gtasklist"," ");var J=this.newNode(M,"td",null,"gspanning gtaskname");J.appendChild(this.drawSelector("top")),1==h&&this.newNode(M,"td",null,"gspanning gresource"," "),1==c&&this.newNode(M,"td",null,"gspanning gduration"," "),1==f&&this.newNode(M,"td",null,"gspanning gpccomplete"," "),1==p&&this.newNode(M,"td",null,"gspanning gstartdate"," "),1==m&&this.newNode(M,"td",null,"gspanning genddate"," "),M=this.newNode(G,"tr"),this.newNode(M,"td",null,"gtasklist"," "),this.newNode(M,"td",null,"gtaskname"," "),1==h&&this.newNode(M,"td",null,"gtaskheading gresource",vLangs[vLang].resource),1==c&&this.newNode(M,"td",null,"gtaskheading gduration",vLangs[vLang].duration),1==f&&this.newNode(M,"td",null,"gtaskheading gpccomplete",vLangs[vLang].comp),1==p&&this.newNode(M,"td",null,"gtaskheading gstartdate",vLangs[vLang].startdate),1==m&&this.newNode(M,"td",null,"gtaskheading genddate",vLangs[vLang].enddate),L=this.newNode(y,"div",null,"glabelfooter");var C=document.createDocumentFragment(),A=this.newNode(C,"div",i+"glistbody","glistgrid gcontainercol");for(this.setListBody(A),N=this.newNode(A,"table",null,"gtasktable"),G=this.newNode(N,"tbody"),st=0;st=n&&(J=this.newNode(M,"td",null,at),this.newNode(J,"div",null,null,JSGantt.formatDateStr(n,H,vLangs[vLang]),T),g++),n.setDate(n.getDate()+1);else if("week"==o)t>=n&&(J=this.newNode(M,"td",null,at),this.newNode(J,"div",null,null,JSGantt.formatDateStr(n,E,vLangs[vLang]),T),g++),n.setDate(n.getDate()+7);else if("month"==o)for(t>=n&&(J=this.newNode(M,"td",null,at),this.newNode(J,"div",null,null,JSGantt.formatDateStr(n,Y,vLangs[vLang]),T),g++),n.setDate(n.getDate()+1);n.getDate()>1;)n.setDate(n.getDate()+1);else if("quarter"==o)for(t>=n&&(J=this.newNode(M,"td",null,at),this.newNode(J,"div",null,null,JSGantt.formatDateStr(n,R,vLangs[vLang]),T),g++),n.setDate(n.getDate()+81);n.getDate()>1;)n.setDate(n.getDate()+1);else if("hour"==o){for(st=n.getHours();24>st;st++)n.setHours(st),t>=n&&(J=this.newNode(M,"td",null,at),this.newNode(J,"div",null,null,JSGantt.formatDateStr(n,F,vLangs[vLang]),T),g++);n.setHours(0),n.setDate(n.getDate()+1)}}D=M,s=g*(T+1)+1,0!=u&&g*d>u&&(S=!0),this.newNode(L,"div",null,"rhscrpad",null,null,s+1);var it=document.createDocumentFragment();L=this.newNode(it,"div",i+"gchartbody","gchartgrid gcontainercol"),this.setChartBody(L),N=this.newNode(L,"table",i+"chartTable","gcharttable",null,s),this.setChartTable(N),this.newNode(L,"div",null,"rhscrpad",null,null,s+1),G=this.newNode(N,"tbody");var st=0,rt=0;for(st=0;strt;rt++)ut="day"!=o||rt%7!=4&&rt%7!=5?"gtaskcell":"gtaskcellwkend",this.newNode(M,"td",null,ut,"  ")}else if(l=r-1,V[st].getGroup()){if(l=l>U&&2*U>l?2*U:l,l=U>l?U:l,M=this.newNode(G,"tr",i+"childrow_"+w,(2==V[st].getGroup()?"glineitem gitem":"ggroupitem ggroup")+o,null,null,null,0==V[st].getVisible()?"none":null),V[st].setChildRow(M),JSGantt.addThisRowListeners(this,V[st].getListChildRow(),M),J=this.newNode(M,"td",null,"gtaskcell"),L=this.newNode(J,"div",null,"gtaskcelldiv","  "),V[st].setCellDiv(L),1==V[st].getGroup()&&(L=this.newNode(L,"div",i+"bardiv_"+w,"gtaskbarcontainer",null,l,s),V[st].setBarDiv(L),A=this.newNode(L,"div",i+"taskbar_"+w,V[st].getClass(),null,l),V[st].setTaskDiv(A),this.newNode(A,"div",i+"complete_"+w,V[st].getClass()+"complete",null,V[st].getCompStr()),this.newNode(L,"div",null,V[st].getClass()+"endpointleft"),l>=2*U&&this.newNode(L,"div",null,V[st].getClass()+"endpointright"),ft="ggroupcaption"),!S&&!dt)for(ut="",rt=0;g-1>rt;rt++)ut="day"!=o||rt%7!=4&&rt%7!=5?"gtaskcell":"gtaskcellwkend",this.newNode(M,"td",null,ut,"  ")}else if(l=0>=l?1:l,dt?L=V[st].getParItem().getCellDiv():(M=this.newNode(G,"tr",i+"childrow_"+w,"glineitem gitem"+o,null,null,null,0==V[st].getVisible()?"none":null),V[st].setChildRow(M),JSGantt.addThisRowListeners(this,V[st].getListChildRow(),M),J=this.newNode(M,"td",null,"gtaskcell"),L=this.newNode(J,"div",null,"gtaskcelldiv","  ")),L=this.newNode(L,"div",i+"bardiv_"+w,"gtaskbarcontainer",null,l,s),V[st].setBarDiv(L),A=this.newNode(L,"div",i+"taskbar_"+w,V[st].getClass(),null,l),V[st].setTaskDiv(A),this.newNode(A,"div",i+"complete_"+w,V[st].getClass()+"complete",null,V[st].getCompStr()),dt&&(ht=V[st].getParItem()),(!dt||dt&&V[st].getParItem().getEnd()==V[st].getEnd())&&(ft="gcaption"),!S&&!dt)for(ut="",rt=0;g-1>rt;rt++)ut="day"!=o||rt%7!=4&&rt%7!=5?"gtaskcell":"gtaskcellwkend",this.newNode(M,"td",null,ut,"  ");if(this.getCaptionType()&&null!==ft){switch(this.getCaptionType()){case"Caption":var ct=ht.getCaption();break;case"Resource":ct=ht.getResource();break;case"Duration":ct=ht.getDuration(o,vLangs[vLang]);break;case"Complete":ct=ht.getCompStr()}this.newNode(L,"div",null,ft,ct,120,"gmilecaption"==ft?12:0)}V[st].getTaskDiv()&&L&&(A=this.newNode(L,"div",i+"tt"+w,null,null,null,null,"none"),A.appendChild(this.createTaskInfo(V[st])),JSGantt.addTooltipListeners(this,V[st].getTaskDiv(),A))}for(S||G.appendChild(D.cloneNode(!0));a.hasChildNodes();)a.removeChild(a.firstChild);if(L=this.newNode(a,"div",null,"gchartcontainer"),L.appendChild(et),L.appendChild(y),L.appendChild(it),L.appendChild(C),this.newNode(L,"div",null,"ggridfooter"),A=this.newNode(this.getChartBody(),"div",i+"Lines","glinediv"),A.style.visibility="hidden",this.setLines(A),JSGantt.addScrollListeners(this),""!=j){var pt=new Date(e.getTime()),mt=0;"px"==j.substr(0,2)?mt=parseInt(j.substr(2)):(pt=JSGantt.parseDateStr(j,this.getDateInputFormat()),"hour"==o?pt.setMinutes(0,0,0):pt.setHours(0,0,0,0),mt=JSGantt.getOffset(e,pt,T,o)),this.getChartBody().scrollLeft=mt}Z=e.getTime()<=(new Date).getTime()&&t.getTime()>=(new Date).getTime()?JSGantt.getOffset(e,new Date,T,o):-1,this.DrawDependencies()}},this.mouseOver=function(t,e){this.getUseRowHlt()&&(t.className+=" gitemhighlight",e.className+=" gitemhighlight")},this.mouseOut=function(t,e){this.getUseRowHlt()&&(t.className=t.className.replace(/(?:^|\s)gitemhighlight(?!\S)/g,""),e.className=e.className.replace(/(?:^|\s)gitemhighlight(?!\S)/g,""))},this.drawSelector=function(t){for(var e=document.createDocumentFragment(),n=!1,a=0;a=0&&a",o+=""+V[a].getID()+"",o+=""+V[a].getName()+"",o+=""+JSGantt.formatDateStr(V[a].getStart(),i,vLangs[vLang])+"",o+=""+JSGantt.formatDateStr(V[a].getEnd(),i,vLangs[vLang])+"",o+=""+V[a].getClass()+"",o+=""+V[a].getLink()+"",o+=""+V[a].getMile()+""," "!=V[a].getResource()&&(o+=""+V[a].getResource()+""),o+=""+V[a].getCompVal()+"",o+=""+V[a].getGroup()+"",o+=""+V[a].getParent()+"",o+=""+V[a].getOpen()+"",o+="";var s=V[a].getDepend();for(n=0;n0&&(o+=","),s[n]>0&&(o+=s[n]+V[a].getDepType()[n]);o+="",o+=""+V[a].getCaption()+"";var r=document.createDocumentFragment(),l=this.newNode(r,"div",null,null,V[a].getNotes().innerHTML);o+=""+l.innerHTML+"",o+=""}return o},a&&"div"==a.nodeName.toLowerCase()&&(i=a.id)},JSGantt.updateFlyingObj=function(t,e,n){var a=3,o=5,i=3,s=15,r=t?t.clientX:window.event.clientX,l=t?t.clientY:window.event.clientY,g=document.documentElement.clientWidth||document.getElementsByTagName("body")[0].clientWidth,d=document.documentElement.clientHeight||document.getElementsByTagName("body")[0].clientHeight,u=r,h=l;if("microsoft internet explorer"==navigator.appName.toLowerCase()){r-=document.documentElement.clientLeft,l-=document.documentElement.clientTop;var c=JSGantt.getZoomFactor();1!=c&&(r=Math.round(r/c),l=Math.round(l/c))}var f=JSGantt.getScrollPositions();u=r-o-e.vTool.offsetWidth<0?r+s+e.vTool.offsetWidth>g?f.x:r+f.x+s:r+f.x-o-e.vTool.offsetWidth,h=l+i+e.vTool.offsetHeight>d?l-a-e.vTool.offsetHeight<0?f.y:l+f.y-a-e.vTool.offsetHeight:l+f.y+i,e.getUseMove()?(clearInterval(e.vTool.moveInterval),e.vTool.moveInterval=setInterval(function(){JSGantt.moveToolTip(u,h,e.vTool,n)},n)):(e.vTool.style.left=u+"px", - e.vTool.style.top=h+"px")},JSGantt.showToolTip=function(t,e,n,a,o){var i=t.getDivId()+"JSGanttToolTip",s=500,r=100,l=n.id;t.getUseToolTip()&&(null==t.vTool&&(t.vTool=document.createElement("div"),t.vTool.id=i,t.vTool.className="JSGanttToolTip",t.vTool.vToolCont=document.createElement("div"),t.vTool.vToolCont.id=i+"cont",t.vTool.vToolCont.className="JSGanttToolTipcont",t.vTool.vToolCont.setAttribute("showing",""),t.vTool.appendChild(t.vTool.vToolCont),document.body.appendChild(t.vTool),t.vTool.style.opacity=0,t.vTool.setAttribute("currentOpacity",0),t.vTool.setAttribute("fadeIncrement",10),t.vTool.setAttribute("moveSpeed",10),t.vTool.style.filter="alpha(opacity=0)",t.vTool.style.visibility="hidden",t.vTool.style.left=Math.floor((e?e.clientX:window.event.clientX)/2)+"px",t.vTool.style.top=Math.floor((e?e.clientY:window.event.clientY)/2)+"px",JSGantt.addListener("mouseover",function(){clearTimeout(t.vTool.delayTimeout)},t.vTool),JSGantt.addListener("mouseout",function(){JSGantt.delayedHide(t,t.vTool,o)},t.vTool)),clearTimeout(t.vTool.delayTimeout),(t.vTool.vToolCont.getAttribute("showing")!=l||"visible"!=t.vTool.style.visibility)&&(t.vTool.vToolCont.getAttribute("showing")!=l&&(t.vTool.vToolCont.setAttribute("showing",l),t.vTool.vToolCont.innerHTML=n.innerHTML,JSGantt.stripIds(t.vTool.vToolCont)),t.vTool.style.visibility="visible",JSGantt.updateFlyingObj(e,t,o),t.vTool.style.width=a?a+"px":"auto",!a&&JSGantt.isIE()&&(t.vTool.style.width=t.vTool.offsetWidth),t.vTool.offsetWidth>s&&(t.vTool.style.width=s+"px")),t.getUseFade()?(clearInterval(t.vTool.fadeInterval),t.vTool.fadeInterval=setInterval(function(){JSGantt.fadeToolTip(1,t.vTool,r)},o)):(t.vTool.style.opacity=.01*r,t.vTool.style.filter="alpha(opacity="+r+")"))},JSGantt.stripIds=function(t){for(var e=0;en-i&&1==t?s=n-i:a>o&&-1==t&&(s=i),o=i+s*t,e.style.opacity=.01*o,e.style.filter="alpha(opacity="+o+")",e.setAttribute("currentOpacity",o)}else clearInterval(e.fadeInterval),-1==t&&(e.style.opacity=0,e.style.filter="alpha(opacity=0)",e.style.visibility="hidden")},JSGantt.moveToolTip=function(t,e,n){var a=parseInt(n.getAttribute("moveSpeed")),o=parseInt(n.style.left),i=parseInt(n.style.top);"visible"!=n.style.visibility?(n.style.left=t+"px",n.style.top=e+"px",clearInterval(n.moveInterval)):t!=o&&e!=i?(o+=Math.ceil((t-o)/a),i+=Math.ceil((e-i)/a),n.style.left=o+"px",n.style.top=i+"px"):clearInterval(n.moveInterval)},JSGantt.getZoomFactor=function(){var t=1;if(document.body.getBoundingClientRect){var e=document.body.getBoundingClientRect(),n=e.right-e.left,a=document.body.offsetWidth;t=Math.round(n/a*100)/100}return t},JSGantt.getScrollPositions=function(){var t=window.pageXOffset,e=window.pageYOffset;if(!("pageXOffset"in window)){var n=JSGantt.getZoomFactor();t=Math.round(document.documentElement.scrollLeft/n),e=Math.round(document.documentElement.scrollTop/n)}return{x:t,y:e}},JSGantt.getOffset=function(t,e,n,a){var o=new Array(31,28,31,30,31,30,31,31,30,31,30,31),i=new Date(t.getTime()),s=new Date(e.getTime()),r=0,l=Date.UTC(i.getFullYear(),i.getMonth(),i.getDate(),i.getHours(),0,0),g=Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),0,0),d=(g-l)/36e5;if("day"==a)r=Math.ceil(d/24*(n+1));else if("week"==a)r=Math.ceil(d/24*(n+1)/7);else if("month"==a){var u=12*(s.getFullYear()-i.getFullYear())+(s.getMonth()-i.getMonth()),h=new Date(s.getTime());h.setDate(i.getDate());var c=(s.getTime()-h.getTime())/864e5;r=Math.ceil(u*(n+1)+c*(n/o[s.getMonth()]))}else if("quarter"==a)u=12*(s.getFullYear()-i.getFullYear())+(s.getMonth()-i.getMonth()),h=new Date(s.getTime()),h.setDate(i.getDate()),c=(s.getTime()-h.getTime())/864e5,r=Math.ceil(u*((n+1)/3)+c*(n/90));else if("hour"==a){h=new Date(s.getTime()),h.setMinutes(i.getMinutes(),0);var f=(s.getTime()-h.getTime())/36e5;r=Math.ceil(d*(n+1)+f*n)}return r},JSGantt.processRows=function(t,e,n,a,o,i){var s=new Date,r=new Date,l=o,g=null,d=0,u=0,h=0,c=0,f=a,p=t,m=!1,v=0;for(v=0;v=0&&t[v].getID()==e&&(g=t[v]);for(v=0;vr)&&(r=t[v].getEnd(),h=1),d+=t[v].getCompVal(),t[v].setSortIdx(v*t.length)}if(n>=0&&(null!=t[n].getGroupMinStart()&&t[n].getGroupMinStart()r&&(r=t[n].getGroupMinEnd()),t[n].setStart(s),t[n].setEnd(r),t[n].setNumKid(c),t[n].setCompVal(Math.ceil(d/c))),0==e&&1==i&&(JSGantt.sortTasks(t,0,0),t.sort(function(t,e){return t.getSortIdx()-e.getSortIdx()})),0==e&&1!=i){for(v=0;v0&&o.sort(function(t,e){var n=t.getStart().getTime()-e.getStart().getTime();return 0==n&&(n=t.getEnd().getTime()-e.getEnd().getTime()),0==n?t.getID()-e.getID():n});for(var s=0;s1;)n.setDate(n.getDate()-1);else if("quarter"==e)n.setDate(n.getDate()-31),0==n.getMonth()||1==n.getMonth()||2==n.getMonth()?n.setFullYear(n.getFullYear(),0,1):3==n.getMonth()||4==n.getMonth()||5==n.getMonth()?n.setFullYear(n.getFullYear(),3,1):6==n.getMonth()||7==n.getMonth()||8==n.getMonth()?n.setFullYear(n.getFullYear(),6,1):(9==n.getMonth()||10==n.getMonth()||11==n.getMonth())&&n.setFullYear(n.getFullYear(),9,1);else if("hour"==e)for(n.setHours(n.getHours()-1);n.getHours()%6!=0;)n.setHours(n.getHours()-1);return"hour"==e?n.setMinutes(0,0):n.setHours(0,0,0),n},JSGantt.getMaxDate=function(t,e){var n=new Date;n.setTime(t[0].getEnd().getTime());for(var a=0;an.getTime()&&n.setTime(t[a].getEnd().getTime());if("day"==e)for(n.setDate(n.getDate()+1);n.getDay()%7!=0;)n.setDate(n.getDate()+1);else if("week"==e)for(n.setDate(n.getDate()+1);n.getDay()%7!=0;)n.setDate(n.getDate()+1);else if("month"==e){for(;n.getDate()>1;)n.setDate(n.getDate()+1);n.setDate(n.getDate()-1)}else if("quarter"==e)0==n.getMonth()||1==n.getMonth()||2==n.getMonth()?n.setFullYear(n.getFullYear(),2,31):3==n.getMonth()||4==n.getMonth()||5==n.getMonth()?n.setFullYear(n.getFullYear(),5,30):6==n.getMonth()||7==n.getMonth()||8==n.getMonth()?n.setFullYear(n.getFullYear(),8,30):(9==n.getMonth()||10==n.getMonth()||11==n.getMonth())&&n.setFullYear(n.getFullYear(),11,31);else if("hour"==e)for(0==n.getHours()&&n.setDate(n.getDate()+1),n.setHours(n.getHours()+1);n.getHours()%6!=5;)n.setHours(n.getHours()+1);return n},JSGantt.findObj=function(t,e){var n;return e||(e=document),document.getElementById&&(n=document.getElementById(t)),n},JSGantt.changeFormat=function(t,e){e?e.setFormat(t):alert("Chart undefined")},JSGantt.folder=function(t,e){var n=e.getList();e.getDivId();e.clearDependencies();for(var a=0;a=10&&a.length>=3){for(;a.length<5;)a.push(0);switch(e){case"mm/dd/yyyy":n=new Date(a[2],a[0]-1,a[1],a[3],a[4]);break;case"dd/mm/yyyy":n=new Date(a[2],a[1]-1,a[0],a[3],a[4]);break;case"yyyy-mm-dd":n=new Date(a[0],a[1]-1,a[2],a[3],a[4])}}return n},JSGantt.formatDateStr=function(t,e,n){for(var a="",o=t.getFullYear().toString().substring(2,4),i=t.getMonth()+1+"",s=new Array(n.january,n.february,n.march,n.april,n.maylong,n.june,n.july,n.august,n.september,n.october,n.november,n.december),r=new Array(n.sunday,n.monday,n.tuesday,n.wednesday,n.thursday,n.friday,n.saturday),l=new Array(n.jan,n.feb,n.mar,n.apr,n.may,n.jun,n.jul,n.aug,n.sep,n.oct,n.nov,n.dec),g=new Array(n.sun,n.mon,n.tue,n.wed,n.thu,n.fri,n.sat),d=0;di&&(a+="0");case"m":a+=i;break;case"mon":a+=l[t.getMonth()];break;case"month":a+=s[t.getMonth()];break;case"yyyy":a+=t.getFullYear();break;case"yy":a+=o;break;case"qq":a+="Q";case"q":a+=Math.floor(t.getMonth()/3)+1;break;case"hh":(t.getHours()%12==0?12:t.getHours()%12)<10&&(a+="0");case"h":a+=t.getHours()%12==0?12:t.getHours()%12;break;case"HH":t.getHours()<10&&(a+="0");case"H":a+=t.getHours();break;case"MI":t.getMinutes()<10&&(a+="0");case"mi":a+=t.getMinutes();break;case"pm":a+=t.getHours()<12?"am":"pm";break;case"PM":a+=t.getHours()<12?"AM":"PM";break;case"ww":JSGantt.getIsoWeek(t)<10&&(a+="0");case"w":a+=JSGantt.getIsoWeek(t);break;case"week":var u=JSGantt.getIsoWeek(t),h=t.getFullYear(),c=0==t.getDay()?7:t.getDay();u>=52&&1==i&&h--,1==u&&12==i&&h++,10>u&&(u="0"+u),a+=h+"-W"+u+"-"+c;break;default:a+=n[e[d].toLowerCase()]?n[e[d].toLowerCase()]:e[d]}return a},JSGantt.parseDateFormatStr=function(t){for(var e="",n="",a=new RegExp("[/\\ -.,'\":]"),o=new Array,i=0;i0&&(a=p[0].getAttribute("xmlns")),"http://schemas.microsoft.com/project"==a){o=!0,t.setDateInputFormat("yyyy-mm-dd"),n=JSGantt.findXMLNode(e,"Task"),i="undefined"==typeof n?0:n.length;var m=JSGantt.findXMLNode(e,"Resource");for("undefined"==typeof m?(i=0,s=0):s=m.length,r=0;s>r;r++){var v=JSGantt.getXMLNodeValue(m[r],"Name",2,""),S=JSGantt.getXMLNodeValue(m[r],"UID",1,-1);v.length>0&&S>0&&(c[S]=v)}var w=JSGantt.findXMLNode(e,"Assignment");for(l="undefined"==typeof w?0:w.length,r=0;l>r;r++){var D=JSGantt.getXMLNodeValue(w[r],"ResourceUID",1,-1);S=JSGantt.getXMLNodeValue(w[r],"TaskUID",1,-1),S>0&&(D>0&&(h[S]=c[D]),u[S]=w[r])}for(r=0;i>r;r++){if(S=JSGantt.getXMLNodeValue(n[r],"UID",1,0),0!=S)var T=JSGantt.getXMLNodeValue(n[r],"OutlineNumber",2,"0");S>0&&(f[T]=S),S>d&&(d=S)}for(r=0;i>r;r++){var y=JSGantt.getXMLNodeValue(n[r],"UID",1,0);if(0!=y){var L=JSGantt.getXMLNodeValue(n[r],"Name",2,"No Task Name"),N=JSGantt.getXMLNodeValue(n[r],"Start",2,""),G=JSGantt.getXMLNodeValue(n[r],"Finish",2,""),M=JSGantt.getXMLNodeValue(n[r],"HyperlinkAddress",2,""),J=JSGantt.getXMLNodeValue(n[r],"Milestone",1,0),k=JSGantt.getXMLNodeValue(n[r],"PercentWorkComplete",1,0),C=JSGantt.getXMLNodeValue(n[r],"Summary",1,0),I=0,F=JSGantt.getXMLNodeValue(n[r],"OutlineLevel",1,0);F>1&&(T=JSGantt.getXMLNodeValue(n[r],"OutlineNumber",2,"0"),I=f[T.substr(0,T.lastIndexOf("."))]);try{var b=n[r].getElementsByTagName("Notes")[0].childNodes[1].nodeValue}catch(H){b=""}if("undefined"!=typeof h[y])var x=h[y];else x="";var E=JSGantt.findXMLNode(n[r],"PredecessorLink");l="undefined"==typeof E?0:E.length;var X="";for(g=0;l>g;g++){var Y=JSGantt.getXMLNodeValue(E[g],"PredecessorUID",1,-1),O=JSGantt.getXMLNodeValue(E[g],"Type",1,1);if(Y>0)switch(X.length>0&&(X+=","),O){case 0:X+=Y+"FF";break;case 1:X+=Y+"FS";break;case 2:X+=Y+"SF";break;case 3:X+=Y+"SS";break;default:X+=Y+"FS"}}var R=1,A="";if(C>0)var V="ggroupblack";else V=J>0?"gmilestone":"gtaskblue";var P=JSGantt.findXMLNode(u[y],"TimephasedData");l="undefined"==typeof P?0:P.length;var B=N,U=G,j=!1,W=X.replace(/,*[0-9]+[FS]F/g,"");for(g=0;l>g;g++){var q=JSGantt.getXMLNodeValue(P[g],"Value",2,"0");q="0"+q.replace(/\D/g,""),q*=1,0==q&&!j||g+1==l&&2==C?(C=2,g+1==l&&(W=X.replace(/,*[0-9]+[FS]S/g,"")),d++,U=JSGantt.getXMLNodeValue(P[g],g+1==l?"Finish":"Start",2,""),t.AddTaskItem(new JSGantt.TaskItem(d,L,B,U,"gtaskblue",M,J,x,k,0,y,R,W,A,b,t)),j=!0,W=""):0!=q&&j&&(B=JSGantt.getXMLNodeValue(P[g],"Start",2,""),j=!1)}j&&(X=""),t.AddTaskItem(new JSGantt.TaskItem(y,L,N,G,V,M,J,x,k,C,I,R,X,A,b,t))}}}else for(n=e.getElementsByTagName("task"),i=n.length,r=0;i>r;r++)y=JSGantt.getXMLNodeValue(n[r],"pID",1,0),0!=y&&(L=JSGantt.getXMLNodeValue(n[r],"pName",2,"No Task Name"),N=JSGantt.getXMLNodeValue(n[r],"pStart",2,""),G=JSGantt.getXMLNodeValue(n[r],"pEnd",2,""),M=JSGantt.getXMLNodeValue(n[r],"pLink",2,""),J=JSGantt.getXMLNodeValue(n[r],"pMile",1,0),k=JSGantt.getXMLNodeValue(n[r],"pComp",1,0),C=JSGantt.getXMLNodeValue(n[r],"pGroup",1,0),I=JSGantt.getXMLNodeValue(n[r],"pParent",1,0),x=JSGantt.getXMLNodeValue(n[r],"pRes",2,""),R=JSGantt.getXMLNodeValue(n[r],"pOpen",1,1),X=JSGantt.getXMLNodeValue(n[r],"pDepend",2,""),A=JSGantt.getXMLNodeValue(n[r],"pCaption",2,""),b=JSGantt.getXMLNodeValue(n[r],"pNotes",2,""),V=JSGantt.getXMLNodeValue(n[r],"pClass",2),"undefined"==typeof V&&(V=C>0?"ggroupblack":J>0?"gmilestone":"gtaskblue"),t.AddTaskItem(new JSGantt.TaskItem(y,L,N,G,V,M,J,x,k,C,I,R,X,A,b,t)))},JSGantt.benchMark=function(t){var e=(new Date).getTime();alert(t+": Elapsed time: "+(e-vBenchTime)/1e3+" seconds."),vBenchTime=(new Date).getTime()},JSGantt.getIsoWeek=function(t){var e=864e5,n=new Date(t.getFullYear(),0,4,0,0,0),a=0==n.getDay()?6:n.getDay()-1,o=n.getTime()-a*e,i=new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,0),s=i.getTime(),r=Math.round((s-o)/e),l=99;new Date(o);return l=Math.ceil((r+1)/7),0>=l?l=JSGantt.getIsoWeek(new Date(t.getFullYear()-1,11,31,0,0,0)):53==l&&4!=new Date(t.getFullYear(),0,1,0,0,0).getDay()&&4!=new Date(t.getFullYear(),11,31,0,0,0).getDay()&&(l=1),l},JSGantt.addListener=function(t,e,n){return n===String(n)&&(n=JSGantt.findObj(n)),n.addEventListener?n.addEventListener(t,e,!1):n.attachEvent?n.attachEvent("on"+t,e):!1},JSGantt.addTooltipListeners=function(t,e,n){JSGantt.addListener("mouseover",function(e){JSGantt.showToolTip(t,e,n,null,t.getTimer())},e),JSGantt.addListener("mouseout",function(e){JSGantt.delayedHide(t,t.vTool,t.getTimer())},e)},JSGantt.addThisRowListeners=function(t,e,n){JSGantt.addListener("mouseover",function(){t.mouseOver(e,n)},e),JSGantt.addListener("mouseover",function(){t.mouseOver(e,n)},n),JSGantt.addListener("mouseout",function(){t.mouseOut(e,n)},e),JSGantt.addListener("mouseout",function(){t.mouseOut(e,n)},n)},JSGantt.addFolderListeners=function(t,e,n){JSGantt.addListener("click",function(){JSGantt.folder(n,t)},e)},JSGantt.addFormatListeners=function(t,e,n){JSGantt.addListener("click",function(){JSGantt.changeFormat(e,t)},n)},JSGantt.addScrollListeners=function(t){JSGantt.addListener("scroll",function(){t.getChartBody().scrollTop=t.getListBody().scrollTop},t.getListBody()),JSGantt.addListener("scroll",function(){t.getListBody().scrollTop=t.getChartBody().scrollTop},t.getChartBody()),JSGantt.addListener("scroll",function(){t.getChartHead().scrollLeft=t.getChartBody().scrollLeft},t.getChartBody()),JSGantt.addListener("scroll",function(){t.getChartBody().scrollLeft=t.getChartHead().scrollLeft},t.getChartHead()),JSGantt.addListener("resize",function(){t.getChartHead().scrollLeft=t.getChartBody().scrollLeft},window),JSGantt.addListener("resize",function(){t.getListBody().scrollTop=t.getChartBody().scrollTop},window)}; \ No newline at end of file diff --git a/htdocs/includes/jsgantt/jsgantt_Minutes.html b/htdocs/includes/jsgantt/jsgantt_Minutes.html deleted file mode 100644 index f49f8a2f5c5..00000000000 --- a/htdocs/includes/jsgantt/jsgantt_Minutes.html +++ /dev/null @@ -1,548 +0,0 @@ - - - - - - -FREE javascript gantt - JSGantt HTML and CSS only - - - - - - - - - - - - - - - - - - - - - - - - - -
      jsGantt - 1.2
      Bugs/Issues    Download    License    Usage    Examples    Documenation    Subscribe    Credits
    -

    -
    -
    - - -  100% Free Javascript / CSS/ HTML Gantt chart control. Completely buzzword compliant including AJAX !

    - - -
    - -
    - -Basic Features
    -
      -
    • Tasks & Collapsible Task Groups
    • -
    • Multiple Dependencies
    • -
    • Task Completion
    • -
    • Task Color
    • -
    • Milestones
    • -
    • Resources
    • -
    • No images needed
    • -
    - -Advanced Features
    -
      -
    • Dynamic Loading of Tasks
    • -
    • Dynamic change of format -
        -
      • Day
      • -
      • Week
      • -
      • Month
      • -
      • Quarter
      • -
      • Hour
      • -
      • Minute
      • -
      -
    • -
    • Load Gantt from XML file
    • -
    -
    -
    - -
    -Current Issues: -
      -
    1. Currently only one gantt chart is allowed per page.
    2. - -

    -New in 1.2: -
      -
    • Support for half-days
    • -
    • Hour/Minute format
    • -
    -
    -
    -Click here to download the jsgantt
    -You can download the latest bleeding edge version, request features and report issues at http://code.google.com/p/jsgantt/ -

    - -JSGantt is released under BSD license. If you require another license please contact shlomygantz@hotmail.com
    -If you plan to use it in a commercial product please consider donating the first sale to charity. -

    -

    - -

    1. Include JSGantt CSS and Javascript

    -
    -<link rel="stylesheet" type="text/css" href="jsgantt.css" />
    -<script language="javascript" src="jsgantt.js"></script>
    -
    - -

    2. Create a div element to hold the gantt chart

    -
    <div style="position:relative" class="gantt" id="GanttChartDIV"></div>
    -

    3. Start a <script> block

    -
    <script language="javascript">
    -

    4. Instantiate JSGantt using GanttChart()

    -
    var g = new JSGantt.GanttChart('g',document.getElementById('GanttChartDIV'), 'day');
    -
    -    
    - -

    GanttChart(pGanttVar, pDiv, pFormat)
    - pGanttVar: (required) name of the variable assigned
    - pDiv: (required) this is a DIV object created in HTML
    - pFormat: (required) - used to indicate whether chart should be drawn in "day", "week", "month", or "quarter" format

    -

    Customize the look and feel using the following setters

    -

    g.setShowRes(1); // Show/Hide Responsible (0/1)
    -g.setShowDur(1); // Show/Hide Duration (0/1)
    -g.setShowComp(1); // Show/Hide % Complete(0/1)
    -g.setCaptionType('Resource');  // Set to Show Caption (None,Caption,Resource,Duration,Complete)
    -g.setShowStartDate(1); // Show/Hide Start Date(0/1)
    -g.setShowEndDate(1); // Show/Hide End Date(0/1)
    -g.setDateInputFormat('mm/dd/yyyy')  // Set format of input dates ('mm/dd/yyyy', 'dd/mm/yyyy', 'yyyy-mm-dd')
    -g.setDateDisplayFormat('mm/dd/yyyy') // Set format to display dates ('mm/dd/yyyy', 'dd/mm/yyyy', 'yyyy-mm-dd')
    -g.setFormatArr("day","week","month","quarter") // Set format options (up to 4 : "minute","hour","day","week","month","quarter")
    -
    - -

    -

    5. Add Tasks using AddTaskItem()

    -
     
    -g.AddTaskItem(new JSGantt.TaskItem(1,   'Define Chart API',     '',          '',          'ff0000', 'http://help.com', 0, 'Brian',     0, 1, 0, 1));
    -g.AddTaskItem(new JSGantt.TaskItem(11,  'Chart Object',         '2/10/2008', '2/10/2008', 'ff00ff', 'http://www.yahoo.com', 1, 'Shlomy',  100, 0, 1, 1, "121,122", "My Caption"));
    -
    - -TaskItem(pID, pName, pStart, pEnd, pColor, pLink, pMile, pRes, pComp, pGroup, pParent, pOpen, pDepend)
    -pID: (required) is a unique ID used to identify each row for parent functions and for setting dom id for hiding/showing
    -pName: (required) is the task Label
    -pStart: (required) the task start date, can enter empty date ('') for groups. You can also enter specific time (2/10/2008 12:00) for additional percision or half days.
    -pEnd: (required) the task end date, can enter empty date ('') for groups
    -pColor: (required) the html color for this task; e.g. '00ff00'
    -pLink: (optional) any http link navigated to when task bar is clicked.
    -pMile:(optional) represent a milestone
    -pRes: (optional) resource name
    -pComp: (required) completion percent
    -pGroup: (optional) indicates whether this is a group(parent) - 0=NOT Parent; 1=IS Parent
    -pParent: (required) identifies a parent pID, this causes this task to be a child of identified task
    -pOpen: can be initially set to close folder when chart is first drawn
    -pDepend: optional list of id's this task is dependent on ... line drawn from dependent to this item
    -pCaption: optional caption that will be added after task bar if CaptionType set to "Caption"
    - -*You should be able to add items to the chart in realtime via javascript and issuing "g.Draw()" command. - -

    5a. Another way to add tasks is to use an external XML file with parseXML()

    -
     
    -JSGantt.parseXML("project.xml",g);
    -
    -The structure of the XML file:
    - - -

    6. Call Draw() and DrawDependencies()

    -
     
    -
    -g.Draw();	
    -g.DrawDependencies();
    -
    -
    - -
    -

    7. Close the <script> block

    -
    </script>
    - -

    -Final code should look like - -

    -
    - -

    -

    -

    - - - -

    -Enter your email address to receive JSGantt announcements
    -

    - - -

    -

    - -
    - -

    Developed by Shlomy Gantz and Brian Twidt
    -Contributed: Paul Labuschagne, Kevin Badgett, Ilan Admon
    -

    - - - - \ No newline at end of file diff --git a/htdocs/includes/jsgantt/jsgantt_exExternalXML.html b/htdocs/includes/jsgantt/jsgantt_exExternalXML.html deleted file mode 100644 index da571e056c8..00000000000 --- a/htdocs/includes/jsgantt/jsgantt_exExternalXML.html +++ /dev/null @@ -1,533 +0,0 @@ - - - - - - -FREE javascript gantt - JSGantt HTML and CSS only - - - - - - - - - - - - - - - - - - - - - - - - - -
      jsGantt - 1.2
      Bugs/Issues    Download    License    Usage    Examples    Documenation    Subscribe    Credits
    -

    -
    -
    - - -  100% Free Javascript / CSS/ HTML Gantt chart control. Completely buzzword compliant including AJAX !

    - - -
    - -
    - -Basic Features
    -
      -
    • Tasks & Collapsible Task Groups
    • -
    • Multiple Dependencies
    • -
    • Task Completion
    • -
    • Task Color
    • -
    • Milestones
    • -
    • Resources
    • -
    • No images needed
    • -
    - -Advanced Features
    -
      -
    • Dynamic Loading of Tasks
    • -
    • Dynamic change of format -
        -
      • Day
      • -
      • Week
      • -
      • Month
      • -
      • Quarter
      • -
      • Hour
      • -
      • Minute
      • -
      -
    • -
    • Load Gantt from XML file
    • -
    -
    -
    -
    -
    -Current Issues: -
      -
    1. Currently only one gantt chart is allowed per page.
    2. - -

    -New in 1.2: -
      -
    • Support for half-days
    • -
    • Hour/Minute format
    • -
    -
    -
    -Click here to download the jsgantt
    -You can download the latest bleeding edge version, request features and report issues at http://code.google.com/p/jsgantt/ -

    - -JSGantt is released under BSD license. If you require another license please contact shlomygantz@hotmail.com
    -If you plan to use it in a commercial product please consider donating the first sale to charity. -

    -

    - -

    1. Include JSGantt CSS and Javascript

    -
    -<link rel="stylesheet" type="text/css" href="jsgantt.css" />
    -<script language="javascript" src="jsgantt.js"></script>
    -
    - -

    2. Create a div element to hold the gantt chart

    -
    <div style="position:relative" class="gantt" id="GanttChartDIV"></div>
    -

    3. Start a <script> block

    -
    <script language="javascript">
    -

    4. Instantiate JSGantt using GanttChart()

    -
    var g = new JSGantt.GanttChart('g',document.getElementById('GanttChartDIV'), 'day');
    -
    -    
    - -

    GanttChart(pGanttVar, pDiv, pFormat)
    - pGanttVar: (required) name of the variable assigned
    - pDiv: (required) this is a DIV object created in HTML
    - pFormat: (required) - used to indicate whether chart should be drawn in "day", "week", "month", or "quarter" format

    -

    Customize the look and feel using the following setters

    -

    g.setShowRes(1); // Show/Hide Responsible (0/1)
    -g.setShowDur(1); // Show/Hide Duration (0/1)
    -g.setShowComp(1); // Show/Hide % Complete(0/1)
    -g.setCaptionType('Resource');  // Set to Show Caption (None,Caption,Resource,Duration,Complete)
    -g.setShowStartDate(1); // Show/Hide Start Date(0/1)
    -g.setShowEndDate(1); // Show/Hide End Date(0/1)
    -g.setDateInputFormat('mm/dd/yyyy')  // Set format of input dates ('mm/dd/yyyy', 'dd/mm/yyyy', 'yyyy-mm-dd')
    -g.setDateDisplayFormat('mm/dd/yyyy') // Set format to display dates ('mm/dd/yyyy', 'dd/mm/yyyy', 'yyyy-mm-dd')
    -g.setFormatArr("day","week","month","quarter") // Set format options (up to 4 : "minute","hour","day","week","month","quarter")
    -
    - -

    -

    5. Add Tasks using AddTaskItem()

    -
     
    -g.AddTaskItem(new JSGantt.TaskItem(1,   'Define Chart API',     '',          '',          'ff0000', 'http://help.com', 0, 'Brian',     0, 1, 0, 1));
    -g.AddTaskItem(new JSGantt.TaskItem(11,  'Chart Object',         '2/10/2008', '2/10/2008', 'ff00ff', 'http://www.yahoo.com', 1, 'Shlomy',  100, 0, 1, 1, "121,122", "My Caption"));
    -
    - -TaskItem(pID, pName, pStart, pEnd, pColor, pLink, pMile, pRes, pComp, pGroup, pParent, pOpen, pDepend)
    -pID: (required) is a unique ID used to identify each row for parent functions and for setting dom id for hiding/showing
    -pName: (required) is the task Label
    -pStart: (required) the task start date, can enter empty date ('') for groups. You can also enter specific time (2/10/2008 12:00) for additional percision or half days.
    -pEnd: (required) the task end date, can enter empty date ('') for groups
    -pColor: (required) the html color for this task; e.g. '00ff00'
    -pLink: (optional) any http link navigated to when task bar is clicked.
    -pMile:(optional) represent a milestone
    -pRes: (optional) resource name
    -pComp: (required) completion percent
    -pGroup: (optional) indicates whether this is a group(parent) - 0=NOT Parent; 1=IS Parent
    -pParent: (required) identifies a parent pID, this causes this task to be a child of identified task
    -pOpen: can be initially set to close folder when chart is first drawn
    -pDepend: optional list of id's this task is dependent on ... line drawn from dependent to this item
    -pCaption: optional caption that will be added after task bar if CaptionType set to "Caption"
    - -*You should be able to add items to the chart in realtime via javascript and issuing "g.Draw()" command. - -

    5a. Another way to add tasks is to use an external XML file with parseXML()

    -
     
    -JSGantt.parseXML("project.xml",g);
    -
    -The structure of the XML file:
    - - -

    6. Call Draw() and DrawDependencies()

    -
     
    -
    -g.Draw();	
    -g.DrawDependencies();
    -
    -
    - -
    -

    7. Close the <script> block

    -
    </script>
    - -

    -Final code should look like - -

    -
    - -

    -

    -

    - - - -

    -Enter your email address to receive JSGantt announcements
    -

    - - -

    -

    - -
    - -

    Developed by Shlomy Gantz and Brian Twidt
    -Contributed: Paul Labuschagne, Kevin Badgett, Ilan Admon
    -

    - - - - \ No newline at end of file diff --git a/htdocs/includes/jsgantt/main.css b/htdocs/includes/jsgantt/main.css new file mode 100644 index 00000000000..544192b1b2d --- /dev/null +++ b/htdocs/includes/jsgantt/main.css @@ -0,0 +1,126 @@ +body { + position: relative; +} + +.product-name { + font-family: Satisfy; +} + +#my-navbar-nav { + font-size: 16px; +} + +#my-nav-brand { + font-size: 24px; + margin: 2px 40px 0 10px; + color: #ffffff; +} + +#home { + background: #323232 url(home-bg.jpg) center 0 no-repeat; + background-attachment: fixed; + background-size: cover; + min-height: 660px; + color: #ffffff; +} +#home-title { + font-size: 70px; + margin-top: 180px; +} +#home-subtitle { + font-size: 36px; + margin-top: 40px; + margin-bottom: 50px; +} +#learn-more { + padding: 0; + width: 50px; + height: 50px; + border-radius: 50%; + font-size: 38px; + margin-top: 60px; +} +@media screen and (max-width: 991px) { + #learn-more { + display: none; + } +} + +.section { + margin: 0 15vw; + padding: 5px 0 0; +} + +h1 { + font-family: Kelly Slab; + font-size: 56px; + margin: 50px 0 20px; +} + +h2 { + font-family: Kelly Slab; + margin: 20px 0 10px; +} + +h3 { + font-family: Kelly Slab; +} +#embedded-Gantt, #external-Gantt { +} + +.code-block { + background-color: #222222; +} + +.contact-card { + max-width: 200px; + margin: auto; +} + +.contact-link { + font-size: 28px; +} + +.footer { + margin-top: 10px; + padding-top: 10px; + border-top: solid #bbbbbb 1px; +} + +#slide-card { + background: transparent; + border: none; + margin: 180px 50px 50px; +} +#slide-dots { + background: transparent; + border: none; +} +.dot { + cursor:pointer; + height: 13px; + width: 13px; + margin: 0 2px; + background-color: #ffffff; + opacity: 0.3; + border-radius: 50%; + display: inline-block; + -webkit-transition: all .5s; /* Safari */ + transition: all .5s; +} +.dot:hover { + opacity: 1; +} +.dot.active { + opacity: 1; +} +.slide { + width: 100%; + height: 150px; + font-size: 20px; + display: none; + opacity: 0; +} +.slide-icon { + font-size: 60px; +} diff --git a/htdocs/includes/jsgantt/main.js b/htdocs/includes/jsgantt/main.js new file mode 100644 index 00000000000..53f5f8f0c10 --- /dev/null +++ b/htdocs/includes/jsgantt/main.js @@ -0,0 +1,85 @@ +$(document).ready(function() { + + // Scrollspy changes navbar active links + $("body").scrollspy({target:"#my-navbar-nav", offset:50}); + + // Smooth scroll + $("a").click(function(event) { + if (this.hash !== "") { + event.preventDefault(); + var linkOffset = 0; + if ($.inArray(this.hash,["#options","#xmlExport","#optionsLanguage","#setDayMajorDateDisplayFormat"]) != -1) { + linkOffset = -25; + } + $("html, body").animate({ + scrollTop: $(this.hash).offset().top - $(".navbar").height() + linkOffset + }, 600); + } + }); + + // Demo buttons + $("#embedded-Gantt").hide(0); + $("#external-Gantt").hide(0); + + $(".btn-demo").click(function() { + if ($(this).html().indexOf("Embedded Code") != -1) { + if ($("#external-Gantt").is(":visible")) { + $("#external-Gantt").animate({ + height: "toggle", + opacity: "toggle"}, 300, function () { + $("#embedded-Gantt").animate({ + height: "toggle", + opacity: "toggle"}, 600 + ); + } + ); + $(".btn-demo:nth-child(2)").removeClass("active"); + } else { + $("#embedded-Gantt").animate({ + height: "toggle", + opacity: "toggle"}, 600 + ); + } + } else { + if ($("#embedded-Gantt").is(":visible")) { + $("#embedded-Gantt").animate({ + height: "toggle", + opacity: "toggle"}, 300, function() { + $("#external-Gantt").animate({ + height: "toggle", + opacity: "toggle"}, 600 + ); + } + ); + $(".btn-demo:nth-child(1)").removeClass("active"); + } else { + $("#external-Gantt").animate({ + height: "toggle", + opacity: "toggle"}, 600 + ); + } + } + }); + + // Slideshow + var slideIndex = 0; + carousel(); + + function carousel() { + var i; + var x = document.getElementsByClassName("slide"); + var d = document.getElementsByClassName("dot"); + for (i = 0; i < x.length; i++) { + x[i].style.display = "none"; + } + slideIndex++; + if (slideIndex > x.length) {slideIndex = 1} + x[slideIndex-1].style.display = "inline-block"; + $(".slide:nth-child(" + (slideIndex).toString() + ")").animate({ + opacity: 1 + }, 500); + $(".dot").removeClass("active"); + $(".dot:nth-child(" + (slideIndex).toString() + ")").addClass("active"); + setTimeout(carousel, 2000); // Change image every 2 seconds + } + }); diff --git a/htdocs/includes/jsgantt/project.xml b/htdocs/includes/jsgantt/project.xml index d43110a6a38..80637aa7cae 100644 --- a/htdocs/includes/jsgantt/project.xml +++ b/htdocs/includes/jsgantt/project.xml @@ -1,65 +1,131 @@ - - - 10 - WCF Changes - - - 0000ff - - 0 - - 0 - 1 - 0 - 1 - - - - 20 - Move to WCF from remoting - 9/11/2008 - 9/15/2008 - 0000ff - - 0 - Rich - 10 - 0 - 10 - 1 - - Brian - - - 30 - add Auditing - 9/19/2008 - 9/21/2008 - 0000ff - - 0 - Shlomy - 50 - 0 - 10 - 1 - 20 - Shlomy - - - 40 - Yet another task - 9/23/2008 - 9/24/2008 - 0000ff - - 0 - Shlomy - 30 - 0 - 0 - 1 - 20,30 - Shlomy - - \ No newline at end of file + + + + 10 + WCF Changes + + + ggroupblack + + 0 + + 0 + 1 + 0 + 1 + + + + 20 + Move to WCF from remoting + 2017-05-11 09:00 + 2017-05-15 + gtaskblue + + 0 + Paul + 10 + 0 + 10 + 1 + + Paul + This text is only available in tool tips + + + 30 + add Auditing + 2017-05-18 10:30 + 2017-05-20 12:00 + gtaskblue + + 0 + Eduardo + 50 + 0 + 10 + 1 + 20 + Eduardo + + + 40 + Yet another task + 2017-05-24 + 2017-05-25 + gtaskblue + + 0 + Ricardo + 30 + 0 + 0 + 1 + 20,30 + Ricardo + + + 50 + Another Group + + + ggroupblack + + 0 + + 0 + 1 + 0 + 1 + + + + 60 + Move to GitHub + 2017-05-14 09:00 + 2017-05-16 + gtaskblue + + 0 + Ricardo + 10 + 0 + 50 + 1 + + Ricardo + This text is only available in tool tips + + + 70 + Updating files + 2017-05-18 10:30 + 2017-05-21 12:00 + gtaskred + + 0 + Paul + 50 + 0 + 50 + 1 + 60 + Paul + + + 80 + Yet another task + 2017-05-23 + 2017-05-25 + gtaskyellow + + 0 + Eduardo + 30 + 0 + 50 + 1 + 60,70 + Eduardo + + diff --git a/htdocs/includes/odtphp/Segment.php b/htdocs/includes/odtphp/Segment.php index 525cd5b4f3f..f9a44b996b2 100644 --- a/htdocs/includes/odtphp/Segment.php +++ b/htdocs/includes/odtphp/Segment.php @@ -175,8 +175,18 @@ class Segment implements IteratorAggregate, Countable { global $langs; - $patterns=array('/__CURRENTDAY__/','/__CURRENTDAYTEXT__/','/__CURRENTMONTHSHORT__/','/__CURRENTMONTH__/','/__CURRENTYEAR__/'); - $values=array(date('j'), $langs->trans(date('l')), $langs->trans(date('M')), $langs->trans(date('F')), date('Y')); + $hoy = dol_getdate(dol_now('tzuser')); + $dateinonemontharray = dol_get_next_month($hoy['mon'], $hoy['year']); + $nextMonth = $dateinonemontharray['month']; + + $patterns=array( '/__CURRENTDAY__/u','/__CURENTWEEKDAY__/u', + '/__CURRENTMONTH__/u','/__CURRENTMONTHLONG__/u', + '/__NEXTMONTH__/u','/__NEXTMONTHLONG__/u', + '/__CURRENTYEAR__/u','/__NEXTYEAR__/u' ); + $values=array( $hoy['mday'], $langs->transnoentitiesnoconv($hoy['weekday']), + $hoy['mon'], $langs->transnoentitiesnoconv($hoy['month']), + $nextMonth, monthArray($langs)[$nextMonth], + $hoy['year'], $hoy['year']+1 ); $text=preg_replace($patterns, $values, $text); diff --git a/htdocs/includes/odtphp/odf.php b/htdocs/includes/odtphp/odf.php index 01633634705..19fd3390937 100644 --- a/htdocs/includes/odtphp/odf.php +++ b/htdocs/includes/odtphp/odf.php @@ -36,14 +36,14 @@ class Odf protected $images = array(); protected $vars = array(); protected $segments = array(); - + public $creator; public $title; public $subject; public $userdefined=array(); - + const PIXEL_TO_CM = 0.026458333; - + /** * Class constructor * @@ -113,7 +113,7 @@ class Odf copy($filename, $this->tmpfile); - // Now file has been loaded, we must move the [!-- BEGIN and [!-- END tags outside the + // Now file has been loaded, we must move the [!-- BEGIN and [!-- END tags outside the // _moveRowSegments(); } @@ -124,7 +124,7 @@ class Odf * @param string $key Name of the variable within the template * @param string $value Replacement value * @param bool $encode If true, special XML characters are encoded - * @param string $charset Charset + * @param string $charset Charset * @throws OdfException * @return odf */ @@ -211,7 +211,7 @@ class Odf { preg_match_all('/[\{\<]\?(php)?\s+(?P.+)\?[\}\>]/iU',$this->contentXml, $matches); // detecting all {?php code ?} or $nbfound=count($matches['content']); - for ($i=0; $i < $nbfound; $i++) + for ($i=0; $i < $nbfound; $i++) { try { $ob_output = ''; // flush the output for each code. This var will be filled in by the eval($code) and output buffering : any print or echo or output will be redirected into this variable @@ -268,7 +268,7 @@ IMG; $this->contentXml = preg_replace('/\[!--\sBEGIN]>(row.[\S]*)\s--\]/sm', '[!-- BEGIN \\1 --]', $this->contentXml); // Replace ENDxxx into END xxx $this->contentXml = preg_replace('/\[!--\sEND]>(row.[\S]*)\s--\]/sm', '[!-- END \\1 --]', $this->contentXml); - + // Search all possible rows in the document $reg1 = "#]*>(.*)#smU"; preg_match_all($reg1, $this->contentXml, $matches); @@ -302,7 +302,7 @@ IMG; // Search all tags fou into condition to complete $this->vars, so we will proceed all tests even if not defined $reg='@\[!--\sIF\s([{}a-zA-Z0-9\.\,_]+)\s--\]@smU'; preg_match_all($reg, $this->contentXml, $matches, PREG_SET_ORDER); - + //var_dump($this->vars);exit; foreach($matches as $match) // For each match, if there is no entry into this->vars, we add it { @@ -312,7 +312,7 @@ IMG; } } //var_dump($this->vars);exit; - + // Conditionals substitution // Note: must be done before static substitution, else the variable will be replaced by its value and the conditional won't work anymore foreach($this->vars as $key => $value) @@ -358,7 +358,7 @@ IMG; if ($type == 'content') $this->contentXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->contentXml); if ($type == 'styles') $this->stylesXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->stylesXml); if ($type == 'meta') $this->metaXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->metaXml); - + } /** @@ -467,7 +467,7 @@ IMG; $this->setMetaData(); //print $this->metaXml;exit; - + if (! $this->file->addFromString('content.xml', $this->contentXml)) { throw new OdfException('Error during file export addFromString content'); } @@ -477,7 +477,7 @@ IMG; if (! $this->file->addFromString('styles.xml', $this->stylesXml)) { throw new OdfException('Error during file export addFromString styles'); } - + foreach ($this->images as $imageKey => $imageValue) { // Add the image inside the ODT document $this->file->addFile($imageKey, 'Pictures/' . $imageValue); @@ -499,12 +499,12 @@ IMG; public function setMetaData() { if (empty($this->creator)) $this->creator=''; - + $this->metaXml = preg_replace('/.*<\/dc:date>/', ''.gmdate("Y-m-d\TH:i:s").'', $this->metaXml); $this->metaXml = preg_replace('/.*<\/dc:creator>/', ''.htmlspecialchars($this->creator).'', $this->metaXml); $this->metaXml = preg_replace('/.*<\/dc:title>/', ''.htmlspecialchars($this->title).'', $this->metaXml); $this->metaXml = preg_replace('/.*<\/dc:subject>/', ''.htmlspecialchars($this->subject).'', $this->metaXml); - + if (count($this->userdefined)) { foreach($this->userdefined as $key => $val) @@ -515,7 +515,7 @@ IMG; } } } - + /** * Update Manifest file according to added image files * @@ -569,24 +569,58 @@ IMG; { global $conf; - if( $name == "" ) $name = md5(uniqid()); + if( $name == "" ) $name = "temp".md5(uniqid()); dol_syslog(get_class($this).'::exportAsAttachedPDF $name='.$name, LOG_DEBUG); $this->saveToDisk($name); $execmethod=(empty($conf->global->MAIN_EXEC_USE_POPEN)?1:2); // 1 or 2 + // Method 1 sometimes hang the server. - $name=preg_replace('/\.odt/i', '', $name); - if (!empty($conf->global->MAIN_DOL_SCRIPTS_ROOT)) + if (preg_match('/unoconv/', $conf->global->MAIN_ODT_AS_PDF)) { - $command = $conf->global->MAIN_DOL_SCRIPTS_ROOT.'/scripts/odt2pdf/odt2pdf.sh '.escapeshellcmd($name).' '.(is_numeric($conf->global->MAIN_ODT_AS_PDF)?'jodconverter':$conf->global->MAIN_ODT_AS_PDF); + // If issue with unoconv, see https://github.com/dagwieers/unoconv/issues/87 + + // MAIN_ODT_AS_PDF should be "sudo -u unoconv /usr/bin/unoconv" and userunoconv must have sudo to be root by adding file /etc/sudoers.d/unoconv with content www-data ALL=(unoconv) NOPASSWD: /usr/bin/unoconv . + + // Try this with www-data user: /usr/bin/unoconv -vvvv -f pdf /tmp/document-example.odt + // It must return: + //Verbosity set to level 4 + //Using office base path: /usr/lib/libreoffice + //Using office binary path: /usr/lib/libreoffice/program + //DEBUG: Connection type: socket,host=127.0.0.1,port=2002;urp;StarOffice.ComponentContext + //DEBUG: Existing listener not found. + //DEBUG: Launching our own listener using /usr/lib/libreoffice/program/soffice.bin. + //LibreOffice listener successfully started. (pid=9287) + //Input file: /tmp/document-example.odt + //unoconv: file `/tmp/document-example.odt' does not exist. + //unoconv: RuntimeException during import phase: + //Office probably died. Unsupported URL : "type detection failed" + //DEBUG: Terminating LibreOffice instance. + //DEBUG: Waiting for LibreOffice instance to exit + + // It fails: + // - set shel of user to bash instead of nologin. + // - set permission to read/write to user on home directory /var/www so user can create the libreoffice , dconf and .cache dir and files then set permission back + + $command = $conf->global->MAIN_ODT_AS_PDF.' '.escapeshellcmd($name); + //$command = '/usr/bin/unoconv -vvv '.escapeshellcmd($name); } else { - dol_syslog(get_class($this).'::exportAsAttachedPDF is used but the constant MAIN_DOL_SCRIPTS_ROOT with path to script directory was not defined.', LOG_WARNING); - $command = '../../scripts/odt2pdf/odt2pdf.sh '.escapeshellcmd($name).' '.(is_numeric($conf->global->MAIN_ODT_AS_PDF)?'jodconverter':$conf->global->MAIN_ODT_AS_PDF); - } + // deprecated old method + $name=preg_replace('/\.odt/i', '', $name); + if (!empty($conf->global->MAIN_DOL_SCRIPTS_ROOT)) + { + $command = $conf->global->MAIN_DOL_SCRIPTS_ROOT.'/scripts/odt2pdf/odt2pdf.sh '.escapeshellcmd($name).' '.(is_numeric($conf->global->MAIN_ODT_AS_PDF)?'jodconverter':$conf->global->MAIN_ODT_AS_PDF); + } + else + { + dol_syslog(get_class($this).'::exportAsAttachedPDF is used but the constant MAIN_DOL_SCRIPTS_ROOT with path to script directory was not defined.', LOG_WARNING); + $command = '../../scripts/odt2pdf/odt2pdf.sh '.escapeshellcmd($name).' '.(is_numeric($conf->global->MAIN_ODT_AS_PDF)?'jodconverter':$conf->global->MAIN_ODT_AS_PDF); + } + } //$dirname=dirname($name); //$command = DOL_DOCUMENT_ROOT.'/includes/odtphp/odt2pdf.sh '.$name.' '.$dirname; @@ -598,16 +632,19 @@ IMG; } if ($execmethod == 2) { + $outputfile = DOL_DATA_ROOT.'/odt2pdf.log'; + $ok=0; $handle = fopen($outputfile, 'w'); if ($handle) { dol_syslog(get_class($this)."Run command ".$command,LOG_DEBUG); + fwrite($handle, $command."\n"); $handlein = popen($command, 'r'); while (!feof($handlein)) { $read = fgets($handlein); - fwrite($handle,$read); + fwrite($handle, $read); $output_arr[]=$read; } pclose($handlein); @@ -616,7 +653,7 @@ IMG; if (! empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK)); } - if($retval == 0) + if ($retval == 0) { dol_syslog(get_class($this).'::exportAsAttachedPDF $ret_val='.$retval, LOG_DEBUG); if (headers_sent($filename, $linenum)) { @@ -686,7 +723,7 @@ IMG; /** * Empty the temporary working directory recursively - * + * * @param string $dir The temporary working directory * @return void */ @@ -709,7 +746,7 @@ IMG; /** * return the value present on odt in [valuename][/valuename] - * + * * @param string $valuename Balise in the template * @return string The value inside the balise */ diff --git a/htdocs/index.php b/htdocs/index.php index ae4ec72a901..0cba7291e9b 100644 --- a/htdocs/index.php +++ b/htdocs/index.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2005-2017 Regis Houssin * Copyright (C) 2011-2012 Juanjo Menent * Copyright (C) 2015 Marcos García @@ -330,10 +330,11 @@ if (empty($user->societe_id)) if (!empty($langfile[$key])) $langs->load($langfile[$key]); $text=$langs->trans($titres[$key]); + //$sep=($conf->dol_use_jmobile?'
    ':' '); $boxstat.='
    '; $boxstat.='
    '; - $boxstat.=''.img_object("",$icons[$key]).' '.$text.'
    '; - $boxstat.=''.($board->nb[$val]?$board->nb[$val]:0).''; + $boxstat.=''.$text.'
    '; + $boxstat.=''.img_object("",$icons[$key],'class="inline-block"').' '.($board->nb[$val]?$board->nb[$val]:0).''; $boxstat.='
    '; $boxstat.='
    '; } @@ -372,135 +373,135 @@ require DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php'; // Number of actions to do (late) if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->read) { - include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - $board=new ActionComm($db); + include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; + $board=new ActionComm($db); - $dashboardlines[] = $board->load_board($user); + $dashboardlines[] = $board->load_board($user); } // Number of project opened if (! empty($conf->projet->enabled) && $user->rights->projet->lire) { - include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - $board=new Project($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + $board=new Project($db); + $dashboardlines[] = $board->load_board($user); } // Number of tasks to do (late) if (! empty($conf->projet->enabled) && empty($conf->global->PROJECT_HIDE_TASKS) && $user->rights->projet->lire) { - include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; - $board=new Task($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; + $board=new Task($db); + $dashboardlines[] = $board->load_board($user); } // Number of commercial proposals opened (expired) if (! empty($conf->propal->enabled) && $user->rights->propale->lire) { - include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $board=new Propal($db); - $dashboardlines[] = $board->load_board($user,"opened"); - // Number of commercial proposals CLOSED signed (billed) - $dashboardlines[] = $board->load_board($user,"signed"); + include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; + $board=new Propal($db); + $dashboardlines[] = $board->load_board($user,"opened"); + // Number of commercial proposals CLOSED signed (billed) + $dashboardlines[] = $board->load_board($user,"signed"); } // Number of commercial proposals opened (expired) if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) { - include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; - $board=new SupplierProposal($db); - $dashboardlines[] = $board->load_board($user,"opened"); - // Number of commercial proposals CLOSED signed (billed) - $dashboardlines[] = $board->load_board($user,"signed"); + include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; + $board=new SupplierProposal($db); + $dashboardlines[] = $board->load_board($user,"opened"); + // Number of commercial proposals CLOSED signed (billed) + $dashboardlines[] = $board->load_board($user,"signed"); } // Number of customer orders a deal if (! empty($conf->commande->enabled) && $user->rights->commande->lire) { - include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $board=new Commande($db); + include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; + $board=new Commande($db); $dashboardlines[] = $board->load_board($user); } // Number of suppliers orders a deal if (! empty($conf->supplier_order->enabled) && $user->rights->fournisseur->commande->lire) { - include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; - $board=new CommandeFournisseur($db); + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; + $board=new CommandeFournisseur($db); $dashboardlines[] = $board->load_board($user); } // Number of services enabled (delayed) if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire) { - include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; - $board=new Contrat($db); - $dashboardlines[] = $board->load_board($user,"inactives"); + include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; + $board=new Contrat($db); + $dashboardlines[] = $board->load_board($user,"inactives"); // Number of active services (expired) - $dashboardlines[] = $board->load_board($user,"expired"); + $dashboardlines[] = $board->load_board($user,"expired"); } // Number of invoices customers (has paid) if (! empty($conf->facture->enabled) && $user->rights->facture->lire) { - include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $board=new Facture($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $board=new Facture($db); + $dashboardlines[] = $board->load_board($user); } // Number of supplier invoices (has paid) if (! empty($conf->supplier_invoice->enabled) && ! empty($user->rights->fournisseur->facture->lire)) { - include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; - $board=new FactureFournisseur($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; + $board=new FactureFournisseur($db); + $dashboardlines[] = $board->load_board($user); } // Number of transactions to conciliate if (! empty($conf->banque->enabled) && $user->rights->banque->lire && ! $user->societe_id) { - include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $board=new Account($db); - $nb = $board::countAccountToReconcile(); // Get nb of account to reconciliate - if ($nb > 0) - { - $dashboardlines[] = $board->load_board($user); - } + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + $board=new Account($db); + $nb = $board::countAccountToReconcile(); // Get nb of account to reconciliate + if ($nb > 0) + { + $dashboardlines[] = $board->load_board($user); + } } // Number of cheque to send if (! empty($conf->banque->enabled) && $user->rights->banque->lire && ! $user->societe_id && empty($conf->global->BANK_DISABLE_CHECK_DEPOSIT)) { - include_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; - $board=new RemiseCheque($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; + $board=new RemiseCheque($db); + $dashboardlines[] = $board->load_board($user); } // Number of foundation members if (! empty($conf->adherent->enabled) && $user->rights->adherent->lire && ! $user->societe_id) { - include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - $board=new Adherent($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + $board=new Adherent($db); + $dashboardlines[] = $board->load_board($user); } // Number of expense reports to approve if (! empty($conf->expensereport->enabled) && $user->rights->expensereport->approve) { - include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; - $board=new ExpenseReport($db); + include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; + $board=new ExpenseReport($db); $dashboardlines[] = $board->load_board($user,'toapprove'); } // Number of expense reports to pay if (! empty($conf->expensereport->enabled) && $user->rights->expensereport->to_paid) { - include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; - $board=new ExpenseReport($db); + include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; + $board=new ExpenseReport($db); $dashboardlines[] = $board->load_board($user,'topay'); } // Calculate total nb of late -$totallate=0; +$totallate=$totaltodo=0; $var=true; //Remove any invalid response @@ -515,11 +516,13 @@ foreach($dashboardlines as $tmp) foreach($valid_dashboardlines as $board) { if ($board->nbtodolate > 0) { + if(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) $totaltodo += $board->nbtodo; $totallate += $board->nbtodolate; } } - - +//var_dump($totallate, $totaltodo); +if(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) $totallate = round($totallate / $totaltodo * 100, 2); +//var_dump($totallate); $boxwork=''; $boxwork.='
    '; $boxwork.=''."\n"; @@ -532,7 +535,7 @@ if ($showweather) $boxwork.=''; $boxwork.=''; + } + } + catch(Exception $e) + { + print $e->getMessage(); + } + } + else + { + if (empty($forceddirread)) + { + $fullpathoffile=dol_buildpath($file, 0); + } + else + { + $fullpathoffile=$dirread.'/'.$file; + } + + $content = file_get_contents($fullpathoffile); + + // New module + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format','aZ09')?GETPOST('format','aZ09'):'html')); + print '
    '; + print '
    '; + print ''; + print '   '; + print ''; + print '
    '; + + print ''; + } + } + + dol_fiche_end(); // Level 3 + } + + if ($tab == 'menus') + { + $pathtofile = $modulelowercase.'/core/modules/mod'.$module.'.class.php'; + + //$menus = $moduleobj->; + + if ($action != 'editfile' || empty($file)) + { + print $langs->trans("MenusDefDesc", ''.$langs->trans('Menus').'').'
    '; + print '
    '; + + print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print '
    '; + + print '
    '; + //print load_fiche_titre($langs->trans("MenusList"), '', ''); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + /* + print '
    '; + print '
    '; $text=''; - if ($totallate > 0) $text=$langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv("NActionsLate",$totallate).')'; + if ($totallate > 0) $text=$langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv("NActionsLate",$totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '')).')'; $text.='. '.$langs->trans("LateDesc"); //$text.=$form->textwithpicto('',$langs->trans("LateDesc")); $options='height="64px"'; @@ -555,6 +558,7 @@ if (! empty($valid_dashboardlines)) $boxwork .='
    '; $boxwork .= '
    '; + $sep=($conf->dol_use_jmobile?'
    ':' '); $boxwork .= ''.$board->img.' '.$board->label.'
    '; $boxwork .= ''.$board->nbtodo.''; $boxwork .= '
    '; @@ -563,7 +567,7 @@ if (! empty($valid_dashboardlines)) $boxwork .= '
    '; $boxwork .= ''; //$boxwork .= img_picto($textlate, "warning_white", 'class="valigntextbottom"').''; - $boxwork .= img_picto($textlate, "warning_white", 'class="valigntextbottom"').''; + $boxwork .= img_picto($textlate, "warning_white", 'class="inline-block hideonsmartphone valigntextbottom"').''; $boxwork .= ''; $boxwork .= $board->nbtodolate; $boxwork .= ''; @@ -689,10 +693,12 @@ function showWeather($totallate,$text,$options) $offset=0; $factor=10; // By default - $level0=$offset; if (! empty($conf->global->MAIN_METEO_LEVEL0)) $level0=$conf->global->MAIN_METEO_LEVEL0; - $level1=$offset+1*$factor; if (! empty($conf->global->MAIN_METEO_LEVEL1)) $level1=$conf->global->MAIN_METEO_LEVEL1; - $level2=$offset+2*$factor; if (! empty($conf->global->MAIN_METEO_LEVEL2)) $level2=$conf->global->MAIN_METEO_LEVEL2; - $level3=$offset+3*$factor; if (! empty($conf->global->MAIN_METEO_LEVEL3)) $level3=$conf->global->MAIN_METEO_LEVEL3; + $used_conf = !empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? 'MAIN_METEO_PERCENTAGE_LEVEL' : 'MAIN_METEO_LEVEL'; + + $level0=$offset; if (! empty($conf->global->{$used_conf.'0'})) $level0=$conf->global->{$used_conf.'0'}; + $level1=$offset+1*$factor; if (! empty($conf->global->{$used_conf.'1'})) $level1=$conf->global->{$used_conf.'1'}; + $level2=$offset+2*$factor; if (! empty($conf->global->{$used_conf.'2'})) $level2=$conf->global->{$used_conf.'2'}; + $level3=$offset+3*$factor; if (! empty($conf->global->{$used_conf.'3'})) $level3=$conf->global->{$used_conf.'3'}; if ($totallate <= $level0) $out.=img_weather($text,'weather-clear.png',$options); if ($totallate > $level0 && $totallate <= $level1) $out.=img_weather($text,'weather-few-clouds.png',$options); diff --git a/htdocs/install/check.php b/htdocs/install/check.php index 94d717b2206..50409fb55e5 100644 --- a/htdocs/install/check.php +++ b/htdocs/install/check.php @@ -365,7 +365,7 @@ else print $langs->trans("InstallEasy")." "; print $langs->trans("ChooseYourSetupMode"); - print '

    '; + print '

    '; $foundrecommandedchoice=0; @@ -424,7 +424,8 @@ else array('from'=>'3.8.0', 'to'=>'3.9.0'), array('from'=>'3.9.0', 'to'=>'4.0.0'), array('from'=>'4.0.0', 'to'=>'5.0.0'), - array('from'=>'5.0.0', 'to'=>'6.0.0') + array('from'=>'5.0.0', 'to'=>'6.0.0'), + array('from'=>'6.0.0', 'to'=>'7.0.0') ); $count=0; @@ -533,13 +534,13 @@ else if (count($notavailable_choices)) { - print '
    '; + print '
    '; print '
    '; print '
    '.$langs->trans('Failed to init the object with the new.').'
    '; + + print ''; + print_liste_field_titre("Menu",$_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder); + print_liste_field_titre("CronTask",'','',"",$param,'',$sortfield,$sortorder); + print_liste_field_titre("CronFrequency",'',"","",$param,'',$sortfield,$sortorder); + print_liste_field_titre("StatusAtInstall",$_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder); + print_liste_field_titre("Comment",$_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder); + print "\n"; + + if (count($menus)) + { + foreach ($cronjobs as $cron) + { + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + } + } + else + { + print ''; + } + + print '
    '; + print $cron['label']; + print ''; + if ($cron['jobtype']=='method') + { + $text=$langs->trans("CronClass"); + $texttoshow=$langs->trans('CronModule').': '.$module.'
    '; + $texttoshow.=$langs->trans('CronClass').': '. $cron['class'].'
    '; + $texttoshow.=$langs->trans('CronObject').': '. $cron['objectname'].'
    '; + $texttoshow.=$langs->trans('CronMethod').': '. $cron['method']; + $texttoshow.='
    '.$langs->trans('CronArgs').': '. $cron['parameters']; + $texttoshow.='
    '.$langs->trans('Comment').': '. $langs->trans($cron['comment']); + } + elseif ($cron['jobtype']=='command') + { + $text=$langs->trans('CronCommand'); + $texttoshow=$langs->trans('CronCommand').': '.dol_trunc($cron['command']); + $texttoshow.='
    '.$langs->trans('CronArgs').': '. $cron['parameters']; + $texttoshow.='
    '.$langs->trans('Comment').': '. $langs->trans($cron['comment']); + } + print $form->textwithpicto($text, $texttoshow, 1); + print '
    '; + if($cron['unitfrequency'] == "60") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Minutes'); + if($cron['unitfrequency'] == "3600") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Hours'); + if($cron['unitfrequency'] == "86400") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Days'); + if($cron['unitfrequency'] == "604800") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Weeks'); + print ''; + print $cron['status']; + print ''; + if (!empty($cron['comment'])) {print $cron['comment'];} + print '
    '.$langs->trans("None").'
    '; + print '
    '; + + print ''; + */ + } + else + { + $fullpathoffile=dol_buildpath($file, 0); + + $content = file_get_contents($fullpathoffile); + + // New module + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + + $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format','aZ09')?GETPOST('format','aZ09'):'html')); + print '
    '; + print '
    '; + print ''; + print '   '; + print ''; + print '
    '; + + print '
    '; + } + } + + if ($tab == 'permissions') + { + $pathtofile = $modulelowercase.'/core/modules/mod'.$module.'.class.php'; + + //$perms = $moduleobj->; + + if ($action != 'editfile' || empty($file)) + { + print $langs->trans("PermissionsDefDesc", ''.$langs->trans('DefaultPermissions').'').'
    '; + print '
    '; + + print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print '
    '; + + print '
    '; + print load_fiche_titre($langs->trans("ListOfPermissionsDefined"), '', ''); + + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + + print 'TODO...'; + /* + print '
    '; + print ''; + + print ''; + print_liste_field_titre("CronLabel",$_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder); + print_liste_field_titre("CronTask",'','',"",$param,'',$sortfield,$sortorder); + print_liste_field_titre("CronFrequency",'',"","",$param,'',$sortfield,$sortorder); + print_liste_field_titre("StatusAtInstall",$_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder); + print_liste_field_titre("Comment",$_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder); + print "\n"; + + if (count($cronjobs)) + { + foreach ($cronjobs as $cron) + { + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + } + } + else + { + print ''; + } + + print '
    '; + print $cron['label']; + print ''; + if ($cron['jobtype']=='method') + { + $text=$langs->trans("CronClass"); + $texttoshow=$langs->trans('CronModule').': '.$module.'
    '; + $texttoshow.=$langs->trans('CronClass').': '. $cron['class'].'
    '; + $texttoshow.=$langs->trans('CronObject').': '. $cron['objectname'].'
    '; + $texttoshow.=$langs->trans('CronMethod').': '. $cron['method']; + $texttoshow.='
    '.$langs->trans('CronArgs').': '. $cron['parameters']; + $texttoshow.='
    '.$langs->trans('Comment').': '. $langs->trans($cron['comment']); + } + elseif ($cron['jobtype']=='command') + { + $text=$langs->trans('CronCommand'); + $texttoshow=$langs->trans('CronCommand').': '.dol_trunc($cron['command']); + $texttoshow.='
    '.$langs->trans('CronArgs').': '. $cron['parameters']; + $texttoshow.='
    '.$langs->trans('Comment').': '. $langs->trans($cron['comment']); + } + print $form->textwithpicto($text, $texttoshow, 1); + print '
    '; + if($cron['unitfrequency'] == "60") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Minutes'); + if($cron['unitfrequency'] == "3600") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Hours'); + if($cron['unitfrequency'] == "86400") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Days'); + if($cron['unitfrequency'] == "604800") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Weeks'); + print ''; + print $cron['status']; + print ''; + if (!empty($cron['comment'])) {print $cron['comment'];} + print '
    '.$langs->trans("None").'
    '; + print '
    '; + + print '
    '; + */ + } + else + { + $fullpathoffile=dol_buildpath($file, 0); + + $content = file_get_contents($fullpathoffile); + + // New module + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + + $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format','aZ09')?GETPOST('format','aZ09'):'html')); + print '
    '; + print '
    '; + print ''; + print '   '; + print ''; + print '
    '; + + print '
    '; + } + } + + if ($tab == 'hooks') + { + if ($action != 'editfile' || empty($file)) + { + print $langs->trans("HooksDefDesc").'
    '; + print '
    '; + + $pathtofile = $modulelowercase.'/core/modules/mod'.$module.'.class.php'; + print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print '
    '; + + $pathtohook = strtolower($module).'/class/actions_'.strtolower($module).'.class.php'; + print ' '.$langs->trans("HooksFile").' : '.$pathtohook.''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print '
    '; + } + else + { + $fullpathoffile=dol_buildpath($file, 0); + + $content = file_get_contents($fullpathoffile); + + // New module + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + + $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format','aZ09')?GETPOST('format','aZ09'):'html')); + print '
    '; + print '
    '; + print ''; + print '   '; + print ''; + print '
    '; + + print '
    '; + } + } + + if ($tab == 'triggers') + { + require_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; $interfaces = new Interfaces($db); $triggers = $interfaces->getTriggersList(array('/'.strtolower($module).'/core/triggers')); if ($action != 'editfile' || empty($file)) { - foreach ($triggers as $trigger) - { - $pathtofile = $trigger['relpath']; + print $langs->trans("TriggerDefDesc").'
    '; + print '
    '; - print ' '.$langs->trans("TriggersFile").' : '.$pathtofile.''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; - print '
    '; - } + if (! empty($triggers)) + { + foreach ($triggers as $trigger) + { + $pathtofile = $trigger['relpath']; + + print ' '.$langs->trans("TriggersFile").' : '.$pathtofile.''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print '
    '; + } + } + else + { + print $langs->trans("NoTrigger"); + } } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile=dol_buildpath($file, 0); - $content = file_get_contents($fullpathoffile); + $content = file_get_contents($fullpathoffile); - // New module - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; + // New module + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '600', 'Full', 'In', true, false, false, 0, '99%'); - print $doleditor->Create(1, '', false); - print '
    '; - print '
    '; - print ''; - print '   '; - print ''; - print '
    '; + $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format','aZ09')?GETPOST('format','aZ09'):'html')); + print '
    '; + print '
    '; + print ''; + print '   '; + print ''; + print '
    '; - print '
    '; + print ''; } - } + } - if ($tab == 'widgets') - { - require_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; + if ($tab == 'widgets') + { + require_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; $widgets = ModeleBoxes::getWidgetsList(array('/'.strtolower($module).'/core/boxes')); if ($action != 'editfile' || empty($file)) { - foreach ($widgets as $widget) - { - $pathtofile = $widget['relpath']; + if (! empty($widget)) + { + foreach ($widgets as $widget) + { + $pathtofile = $widget['relpath']; - print ' '.$langs->trans("WidgetFile").' : '.$pathtofile.''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; - print '
    '; - } + print ' '.$langs->trans("WidgetFile").' : '.$pathtofile.''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print '
    '; + } + } + else + { + print $langs->trans("NoWidget"); + } } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile=dol_buildpath($file, 0); - $content = file_get_contents($fullpathoffile); + $content = file_get_contents($fullpathoffile); - // New module - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; + // New module + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '600', 'Full', 'In', true, false, false, 0, '99%'); - print $doleditor->Create(1, '', false); - print '
    '; - print '
    '; - print ''; - print '   '; - print ''; - print '
    '; + $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format','aZ09')?GETPOST('format','aZ09'):'html')); + print '
    '; + print '
    '; + print ''; + print '   '; + print ''; + print '
    '; - print '
    '; + print ''; } - } + } - if ($tab == 'buildpackage') - { - if (! class_exists('ZipArchive') && ! defined('ODTPHP_PATHTOPCLZIP')) - { - print img_warning().' '.$langs->trans("ErrNoZipEngine"); - print '
    '; - } + if ($tab == 'cron') + { + $pathtofile = $modulelowercase.'/core/modules/mod'.$module.'.class.php'; - $modulelowercase=strtolower($module); + $cronjobs = $moduleobj->cronjobs; - // Zip file to build - $FILENAMEZIP=''; + if ($action != 'editfile' || empty($file)) + { + print $langs->trans("CronJobDefDesc", ''.$langs->trans('CronList').'').'
    '; + print '
    '; - // Load module - dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php'); - $class='mod'.$module; + print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print '
    '; - if (class_exists($class)) - { - try { - $moduleobj = new $class($db); - } - catch(Exception $e) - { - $error++; - dol_print_error($e->getMessage()); - } - } - else - { - $error++; - $langs->load("errors"); - dol_print_error($langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module)); - exit; - } + print '
    '; + print load_fiche_titre($langs->trans("CronJobProfiles"), '', ''); - $arrayversion=explode('.',$moduleobj->version,3); - if (count($arrayversion)) - { - $FILENAMEZIP="module_".$modulelowercase.'-'.$arrayversion[0].'.'.$arrayversion[1].($arrayversion[2]?".".$arrayversion[2]:"").".zip"; - $outputfile = dol_buildpath($modulelowercase, 0).'/bin/'.$FILENAMEZIP; + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; - $FILENAMEDOC=$modulelowercase.'.html'; - $outputfiledoc = dol_buildpath($modulelowercase, 0).'/doc/'.$FILENAMEDOC; - } + print '
    '; + print ''; - print '
    '; + print ''; + print_liste_field_titre("CronLabel",$_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder); + print_liste_field_titre("CronTask",'','',"",$param,'',$sortfield,$sortorder); + print_liste_field_titre("CronFrequency",'',"","",$param,'',$sortfield,$sortorder); + print_liste_field_titre("StatusAtInstall",$_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder); + print_liste_field_titre("Comment",$_SERVER["PHP_SELF"],"","",$param,'',$sortfield,$sortorder); + print "\n"; - print ' '. $langs->trans("PathToModulePackage") . ' : '; - if (! dol_is_file($outputfile)) print ''.$langs->trans("FileNotYetGenerated").''; - else { - print ''.$outputfile.''; - print ' ('.$langs->trans("GeneratedOn").' '.dol_print_date(dol_filemtime($outputfile), 'dayhour').')'; - } - print '
    '; + if (count($cronjobs)) + { + foreach ($cronjobs as $cron) + { + print ''; - print '
    '; + print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; - print '


    '; + print ''; - print ' '. $langs->trans("PathToModuleDocumentation") . ' : '; - if (! dol_is_file($outputfiledoc)) print ''.$langs->trans("FileNotYetGenerated").''; - else { - print ''.$outputfiledoc.''; - print ' ('.$langs->trans("GeneratedOn").' '.dol_print_date(dol_filemtime($outputfiledoc), 'dayhour').')'; - } - print '
    '; + print ''; - print '
    '; + print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - } + print ''; + } + } + else + { + print ''; + } - dol_fiche_end(); - } + print '
    '; + print $cron['label']; + print ''; + if ($cron['jobtype']=='method') + { + $text=$langs->trans("CronClass"); + $texttoshow=$langs->trans('CronModule').': '.$module.'
    '; + $texttoshow.=$langs->trans('CronClass').': '. $cron['class'].'
    '; + $texttoshow.=$langs->trans('CronObject').': '. $cron['objectname'].'
    '; + $texttoshow.=$langs->trans('CronMethod').': '. $cron['method']; + $texttoshow.='
    '.$langs->trans('CronArgs').': '. $cron['parameters']; + $texttoshow.='
    '.$langs->trans('Comment').': '. $langs->trans($cron['comment']); + } + elseif ($cron['jobtype']=='command') + { + $text=$langs->trans('CronCommand'); + $texttoshow=$langs->trans('CronCommand').': '.dol_trunc($cron['command']); + $texttoshow.='
    '.$langs->trans('CronArgs').': '. $cron['parameters']; + $texttoshow.='
    '.$langs->trans('Comment').': '. $langs->trans($cron['comment']); + } + print $form->textwithpicto($text, $texttoshow, 1); + print '
    '; + if($cron['unitfrequency'] == "60") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Minutes'); + if($cron['unitfrequency'] == "3600") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Hours'); + if($cron['unitfrequency'] == "86400") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Days'); + if($cron['unitfrequency'] == "604800") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Weeks'); + print ''; + print $cron['status']; + print ''; + if (!empty($cron['comment'])) {print $cron['comment'];} + print '
    '.$langs->trans("None").'
    '; + print '
    '; + + print ''; + } + else + { + $fullpathoffile=dol_buildpath($file, 0); + + $content = file_get_contents($fullpathoffile); + + // New module + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + + $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format','aZ09')?GETPOST('format','aZ09'):'html')); + print '
    '; + print '
    '; + print ''; + print '   '; + print ''; + print '
    '; + + print '
    '; + } + } + + if ($tab == 'buildpackage') + { + if (! class_exists('ZipArchive') && ! defined('ODTPHP_PATHTOPCLZIP')) + { + print img_warning().' '.$langs->trans("ErrNoZipEngine"); + print '
    '; + } + + $modulelowercase=strtolower($module); + + // Zip file to build + $FILENAMEZIP=''; + + // Load module + dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php'); + $class='mod'.$module; + + if (class_exists($class)) + { + try { + $moduleobj = new $class($db); + } + catch(Exception $e) + { + $error++; + dol_print_error($e->getMessage()); + } + } + else + { + $error++; + $langs->load("errors"); + dol_print_error($langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module)); + exit; + } + + $arrayversion=explode('.',$moduleobj->version,3); + if (count($arrayversion)) + { + $FILENAMEZIP="module_".$modulelowercase.'-'.$arrayversion[0].'.'.$arrayversion[1].($arrayversion[2]?".".$arrayversion[2]:"").".zip"; + $outputfilezip = dol_buildpath($modulelowercase, 0).'/bin/'.$FILENAMEZIP; + + $FILENAMEDOC=$modulelowercase.'.html'; + $outputfiledoc = dol_buildpath($modulelowercase, 0).'/doc/'.$FILENAMEDOC; + } + + print '
    '; + + print ' '. $langs->trans("PathToModulePackage") . ' : '; + if (! dol_is_file($outputfilezip)) print ''.$langs->trans("FileNotYetGenerated").''; + else { + $relativepath = $modulelowercase.'/bin/'.$FILENAMEZIP; + print ''.$outputfilezip.''; + print ' ('.$langs->trans("GeneratedOn").' '.dol_print_date(dol_filemtime($outputfilezip), 'dayhour').')'; + } + print '
    '; + + print '
    '; + + print '
    '; + print ''; + print ''; + print ''; + print ''; + print '
    '; + + print '


    '; + + print ' '. $langs->trans("PathToModuleDocumentation") . ' : '; + if (! dol_is_file($outputfiledoc)) print ''.$langs->trans("FileNotYetGenerated").''; + else { + print ''.$outputfiledoc.''; + print ' ('.$langs->trans("GeneratedOn").' '.dol_print_date(dol_filemtime($outputfiledoc), 'dayhour').')'; + } + print '
    '; + + print '
    '; + + print '
    '; + print ''; + print ''; + print ''; + print ''; + print '
    '; + } + + if ($tab != 'description') + { + dol_fiche_end(); + } + } } -dol_fiche_end(); +dol_fiche_end(); // End modules diff --git a/htdocs/modulebuilder/template/ChangeLog.md b/htdocs/modulebuilder/template/ChangeLog.md index 0f04e316f58..99f4f673c0c 100644 --- a/htdocs/modulebuilder/template/ChangeLog.md +++ b/htdocs/modulebuilder/template/ChangeLog.md @@ -1,4 +1,4 @@ -# CHANGELOG FOR DOLIBARR ERP CRM +# CHANGELOG MYMODULE FOR DOLIBARR ERP CRM ## 1.0 Initial version diff --git a/htdocs/modulebuilder/template/README.md b/htdocs/modulebuilder/template/README.md index 3385110838d..658baf212fa 100644 --- a/htdocs/modulebuilder/template/README.md +++ b/htdocs/modulebuilder/template/README.md @@ -1,4 +1,4 @@ -# MYMODULE FOR DOLIBARR ERP CRM +# MYMODULE FOR DOLIBARR ERP CRM ## Features MyModuleDescription diff --git a/htdocs/modulebuilder/template/admin/about.php b/htdocs/modulebuilder/template/admin/about.php index ac21d2810e0..c2adc8040d1 100644 --- a/htdocs/modulebuilder/template/admin/about.php +++ b/htdocs/modulebuilder/template/admin/about.php @@ -72,24 +72,13 @@ $page_name = "MyModuleAbout"; llxHeader('', $langs->trans($page_name)); // Subheader -$linkback = '' - . $langs->trans("BackToModuleList") . ''; -print load_fiche_titre($langs->trans($page_name), $linkback); +$linkback = '' . $langs->trans("BackToModuleList") . ''; + +print load_fiche_titre($langs->trans($page_name), $linkback, 'object_mymodule@mymodule'); // Configuration header $head = mymoduleAdminPrepareHead(); -dol_fiche_head( - $head, - 'about', - $langs->trans("MyModuleName"), - 0, - 'mymodule@mymodule' -); - -// About page goes here -echo $langs->trans("MyModuleAboutPage"); - -echo '
    '; +dol_fiche_head($head, 'about', '', 0, 'mymodule@mymodule'); dol_include_once('/mymodule/core/modules/modMyModule.class.php'); $tmpmodule = new modMyModule($db); diff --git a/htdocs/modulebuilder/template/admin/setup.php b/htdocs/modulebuilder/template/admin/setup.php index d32bd0a1723..c031e67a346 100644 --- a/htdocs/modulebuilder/template/admin/setup.php +++ b/htdocs/modulebuilder/template/admin/setup.php @@ -42,8 +42,9 @@ global $langs, $user; require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php"; require_once '../lib/mymodule.lib.php'; //require_once "../class/myclass.class.php"; + // Translations -$langs->load("mymodule@mymodule"); +$langs->loadLangs(array("admin", "mymodule@mymodule")); // Access control if (! $user->admin) accessforbidden(); @@ -51,6 +52,8 @@ if (! $user->admin) accessforbidden(); // Parameters $action = GETPOST('action', 'alpha'); +$arrayofparameters=array('MYMODULE_MYPARAM1'=>array('css'=>'minwidth200'), 'MYMODULE_MYPARAM2'=>array('css'=>'minwidth500')); + /* * Actions @@ -69,21 +72,63 @@ llxHeader('', $langs->trans($page_name)); // Subheader $linkback = '' . $langs->trans("BackToModuleList") . ''; -print load_fiche_titre($langs->trans($page_name), $linkback); +print load_fiche_titre($langs->trans($page_name), $linkback, 'object_mymodule@mymodule'); // Configuration header $head = mymoduleAdminPrepareHead(); -dol_fiche_head( - $head, - 'settings', - $langs->trans("Module500000Name"), - 0, - "mymodule@mymodule" -); +dol_fiche_head($head, 'settings', '', -1, "mymodule@mymodule"); // Setup page goes here echo $langs->trans("MyModuleSetupPage"); + +if ($action == 'edit') +{ + print '
    '; + print ''; + print ''; + + print ''; + print ''; + + foreach($arrayofparameters as $key => $val) + { + print ''; + } + + print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; + print $form->textwithpicto($langs->trans($key),$langs->trans($key.'Tooltip')); + print '
    '; + + print '
    '; + print ''; + print '
    '; + + print '
    '; + print '
    '; +} +else +{ + print ''; + print ''; + + foreach($arrayofparameters as $key => $val) + { + print ''; + } + + print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; + print $form->textwithpicto($langs->trans($key),$langs->trans($key.'Tooltip')); + print '' . $conf->global->$key . '
    '; + + print '
    '; + print ''.$langs->trans("Modify").''; + print '
    '; +} + + // Page end dol_fiche_end(); + llxFooter(); +$db->close(); diff --git a/htdocs/modulebuilder/template/class/MyObject.txt b/htdocs/modulebuilder/template/class/MyObject.txt deleted file mode 100644 index 35eb3529698..00000000000 --- a/htdocs/modulebuilder/template/class/MyObject.txt +++ /dev/null @@ -1,2 +0,0 @@ -# DO NOT DELETE THIS FILE MANUALLY -# If this file exists, it means the class and file for object MyOjbect was generated by ModuleBuilder. So prefer to use ModuleBuilder if you want to delete object. \ No newline at end of file diff --git a/htdocs/modulebuilder/template/class/actions_mymodule.class.php b/htdocs/modulebuilder/template/class/actions_mymodule.class.php index b8b43f1359d..b0265a28e3f 100644 --- a/htdocs/modulebuilder/template/class/actions_mymodule.class.php +++ b/htdocs/modulebuilder/template/class/actions_mymodule.class.php @@ -78,15 +78,11 @@ class ActionsMyModule $error = 0; // Error counter - /* - print_r($parameters); - print_r($object); - echo "action: " . $action; - */ - - if (in_array($parameters['currentcontext'], array('somecontext1','somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2' - - + /* print_r($parameters); print_r($object); echo "action: " . $action; */ + if (in_array($parameters['currentcontext'], array('somecontext1','somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' + { + // Do what you want here... + // You can for example call global vars like $fieldstosearchall to overwrite them, or update database depending on $action and $_POST values. } if (! $error) { @@ -115,14 +111,9 @@ class ActionsMyModule $error = 0; // Error counter - /* - print_r($parameters); - print_r($object); - echo "action: " . $action; - */ - - if (in_array($parameters['currentcontext'], array('somecontext1','somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2' - + /* print_r($parameters); print_r($object); echo "action: " . $action; */ + if (in_array($parameters['currentcontext'], array('somecontext1','somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' + { foreach($parameters['toselect'] as $objectid) { // Do action on each object id @@ -156,7 +147,8 @@ class ActionsMyModule $error = 0; // Error counter - if (in_array($parameters['currentcontext'], array('somecontext1','somecontext2'))) // do something only for the context 'somecontext' + /* print_r($parameters); print_r($object); echo "action: " . $action; */ + if (in_array($parameters['currentcontext'], array('somecontext1','somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' { $this->resprints = ''; } @@ -171,4 +163,64 @@ class ActionsMyModule + /** + * Execute action + * + * @param array $parameters Array of parameters + * @param Object $object Object output on PDF + * @param string $action 'add', 'update', 'view' + * @return int <0 if KO, + * =0 if OK but we want to process standard actions too, + * >0 if OK and we want to replace standard actions. + */ + function beforePDFCreation($parameters, &$object, &$action) + { + global $langs,$conf; + global $hookmanager; + + $outputlangs=$langs; + + $ret=0; $deltemp=array(); + dol_syslog(get_class($this).'::executeHooks action='.$action); + + /* print_r($parameters); print_r($object); echo "action: " . $action; */ + if (in_array($parameters['currentcontext'], array('somecontext1','somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' + { + + } + + return $ret; + } + + /** + * Execute action + * + * @param array $parameters Array of parameters + * @param Object $pdfhandler PDF builder handler + * @param string $action 'add', 'update', 'view' + * @return int <0 if KO, + * =0 if OK but we want to process standard actions too, + * >0 if OK and we want to replace standard actions. + */ + function afterPDFCreation($parameters, &$pdfhandler, &$action) + { + global $langs,$conf; + global $hookmanager; + + $outputlangs=$langs; + + $ret=0; $deltemp=array(); + dol_syslog(get_class($this).'::executeHooks action='.$action); + + /* print_r($parameters); print_r($object); echo "action: " . $action; */ + if (in_array($parameters['currentcontext'], array('somecontext1','somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' + { + + } + + return $ret; + } + + /* Add here any other hooked methods... */ + } diff --git a/htdocs/modulebuilder/template/class/api_myobject.class.php b/htdocs/modulebuilder/template/class/api_mymodule.class.php similarity index 89% rename from htdocs/modulebuilder/template/class/api_myobject.class.php rename to htdocs/modulebuilder/template/class/api_mymodule.class.php index e3e38cefd38..a068715b521 100644 --- a/htdocs/modulebuilder/template/class/api_myobject.class.php +++ b/htdocs/modulebuilder/template/class/api_mymodule.class.php @@ -18,8 +18,12 @@ use Luracast\Restler\RestException; +dol_include_once('/mymodule/class/myobject.class.php'); + + + /** - * \file htdocs/modulebuilder/template/class/api_myobject.class.php + * \file htdocs/modulebuilder/template/class/api_mymodule.class.php * \ingroup mymodule * \brief File for API management of myobject. */ @@ -31,7 +35,7 @@ use Luracast\Restler\RestException; * @access protected * @class DolibarrApiAccess {@requires user,external} */ -class MyObjectApi extends DolibarrApi +class MyModuleApi extends DolibarrApi { /** * @var array $FIELDS Mandatory fields, checked when create and update object @@ -40,6 +44,7 @@ class MyObjectApi extends DolibarrApi 'name' ); + /** * @var MyObject $myobject {@type MyObject} */ @@ -48,7 +53,7 @@ class MyObjectApi extends DolibarrApi /** * Constructor * - * @url GET myobject/ + * @url GET / * */ function __construct() @@ -66,7 +71,7 @@ class MyObjectApi extends DolibarrApi * @param int $id ID of myobject * @return array|mixed data without useless information * - * @url GET myobject/{id} + * @url GET myobjects/{id} * @throws RestException */ function get($id) @@ -87,22 +92,24 @@ class MyObjectApi extends DolibarrApi return $this->_cleanObjectDatas($this->myobject); } + /** * List myobjects * * Get a list of myobjects * - * @param int $mode Use this param to filter list - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101') or (t.import_key:=:'20160101')" - * @return array Array of myobject objects + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return array Array of order objects + * + * @throws RestException * * @url GET /myobjects/ */ - function index($mode, $sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -183,7 +190,7 @@ class MyObjectApi extends DolibarrApi * @param array $request_data Request datas * @return int ID of myobject * - * @url POST myobject/ + * @url POST myobjects/ */ function post($request_data = NULL) { @@ -209,7 +216,7 @@ class MyObjectApi extends DolibarrApi * @param array $request_data Datas * @return int * - * @url PUT myobject/{id} + * @url PUT myobjects/{id} */ function put($id, $request_data = NULL) { @@ -231,7 +238,7 @@ class MyObjectApi extends DolibarrApi } if($this->myobject->update($id, DolibarrApiAccess::$user)) - return $this->get ($id); + return $this->get($id); return false; } diff --git a/htdocs/modulebuilder/template/class/myobject.class.php b/htdocs/modulebuilder/template/class/myobject.class.php index f75e40f2730..90026e7389c 100644 --- a/htdocs/modulebuilder/template/class/myobject.class.php +++ b/htdocs/modulebuilder/template/class/myobject.class.php @@ -1,8 +1,5 @@ - * Copyright (C) 2014-2016 Juanjo Menent - * Copyright (C) 2015 Florian Henry - * Copyright (C) 2015 Raphaël Doursenaud +/* Copyright (C) 2017 Laurent Destailleur * Copyright (C) ---Put here your own copyright and developer email--- * * This program is free software; you can redistribute it and/or modify @@ -43,47 +40,67 @@ class MyObject extends CommonObject * @var string Name of table without prefix where object is stored */ public $table_element = 'myobject'; - - /** - * @var array Does this field is linked to a thirdparty ? - */ - protected $isnolinkedbythird = 1; /** * @var array Does myobject support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe */ - protected $ismultientitymanaged = 1; + public $ismultientitymanaged = 0; /** - * @var string String with name of icon for myobject + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ - public $picto = 'myobject'; + public $picto = 'myobject@mymodule'; /** - * 'type' if the field format, 'label' the translation key, 'enabled' is a condition when the filed must be managed, - * 'visible' says if field is visible in list (-1 means not shown by default but can be aded into list to be viewed) - * 'notnull' if not null in database - * 'index' if we want an index in database - * 'position' is the sort order of field - * 'searchall' is 1 if we want to search in this field when making a search from the quick search button - * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). - * 'comment' is not used. You can store here any text of your choice. + * 'type' if the field format. + * 'label' the translation key. + * 'enabled' is a condition when the field must be managed. + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only. Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'position' is the sort order of field. + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'help' is a string visible as a tooltip on field + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'default' is a default value for creation (can still be replaced by the global setup of default values) + * 'showoncombobox' if field must be shown into the label of combobox */ // BEGIN MODULEBUILDER PROPERTIES /** - * @var array Array with all fields and their property + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ public $fields=array( - 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>true, 'index'=>true, 'position'=>1, 'comment'=>'Id'), - 'ref' =>array('type'=>'varchar(64)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>true, 'index'=>true, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), - 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=>true, 'index'=>true, 'position'=>20), - 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1), - 'qty' =>array('type'=>'double(24,8)', 'label'=>'Qty', 'enabled'=>1, 'visible'=>1, 'position'=>40, 'searchall'=>0, 'isameasure'=>1), - 'status' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'index'=>true, 'position'=>1000), - 'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>true, 'position'=>500), - 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>true, 'position'=>500), - 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'index'=>true, 'position'=>1000, 'nullifempty'=>1), + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), + 'ref' =>array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), + 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'css'=>'minwidth200', 'help'=>'Help text'), + 'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>1, 'default'=>'null', 'position'=>40, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text'), + 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>'LinkToThirparty'), + 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>60), + 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>61), + 'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501), + //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502), + 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510), + 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511), + //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000), + 'status' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>-1, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')), ); + + public $rowid; + public $ref; + public $entity; + public $label; + public $amount; + public $status; + public $date_creation; + public $tms; + public $fk_user_creat; + public $fk_user_modif; + public $import_key; // END MODULEBUILDER PROPERTIES @@ -120,20 +137,138 @@ class MyObject extends CommonObject */ public function __construct(DoliDB $db) { + global $conf; + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; } + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + /** + * Clone and object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $hookmanager, $langs; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $object->fetchCommon($fromid); + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + // Clear fields + $object->ref = "copy_of_".$object->ref; + $object->title = $langs->trans("CopyOf")." ".$object->title; + // ... + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + /*public function fetchLines() + { + $this->lines=array(); + + // Load lines with object MyObjectLine + + return count($this->lines)?1:0; + }*/ + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + } /** * Return a link to the object card (with optionaly the picto) * - * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) - * @param string $option On what the link point to - * @param int $notooltip 1=Disable tooltip - * @param string $morecss Add more css on link - * @return string String with URL + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - function getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='') + function getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1) { global $db, $conf, $langs; global $dolibarr_main_authentication, $dolibarr_main_demo; @@ -148,7 +283,15 @@ class MyObject extends CommonObject $label.= '
    '; $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; - $url = $url = dol_buildpath('/mymodule/m_card.php',1).'?id='.$this->id; + $url = dol_buildpath('/mymodule/myobject_card.php',1).'?id='.$this->id; + + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } $linkclose=''; if (empty($notooltip)) @@ -167,12 +310,12 @@ class MyObject extends CommonObject $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) - { - $result.=($linkstart.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend); - if ($withpicto != 2) $result.=' '; - } - $result.= $linkstart . $this->ref . $linkend; + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; + //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + return $result; } @@ -191,7 +334,7 @@ class MyObject extends CommonObject * 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 + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto * @return string Label of status */ static function LibStatut($status,$mode=0) @@ -236,6 +379,59 @@ class MyObject extends CommonObject } } + /** + * Charge les informations d'ordre info dans l'objet commande + * + * @param int $id Id of order + * @return void + */ + function info($id) + { + $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; + $sql.= ' fk_user_creat, fk_user_modif'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql.= ' WHERE t.rowid = '.$id; + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if ($obj->fk_user_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + + } + else + { + dol_print_error($this->db); + } + } /** * Initialise object with example values @@ -248,23 +444,39 @@ class MyObject extends CommonObject $this->initAsSpecimenCommon(); } + + /** + * Action executed by scheduler + * CAN BE A CRON TASK + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function doScheduledJob() + { + global $conf, $langs; + + $this->output = ''; + $this->error=''; + + dol_syslog(__METHOD__, LOG_DEBUG); + + // ... + + return 0; + } } /** - * Class MyModuleObjectLine + * Class MyObjectLine. You can also remove this and generate a CRUD class for lines objects. */ -class MyModuleObjectLine +/* +class MyObjectLine { - /** - * @var int ID - */ + // @var int ID public $id; - /** - * @var mixed Sample line property 1 - */ + // @var mixed Sample line property 1 public $prop1; - /** - * @var mixed Sample line property 2 - */ + // @var mixed Sample line property 2 public $prop2; } +*/ \ No newline at end of file diff --git a/htdocs/modulebuilder/template/core/boxes/README.md b/htdocs/modulebuilder/template/core/boxes/README.md new file mode 100644 index 00000000000..b641e7136bc --- /dev/null +++ b/htdocs/modulebuilder/template/core/boxes/README.md @@ -0,0 +1 @@ +Directory where widgets files are stored. \ No newline at end of file diff --git a/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php b/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php new file mode 100644 index 00000000000..cd8612cb7d1 --- /dev/null +++ b/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php @@ -0,0 +1,200 @@ + + * + * This file is an example to follow to add your own email selector inside + * the Dolibarr email tool. + * Follow instructions given in README file to know what to change to build + * your own emailing list selector. + * Code that need to be changed in this file are marked by "CHANGE THIS" tag. + */ + +include_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php'; +dol_include_once("/mymodule/class/myobject.class.php"); + + +/** + * mailing_mailinglist_mymodule + */ +class mailing_mailinglist_mymodule_myobject extends MailingTargets +{ + // CHANGE THIS: Put here a name not already used + var $name='mailinglist_mymodule_myobject'; + // CHANGE THIS: Put here a description of your selector module + var $desc='My object emailing target selector'; + // CHANGE THIS: Set to 1 if selector is available for admin users only + var $require_admin=0; + + var $enabled=0; + var $require_module=array(); + var $picto='mymodule@mymodule'; + var $db; + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + global $conf; + + $this->db=$db; + if (is_array($conf->modules)) + { + $this->enabled=in_array('mymodule',$conf->modules)?1:0; + } + } + + + /** + * Affiche formulaire de filtre qui apparait dans page de selection des destinataires de mailings + * + * @return string Retourne zone select + */ + function formFilter() + { + global $langs; + $langs->load("members"); + + $form=new Form($this->db); + + $arraystatus=array(1=>'Option 1', 2=>'Option 2'); + + $s=''; + $s.=$langs->trans("Status").': '; + $s.=''; + $s.='
    '; + + return $s; + } + + + /** + * Renvoie url lien vers fiche de la source du destinataire du mailing + * + * @param int $id ID + * @return string Url lien + */ + function url($id) + { + return ''.img_object('',"generic").''; + } + + + /** + * This is the main function that returns the array of emails + * + * @param int $mailing_id Id of emailing + * @param array $filtersarray Requete sql de selection des destinataires + * @return int <0 if error, number of emails added if ok + */ + function add_to_target($mailing_id,$filtersarray=array()) + { + $target = array(); + $cibles = array(); + $j = 0; + + + $sql = " select rowid as id, email, firstname, lastname, plan, partner"; + $sql.= " from ".MAIN_DB_PREFIX."myobject"; + $sql.= " where email IS NOT NULL AND email != ''"; + if (! empty($_POST['filter']) && $_POST['filter'] != 'none') $sql.= " AND status = '".$this->db->escape($_POST['filter'])."'"; + $sql.= " ORDER BY email"; + + // Stocke destinataires dans cibles + $result=$this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + + dol_syslog("mailinglist_mymodule_myobject.modules.php: mailing ".$num." targets found"); + + $old = ''; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + if ($old <> $obj->email) + { + $cibles[$j] = array( + 'email' => $obj->email, + 'name' => $obj->lastname, + 'id' => $obj->id, + 'firstname' => $obj->firstname, + 'other' => $obj->plan.';'.$obj->partner, + 'source_url' => $this->url($obj->id), + 'source_id' => $obj->id, + 'source_type' => 'dolicloud' + ); + $old = $obj->email; + $j++; + } + + $i++; + } + } + else + { + dol_syslog($this->db->error()); + $this->error=$this->db->error(); + return -1; + } + + // You must fill the $target array with record like this + // $target[0]=array('email'=>'email_0','name'=>'name_0','firstname'=>'firstname_0'); + // ... + // $target[n]=array('email'=>'email_n','name'=>'name_n','firstname'=>'firstname_n'); + + // Example: $target[0]=array('email'=>'myemail@mydomain.com','name'=>'Doe','firstname'=>'John'); + + // ----- Your code end here ----- + + return parent::add_to_target($mailing_id, $cibles); + } + + + /** + * On the main mailing area, there is a box with statistics. + * If you want to add a line in this report you must provide an + * array of SQL request that returns two field: + * One called "label", One called "nb". + * + * @return array + */ + function getSqlArrayForStats() + { + // CHANGE THIS: Optionnal + + //var $statssql=array(); + //$this->statssql[0]="SELECT field1 as label, count(distinct(email)) as nb FROM mytable WHERE email IS NOT NULL"; + + return array(); + } + + + /** + * Return here number of distinct emails returned by your selector. + * For example if this selector is used to extract 500 different + * emails from a text file, this function must return 500. + * + * @param string $filter Filter + * @param string $option Options + * @return int Nb of recipients or -1 if KO + */ + function getNbOfRecipients($filter=1,$option='') + { + $a=parent::getNbOfRecipients("select count(distinct(email)) as nb from ".MAIN_DB_PREFIX."myobject as p where email IS NOT NULL AND email != ''"); + + if ($a < 0) return -1; + return $a; + } + +} + diff --git a/htdocs/modulebuilder/template/core/modules/modMyModule.class.php b/htdocs/modulebuilder/template/core/modules/modMyModule.class.php index 8f8079b1d46..63a132699b7 100644 --- a/htdocs/modulebuilder/template/core/modules/modMyModule.class.php +++ b/htdocs/modulebuilder/template/core/modules/modMyModule.class.php @@ -56,10 +56,10 @@ class modMyModule extends DolibarrModules // Family can be 'crm','financial','hr','projects','products','ecm','technic','interface','other' // It is used to group modules by family in module setup page $this->family = "other"; - // Module position in the family - $this->module_position = 500; + // Module position in the family on 2 digits ('01', '10', '20', ...) + $this->module_position = '90'; // Gives the possibility to the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this) - //$this->familyinfo = array('myownfamily' => array('position' => '001', 'label' => $langs->trans("MyOwnFamily"))); + //$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily"))); // Module label (no space allowed), used if translation string 'ModuleMyModuleName' not found (MyModue is name of module). $this->name = preg_replace('/^mod/i','',get_class($this)); @@ -95,7 +95,7 @@ class modMyModule extends DolibarrModules 'models' => 0, // Set this to 1 if module has its own models directory (core/modules/xxx) 'css' => array('/mymodule/css/mymodule.css.php'), // Set this to relative path of css file if module has its own css file 'js' => array('/mymodule/js/mymodule.js.php'), // Set this to relative path of js file if module must load a js on all pages - 'hooks' => array('hookcontext1','hookcontext2') // Set here all hooks context managed by module. You can also set hook context 'all' + 'hooks' => array('data'=>array('hookcontext1','hookcontext2'), 'entity'=>'0') // Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context 'all' ); // Data directories to create when module is enabled. @@ -125,13 +125,22 @@ class modMyModule extends DolibarrModules 1=>array('MYMODULE_MYCONSTANT', 'chaine', 'avalue', 'This is a constant to add', 1, 'allentities', 1) ); + + if (! isset($conf->mymodule) || ! isset($conf->mymodule->enabled)) + { + $conf->mymodule=new stdClass(); + $conf->mymodule->enabled=0; + } + + // Array to add new pages in new tabs - // Example: $this->tabs = array('objecttype:+tabname1:Title1:mylangfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__', // To add a new tab identified by code tabname1 - // 'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@mymodule:$user->rights->othermodule->read:/mymodule/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key. - // 'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname - // Can also be: $this->tabs = array('data'=>'...', 'entity'=>0); + $this->tabs = array(); + // Example: + // $this->tabs[] = array('data'=>'objecttype:+tabname1:Title1:mylangfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'); // To add a new tab identified by code tabname1 + // $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@mymodule:$user->rights->othermodule->read:/mymodule/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key. + // $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname // - // where objecttype can be + // Where objecttype can be // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member) // 'contact' to add a tab in contact view // 'contract' to add a tab in contract view @@ -151,13 +160,7 @@ class modMyModule extends DolibarrModules // 'stock' to add a tab in stock view // 'thirdparty' to add a tab in third party view // 'user' to add a tab in user view - $this->tabs = array(); - if (! isset($conf->mymodule) || ! isset($conf->mymodule->enabled)) - { - $conf->mymodule=new stdClass(); - $conf->mymodule->enabled=0; - } // Dictionaries $this->dictionaries=array(); @@ -187,11 +190,12 @@ class modMyModule extends DolibarrModules // Cronjobs (List of cron jobs entries to add when module is enabled) + // unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week $this->cronjobs = array( - 0=>array('label'=>'MyJob label', 'jobtype'=>'method', 'class'=>'/mymodule/class/mymodulemyjob.class.php', 'objectname'=>'MyModuleMyJob', 'method'=>'myMethod', 'parameters'=>'', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>true) + 0=>array('label'=>'MyJob label', 'jobtype'=>'method', 'class'=>'/mymodule/class/myobject.class.php', 'objectname'=>'MyObject', 'method'=>'doScheduledJob', 'parameters'=>'', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>true) ); - // Example: $this->cronjobs=array(0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>true), - // 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>true) + // Example: $this->cronjobs=array(0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>true), + // 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>true) // ); @@ -200,21 +204,21 @@ class modMyModule extends DolibarrModules $r=0; $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Read objects of My Module'; // Permission label + $this->rights[$r][1] = 'Read myobject of MyModule'; // Permission label $this->rights[$r][3] = 1; // Permission by default for new user (0/1) $this->rights[$r][4] = 'read'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) $r++; $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Create/Update objects of My Module'; // Permission label + $this->rights[$r][1] = 'Create/Update myobject of MyModule'; // Permission label $this->rights[$r][3] = 1; // Permission by default for new user (0/1) $this->rights[$r][4] = 'create'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) $r++; $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Delete objects of My Module'; // Permission label + $this->rights[$r][1] = 'Delete myobject of MyModule'; // Permission label $this->rights[$r][3] = 1; // Permission by default for new user (0/1) $this->rights[$r][4] = 'delete'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) @@ -249,7 +253,7 @@ class modMyModule extends DolibarrModules 'type'=>'left', // This is a Left menu entry 'titre'=>'List MyObject', 'mainmenu'=>'mymodule', - 'leftmenu'=>'mymodule', + 'leftmenu'=>'mymodule_myobject_list', 'url'=>'/mymodule/myobject_list.php', 'langs'=>'mymodule@mymodule', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. 'position'=>1000+$r, @@ -261,7 +265,7 @@ class modMyModule extends DolibarrModules 'type'=>'left', // This is a Left menu entry 'titre'=>'New MyObject', 'mainmenu'=>'mymodule', - 'leftmenu'=>'mymodule', + 'leftmenu'=>'mymodule_myobject_new', 'url'=>'/mymodule/myobject_page.php?action=create', 'langs'=>'mymodule@mymodule', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. 'position'=>1000+$r, @@ -275,23 +279,23 @@ class modMyModule extends DolibarrModules // Exports $r=1; - // Example: - /* BEGIN MODULEBUILDER EXPORT MYOBJECT + /* BEGIN MODULEBUILDER EXPORT MYOBJECT */ + /* + $langs->load("mymodule@mymodule"); $this->export_code[$r]=$this->rights_class.'_'.$r; - $this->export_label[$r]='MyModule'; // Translation key (used only if key ExportDataset_xxx_z not found) - $this->export_enabled[$r]='1'; // Condition to show export in list (ie: '$user->id==3'). Set to 1 to always show when module is enabled. - $this->export_icon[$r]='generic:MyModule'; // Put here code of icon then string for translation key of module name - //$this->export_permission[$r]=array(array("mymodule","level1","level2")); - $this->export_fields_array[$r]=array('t.rowid'=>"Id",'t.ref'=>'Ref','t.label'=>'Label','t.datec'=>"DateCreation",'t.tms'=>"DateUpdate"); - $this->export_TypeFields_array[$r]=array('t.rowid'=>'Numeric', 't.ref'=>'Text', 't.label'=>'Label', 't.datec'=>"Date", 't.tms'=>"Date"); - // $this->export_entities_array[$r]=array('t.rowid'=>"company",'s.nom'=>'company','s.address'=>'company','s.zip'=>'company','s.town'=>'company','s.fk_pays'=>'company','s.phone'=>'company','s.siren'=>'company','s.siret'=>'company','s.ape'=>'company','s.idprof4'=>'company','s.code_compta'=>'company','s.code_compta_fournisseur'=>'company','f.rowid'=>"invoice",'f.facnumber'=>"invoice",'f.datec'=>"invoice",'f.datef'=>"invoice",'f.total'=>"invoice",'f.total_ttc'=>"invoice",'f.tva'=>"invoice",'f.paye'=>"invoice",'f.fk_statut'=>'invoice','f.note'=>"invoice",'fd.rowid'=>'invoice_line','fd.description'=>"invoice_line",'fd.price'=>"invoice_line",'fd.total_ht'=>"invoice_line",'fd.total_tva'=>"invoice_line",'fd.total_ttc'=>"invoice_line",'fd.tva_tx'=>"invoice_line",'fd.qty'=>"invoice_line",'fd.date_start'=>"invoice_line",'fd.date_end'=>"invoice_line",'fd.fk_product'=>'product','p.ref'=>'product'); - // $this->export_dependencies_array[$r]=array('invoice_line'=>'fd.rowid','product'=>'fd.rowid'); // To add unique key if we ask a field of a child to avoid the DISTINCT to discard them - // $this->export_sql_start[$r]='SELECT DISTINCT '; - // $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'myobject as t'; - // $this->export_sql_order[$r] .=' ORDER BY t.ref'; - // $r++; - END MODULEBUILDER EXPORT MYOBJECT */ - + $this->export_label[$r]='MyObjectLines'; // Translation key (used only if key ExportDataset_xxx_z not found) + $this->export_icon[$r]='myobject@mymodule'; + $keyforclass = 'MyObject'; $keyforclassfile='/mymobule/class/myobject.class.php'; $keyforelement='myobject'; + include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php'; + $keyforselect='myobject'; $keyforaliasextra='extra'; $keyforelement='myobject'; + include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php'; + //$this->export_dependencies_array[$r]=array('mysubobject'=>'ts.rowid', 't.myfield'=>array('t.myfield2','t.myfield3')); // To force to activate one or several fields if we select some fields that need same (like to select a unique key if we ask a field of a child to avoid the DISTINCT to discard them, or for computed field than need several other fields) + $this->export_sql_start[$r]='SELECT DISTINCT '; + $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'myobject as t'; + $this->export_sql_end[$r] .=' WHERE 1 = 1'; + $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('myobject').')'; + $r++; */ + /* END MODULEBUILDER EXPORT MYOBJECT */ } /** @@ -304,15 +308,19 @@ class modMyModule extends DolibarrModules */ public function init($options='') { - $sql = array(); - $this->_load_tables('/mymodule/sql/'); // Create extrafields include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); - //$result1=$extrafields->addExtraField('myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty'); - //$result2=$extrafields->addExtraField('myattr2', "New Attr 2 label", 'string', 1, 10, 'project'); + + //$result1=$extrafields->addExtraField('myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty', 0, 0, '', '', 1, '', 0, 0, '', '', 'mymodule@mymodule'); + //$result2=$extrafields->addExtraField('myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project', 0, 0, '', '', 1, '', 0, 0, '', '', 'mymodule@mymodule'); + //$result3=$extrafields->addExtraField('myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', 0, 0, '', '', 'mymodule@mymodule'); + //$result4=$extrafields->addExtraField('myattr4', "New Attr 4 label", 'select', 1, 3, 'thirdparty', 0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1); + //$result5=$extrafields->addExtraField('myattr5', "New Attr 5 label", 'text', 1, 10, 'user', 0, 0, '', '', 1, '', 0, 0, '', '', 'mymodule@mymodule'); + + $sql = array(); return $this->_init($sql, $options); } diff --git a/htdocs/modulebuilder/template/core/triggers/README.md b/htdocs/modulebuilder/template/core/triggers/README.md new file mode 100644 index 00000000000..38d1b1d8961 --- /dev/null +++ b/htdocs/modulebuilder/template/core/triggers/README.md @@ -0,0 +1 @@ +Directory where triggers files are stored. \ No newline at end of file diff --git a/htdocs/modulebuilder/template/doc/Specifications.asciidoc b/htdocs/modulebuilder/template/doc/Specifications.asciidoc index 7b1711cf514..adfaeb4e9b5 100644 --- a/htdocs/modulebuilder/template/doc/Specifications.asciidoc +++ b/htdocs/modulebuilder/template/doc/Specifications.asciidoc @@ -1 +1,127 @@ -# SPECIFICATIONS OF MODULE MYMODULE FOR DOLIBARR ERP CRM \ No newline at end of file += MYMODULE = +Copyright (C) ---Put here your own copyright and developer email--- +:subtitle: MYMODULE SPECIFICATIONS + + + +== Topic of document + +This document was build from following input: + +* Date 1 +... + +* Date 2 +... + + +The document includes an introductory chapter of functional specifications, presenting the different actors involved in the rebuild of the definitions +of business terms that will be used (some of which may be new or different). +The main following chapter will present the entire process, also known as *uses cases*, according to a principle of a description, in chronological sequence if possible, +to present the actor and the action performed, as in the following example: + +* *X* Actor realizes Action A. +* *Y* Actor communicates Info B to Actor *Z* +* *Automaton* performs update of data for... +* Etc ... + +Functional requirements are complemented by a chapter of technical requirements. +The chapter on data lists key information specific to Presto that were identified at the time of writing specification. It will be enriched as +iterations occurs. + +Finally, in the Appendix, the documents known when writing this document are centralized to illustrate the existing document or inspire the new expected one. +These documents have their content directly integrated in this specification or have a reference to +external documents stored in the *Appendices* directory accompanying this document. + + + +*Log of versions* + +[options="header",format="csv"] +|=== +Author, Date, Version +John Doe, Date YYY-MM-DD, Version 1.0 +|=== + + + +<<< + + +== BUSINESS SPECIFICATIONS - INTRODUCTION + +=== List of actors [[actors]] + +Actors are physical people or moral entities working on at least one process. +The following chart prensts list of actors or partners identified by the project for the defined scope of project. We will use then the name defined into first column to speak about roles in the rest of documents. + +[options="header",format="csv"] +|=== +Actor/profil/role, Description of role, Access to system or not, Example of actor +Customer Service, Receive and create Sales orders (SO), Yes, Mr Smith +Purchase, Make puchase order (PO), Yes, 5 people +Administrator - IT, Administration of users/groups and IT services, Yes, John Doe +Automaton, Execute automatic data processing, Yes, NA +|=== + + +=== Definitions [[definitions]] + +To understand the descriptions of the target process, it was necessary to define or redefine some vocabulary concepts. We must see these definitions as defined in the +new system. Indeed, some terms are already being used but have either not a definition in line with standards, or even differs between services. To bring everyone, +and to consolidate the process, these terms are redefined here, and with their definition in the target objective. + +*Definition ABC* + +... + +*Definition DEF* + +... + + +[NOTE] +============== +Important information will be noticed with a notice like this one. + +* Main information 1 +* Main information 2 +============== + + + +== BUSINESS SPECIFICATION - PROCESS + +Specifications were cut into different business process. We call a business process a workflow with a starting situation and ending situation. Between start and end, we will find actions +done by actors to bring the value of the company. This actions are described using the syntax rule: +*Actor X* do action Y, *Actor Z* do action W. + +_Each process/use case is described into a separate chapter._ + + +=== Use case / Process 1 [[process_1]] + +==== Title and goals + +... + +==== Actors or roles + +* Members of group *...* + +==== Standard flow + +* Members of Groupe *...*: Do ... +* Members of Groupe *...*: Do ... +* Members of Groupe *...*: Do ... + +==== Alternative flow + +* A user without role *...*: Can't do ... + +==== Business rules + +* Business rule 1 +* Business rule 2 + + diff --git a/htdocs/modulebuilder/template/langs/en_US/mymodule.lang b/htdocs/modulebuilder/template/langs/en_US/mymodule.lang index e09e396dce0..a37d8e0c241 100644 --- a/htdocs/modulebuilder/template/langs/en_US/mymodule.lang +++ b/htdocs/modulebuilder/template/langs/en_US/mymodule.lang @@ -28,6 +28,11 @@ ModuleMyModuleDesc = My module description MyModuleSetup = My module setup Settings = Settings MyModuleSetupPage = My module setup page +MYMODULE_MYPARAM1 = My param 1 +MYMODULE_MYPARAM1Tooltip = My param 1 tooltip +MYMODULE_MYPARAM2=My param 2 +MYMODULE_MYPARAM2Tooltip=My param 2 tooltip + # # About page diff --git a/htdocs/modulebuilder/template/lib/mymodule.lib.php b/htdocs/modulebuilder/template/lib/mymodule.lib.php index 3c88bcdea67..cec23bd3c11 100644 --- a/htdocs/modulebuilder/template/lib/mymodule.lib.php +++ b/htdocs/modulebuilder/template/lib/mymodule.lib.php @@ -16,11 +16,9 @@ */ /** - * \file lib/mymodule.lib.php + * \file htdocs/modulebuilder/template/lib/mymodule.lib.php * \ingroup mymodule - * \brief Example module library. - * - * Put detailed description here. + * \brief Library files with common functions for MyModule */ /** diff --git a/htdocs/modulebuilder/template/lib/myobject.lib.php b/htdocs/modulebuilder/template/lib/myobject.lib.php new file mode 100644 index 00000000000..d3665dff236 --- /dev/null +++ b/htdocs/modulebuilder/template/lib/myobject.lib.php @@ -0,0 +1,83 @@ +. + */ + +/** + * \file htdocs/modulebuilder/template/lib/myobject.lib.php + * \ingroup mymodule + * \brief Library files with common functions for MyObject + */ + +/** + * Prepare array of tabs for MyObject + * + * @param MyObject $object MyObject + * @return array Array of tabs + */ +function myobjectPrepareHead($object) +{ + global $db, $langs, $conf; + + $langs->load("mymodule@mymodule"); + + $h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath("/mymodule/myobject_card.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Card"); + $head[$h][2] = 'card'; + $h++; + + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) + { + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; + if (!empty($object->note_public)) $nbNote++; + $head[$h][0] = dol_buildpath('/mymodule/myobject_note.php', 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Notes'); + if ($nbNote > 0) $head[$h][1].= ' '.$nbNote.''; + $head[$h][2] = 'note'; + $h++; + } + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->mymodule->dir_output . "/myobject/" . dol_sanitizeFileName($object->ref); + $nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$')); + $nbLinks=Link::count($db, $object->element, $object->id); + $head[$h][0] = dol_buildpath("/mymodule/myobject_document.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Documents'); + if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' '.($nbFiles+$nbLinks).''; + $head[$h][2] = 'document'; + $h++; + + $head[$h][0] = dol_buildpath("/mymodule/myobject_agenda.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Events"); + $head[$h][2] = 'agenda'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'myobject@mymodule'); + + return $head; +} diff --git a/htdocs/modulebuilder/template/mymoduleindex.php b/htdocs/modulebuilder/template/mymoduleindex.php index f1c92659f9b..c6f70b0ba85 100644 --- a/htdocs/modulebuilder/template/mymoduleindex.php +++ b/htdocs/modulebuilder/template/mymoduleindex.php @@ -41,13 +41,13 @@ if (! $res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (! $user->rights->mymodule->read) accessforbidden(); - -$langs->load("mymodule@mymodule"); +$langs->loadLangs(array("mymodule@mymodule")); $action=GETPOST('action', 'alpha'); + // Securite acces client +if (! $user->rights->mymodule->read) accessforbidden(); $socid=GETPOST('socid','int'); if (isset($user->societe_id) && $user->societe_id > 0) { diff --git a/htdocs/modulebuilder/template/myobject_agenda.php b/htdocs/modulebuilder/template/myobject_agenda.php new file mode 100644 index 00000000000..d6ccb79eea8 --- /dev/null +++ b/htdocs/modulebuilder/template/myobject_agenda.php @@ -0,0 +1,262 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/modulebuilder/template/myobject_agenda.php + * \ingroup mymodule + * \brief Page of MyObject events + */ + +// Load Dolibarr environment +$res=0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"); +// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME +$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; +while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } +if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include(substr($tmp, 0, ($i+1))."/main.inc.php"); +if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"); +// Try main.inc.php using relative path +if (! $res && file_exists("../main.inc.php")) $res=@include("../main.inc.php"); +if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); +if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main.inc.php"); +if (! $res) die("Include of main fails"); + +require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +dol_include_once('/mymodule/class/myobject.class.php'); +dol_include_once('/mymodule/lib/myobject.lib.php'); + + +// Load traductions files requiredby by page +$langs->loadLangs(array("mymodule@mymodule","other")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +if (GETPOST('actioncode','array')) +{ + $actioncode=GETPOST('actioncode','array',3); + if (! count($actioncode)) $actioncode='0'; +} +else +{ + $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); +} +$search_agenda_label=GETPOST('search_agenda_label'); + +// Security check - Protection if external user +//if ($user->societe_id > 0) access_forbidden(); +//if ($user->societe_id > 0) $socid = $user->societe_id; +//$result = restrictedArea($user, 'mymodule', $id); + +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortfield) $sortfield='a.datep,a.id'; +if (! $sortorder) $sortorder='DESC'; + +// Initialize technical objects +$object=new MyObject($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectagenda')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('myobject'); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id > 0 || ! empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity] . "/" . $object->id; + + + +/* + * Actions + */ + +$parameters=array('id'=>$socid); +$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)) +{ + // Cancel + if (GETPOST('cancel','alpha') && ! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $actioncode=''; + $search_agenda_label=''; + } +} + + + +/* + * View + */ + +$contactstatic = new Contact($db); + +$form = new Form($db); + +if ($object->id > 0) +{ + $title=$langs->trans("Agenda"); + //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; + $help_url = ''; + llxHeader('', $title, $help_url); + + if (! empty($conf->notification->enabled)) $langs->load("mails"); + $head = myobjectPrepareHead($object); + + + dol_fiche_head($head, 'agenda', $langs->trans("MyObject"), -1, 'myobject@mymodule'); + + // Object card + // ------------------------------------------------------------ + $linkback = '' . $langs->trans("BackToList") . ''; + + $morehtmlref='
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->mymodule->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + }*/ + $morehtmlref.='
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + + $object->info($object->id); + print dol_print_object_info($object, 1); + + print '
    '; + + dol_fiche_end(); + + + + // Actions buttons + + $objthirdparty=$object; + $objcon=new stdClass(); + + $out=''; + $permok=$user->rights->agenda->myactions->create; + if ((! empty($objthirdparty->id) || ! empty($objcon->id)) && $permok) + { + //$out.='trans("AddAnAction"),'filenew'); + //$out.=""; + } + + + print '
    '; + + if (! empty($conf->agenda->enabled)) + { + if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) + { + print ''.$langs->trans("AddAction").''; + } + else + { + print ''.$langs->trans("AddAction").''; + } + } + + print '
    '; + + if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) )) + { + $param='&socid='.$socid; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + + + print load_fiche_titre($langs->trans("ActionsOnMyObject"),'',''); + + // List of all actions + $filters=array(); + $filters['search_agenda_label']=$search_agenda_label; + + // TODO Replace this with same code than into listactions.php + //show_actions_done($conf,$langs,$db,$object,null,0,$actioncode, '', $filters, $sortfield, $sortorder); + } +} + + +llxFooter(); + +$db->close(); diff --git a/htdocs/modulebuilder/template/myobject_card.php b/htdocs/modulebuilder/template/myobject_card.php index 310d53f08b0..79e11d03cb9 100644 --- a/htdocs/modulebuilder/template/myobject_card.php +++ b/htdocs/modulebuilder/template/myobject_card.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2017 Laurent Destailleur * Copyright (C) ---Put here your own copyright and developer email--- * * This program is free software; you can redistribute it and/or modify @@ -27,8 +27,8 @@ //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); //if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test done when option MAIN_SECURITY_CSRF_WITH_TOKEN is on. //if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data //if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test //if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu @@ -52,13 +52,16 @@ if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main if (! $res) die("Include of main fails"); include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'); +include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); dol_include_once('/mymodule/class/myobject.class.php'); +dol_include_once('/mymodule/lib/myobject.lib.php'); // Load traductions files requiredby by page -$langs->loadLangs(array("mymodule","other")); +$langs->loadLangs(array("mymodule@mymodule","other")); // Get parameters $id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); @@ -82,11 +85,9 @@ foreach($object->fields as $key => $val) if (empty($action) && empty($id) && empty($ref)) $action='view'; -// Protection if external user -if ($user->societe_id > 0) -{ - //accessforbidden(); -} +// Security check - Protection if external user +//if ($user->societe_id > 0) access_forbidden(); +//if ($user->societe_id > 0) $socid = $user->societe_id; //$result = restrictedArea($user, 'mymodule', $id); // fetch optionals attributes and labels @@ -98,7 +99,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be inclu /* - * ACTIONS + * Actions * * Put here all code to do according to value of "action" parameter */ @@ -111,121 +112,34 @@ if (empty($reshook)) { $error=0; - if ($cancel) - { - if ($action != 'addlink') - { - $urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/myobject_list.php',1); - header("Location: ".$urltogo); - exit; - } - if ($id > 0 || ! empty($ref)) $ret = $object->fetch($id,$ref); - $action=''; - } + $permissiontoadd = $user->rights->mymodule->create; + $permissiontodelete = $user->rights->mymodule->delete; + $backurlforlist = dol_buildpath('/mymodule/myobject_list.php',1); - // Action to add record - if ($action == 'add' && ! empty($user->rights->mymodule->create)) - { - foreach ($object->fields as $key => $val) - { - if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'import_key'))) continue; // Ignore special fields + // Actions cancel, add, update or delete + include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; - $object->$key=GETPOST($key,'alpha'); - if ($val['notnull'] && $object->$key == '') - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv($val['label'])), null, 'errors'); - } - } + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; - if (! $error) - { - $result=$object->createCommon($user); - if ($result > 0) - { - // Creation OK - $urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/myobject_list.php',1); - header("Location: ".$urltogo); - exit; - } - else - { - // Creation KO - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); - $action='create'; - } - } - else - { - $action='create'; - } - } - - // Action to update record - if ($action == 'update' && ! empty($user->rights->mymodule->create)) - { - foreach ($object->fields as $key => $val) - { - $object->$key=GETPOST($key,'alpha'); - if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'import_key'))) continue; - if ($val['notnull'] && $object->$key == '') - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv($val['label'])), null, 'errors'); - } - } - - if (! $error) - { - $result=$object->updateCommon($user); - if ($result > 0) - { - $action='view'; - } - else - { - // Creation KO - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); - $action='edit'; - } - } - else - { - $action='edit'; - } - } - - // Action to delete - if ($action == 'confirm_delete' && ! empty($user->rights->mymodule->delete)) - { - $result=$object->deleteCommon($user); - if ($result > 0) - { - // Delete OK - setEventMessages("RecordDeleted", null, 'mesgs'); - header("Location: ".dol_buildpath('/mymodule/myobject_list.php',1)); - exit; - } - else - { - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); - } - } + // Actions to send emails + $trigger_name='MYOBJECT_SENTBYMAIL'; + $autocopy='MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; + $trackid='myobject'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } /* - * VIEW + * View * * Put here all code to build page */ $form=new Form($db); +$formfile=new FormFile($db); llxHeader('','MyObject',''); @@ -258,32 +172,33 @@ if ($action == 'create') dol_fiche_head(array(), ''); print ''."\n"; - foreach($object->fields as $key => $val) - { - if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'import_key'))) continue; - print ''.$langs->trans($val['label']).''; - } + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + print '
    '."\n"; dol_fiche_end(); - print '
     
    '; + print '
    '; + print ''; + print '  '; + print ''; // Cancel for create does not post form if we don't know the backtopage + print '
    '; print ''; } - - // Part to edit record if (($id || $ref) && $action == 'edit') { - print load_fiche_titre($langs->trans("MyModule")); + print load_fiche_titre($langs->trans("MyObject")); print '
    '; + print ''; print ''; print ''; print ''; @@ -291,8 +206,13 @@ if (($id || $ref) && $action == 'edit') dol_fiche_head(); print ''."\n"; - // print ''; - // LIST_OF_TD_LABEL_FIELDS_EDIT + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + print '
    '.$langs->trans("Label").'
    '; dol_fiche_end(); @@ -304,21 +224,19 @@ if (($id || $ref) && $action == 'edit') print '
    '; } - - // Part to show record if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals($object->id, $extralabels); - $head = mymodule_prepare_head($object); - dol_fiche_head($head, 'order', $langs->trans("CustomerOrder"), -1, 'order'); + $head = myobjectPrepareHead($object); + dol_fiche_head($head, 'card', $langs->trans("MyObject"), -1, 'myobject@mymodule'); $formconfirm = ''; // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteMyObject'), 'confirm_delete', '', 0, 1); } // Confirmation of action xxxx @@ -346,12 +264,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print $formconfirm; - // Object card // ------------------------------------------------------------ - - $linkback = '' . $langs->trans("BackToList") . ''; - + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; /* @@ -405,22 +320,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '
    '; print '
    '; print ''."\n"; - // print ''; - // LIST_OF_TD_LABEL_FIELDS_VIEW + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; // Other attributes include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print '
    '.$langs->trans("Label").''.$object->label.'
    '; - print '
    '; - print '
    '; - print '
    '; - print '
    '; - print ''; - - - print '
    '; print '
    '; print '
    '; @@ -441,17 +347,39 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if (empty($reshook)) { // Send - print ''."\n"; + print ''."\n"; if ($user->rights->mymodule->write) { print ''."\n"; } + else + { + print ''."\n"; + } + + /* + if ($user->rights->sellyoursaas->create) + { + if ($object->status == 1) + { + print ''."\n"; + } + else + { + print ''."\n"; + } + } + */ if ($user->rights->mymodule->delete) { print ''."\n"; } + else + { + print ''."\n"; + } } print '
    '."\n"; } @@ -466,152 +394,41 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea { print '
    '; print ''; // ancre + // Documents - $comref = dol_sanitizeFileName($object->ref); + /*$comref = dol_sanitizeFileName($object->ref); $relativepath = $comref . '/' . $comref . '.pdf'; $filedir = $conf->mymodule->dir_output . '/' . $comref; $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; $genallowed = $user->rights->mymodule->read; // If you can read, you can build the PDF to read content $delallowed = $user->rights->mymodule->create; // If you can create/edit, you can remove a file on card print $formfile->showdocuments('mymodule', $comref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); - + */ // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('order')); + $linktoelem = $form->showLinkToObjectBlock($object, null, array('myobject')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); print '
    '; + $MAXEVENT = 10; + // List of actions on element include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'order', $socid); + $somethingshown = $formactions->showactions($object, 'myobject', $socid, 1, '', $MAXEVENT); print '
    '; } + // Presend form + $modelmail='myobject'; + $defaulttopic='Information'; + $diroutput = $conf->mymodule->dir_output; + $trackid = 'myobject'.$object->id; - /* - * Action presend - */ - /* - if ($action == 'presend') - { - $object->fetch_projet(); - - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($conf->commande->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - - if (!empty($newlang)) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($newlang); - $outputlangs->load('commercial'); - } - - // Build document if it not exists - if (! $file || ! is_readable($file)) { - $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) { - dol_print_error($db, $object->error, $object->errors); - exit(); - } - $fileparams = dol_most_recent_file($conf->commande->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - } - - print '
    '; - print '
    '; - print '
    '; - print load_fiche_titre($langs->trans('SendOrderByMail')); - - dol_fiche_head(''); - - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - $formmail->trackid='ord'.$object->id; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'ord'.$object->id); - } - $formmail->withfrom = 1; - $liste = array(); - foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) - $liste [$key] = $value; - $formmail->withto = GETPOST('sendto') ? GETPOST('sendto') : $liste; - $formmail->withtocc = $liste; - $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; - if (empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->trans('SendOrderRef', '__ORDERREF__'); - } else if (! empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->trans('SendOrderRef', '__ORDERREF__ (__REFCLIENT__)'); - } - $formmail->withfile = 2; - $formmail->withbody = 1; - $formmail->withdeliveryreceipt = 1; - $formmail->withcancel = 1; - // Tableau des substitutions - $formmail->setSubstitFromObject($object); - $formmail->substit ['__ORDERREF__'] = $object->ref; - - $custcontact = ''; - $contactarr = array(); - $contactarr = $object->liste_contact(- 1, 'external'); - - if (is_array($contactarr) && count($contactarr) > 0) - { - foreach ($contactarr as $contact) - { - if ($contact['libelle'] == $langs->trans('TypeContact_commande_external_CUSTOMER')) { // TODO Use code and not label - $contactstatic = new Contact($db); - $contactstatic->fetch($contact ['id']); - $custcontact = $contactstatic->getFullName($langs, 1); - } - } - - if (! empty($custcontact)) { - $formmail->substit['__CONTACTCIVNAME__'] = $custcontact; - } - } - - // Tableau des parametres complementaires - $formmail->param['action'] = 'send'; - $formmail->param['models'] = 'order_send'; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['orderid'] = $object->id; - $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; - - // Init list of files - if (GETPOST("mode") == 'init') { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file, basename($file), dol_mimetype($file)); - } - - // Show form - print $formmail->get_form(); - - dol_fiche_end(); - }*/ + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } diff --git a/htdocs/modulebuilder/template/myobject_document.php b/htdocs/modulebuilder/template/myobject_document.php new file mode 100644 index 00000000000..05b76b3d588 --- /dev/null +++ b/htdocs/modulebuilder/template/myobject_document.php @@ -0,0 +1,191 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/modulebuilder/template/myobject_document.php + * \ingroup mymodule + * \brief Tab for documents linked to MyObject + */ + +// Load Dolibarr environment +$res=0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"); +// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME +$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; +while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } +if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include(substr($tmp, 0, ($i+1))."/main.inc.php"); +if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"); +// Try main.inc.php using relative path +if (! $res && file_exists("../main.inc.php")) $res=@include("../main.inc.php"); +if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); +if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main.inc.php"); +if (! $res) die("Include of main fails"); + +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +dol_include_once('/mymodule/class/myobject.class.php'); +dol_include_once('/mymodule/lib/myobject.lib.php'); + +// Load traductions files requiredby by page +$langs->loadLangs(array("mymodule@mymodule","companies","other")); + + +$action=GETPOST('action','aZ09'); +$confirm=GETPOST('confirm'); +$id=(GETPOST('socid','int') ? GETPOST('socid','int') : GETPOST('id','int')); +$ref = GETPOST('ref', 'alpha'); + +// Security check - Protection if external user +//if ($user->societe_id > 0) access_forbidden(); +//if ($user->societe_id > 0) $socid = $user->societe_id; +//$result = restrictedArea($user, 'mymodule', $id); + +// Get parameters +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $conf->liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortorder) $sortorder="ASC"; +if (! $sortfield) $sortfield="name"; + +// Initialize technical objects +$object=new MyObject($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectdocument')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('myobject'); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals + +//if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/packages/" . dol_sanitizeFileName($object->id); +if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/packages/" . dol_sanitizeFileName($object->ref); + + + +/* + * Actions + */ + +include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; + + +/* + * View + */ + +$form = new Form($db); + +$title=$langs->trans("MyObject").' - '.$langs->trans("Files"); +$help_url=''; +//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +llxHeader('', $title, $help_url); + +if ($object->id) +{ + /* + * Show tabs + */ + if (! empty($conf->notification->enabled)) $langs->load("mails"); + $head = myobjectPrepareHead($object); + + dol_fiche_head($head, 'document', $langs->trans("MyObject"), -1, 'myobject@mymodule'); + + + // Construit liste des fichiers + $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); + $totalsize=0; + foreach($filearray as $key => $file) + { + $totalsize+=$file['size']; + } + + // Object card + // ------------------------------------------------------------ + $linkback = '' . $langs->trans("BackToList") . ''; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + + print '
    '; + print ''; + + // Prefix + if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field + { + print ''; + } + + if ($object->client) + { + print ''; + } + + if ($object->fournisseur) + { + print ''; + } + + // Number of files + print ''; + + // Total size + print ''; + + print '
    '.$langs->trans('Prefix').''.$object->prefix_comm.'
    '; + print $langs->trans('CustomerCode').''; + print $object->code_client; + if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; + print '
    '; + print $langs->trans('SupplierCode').''; + print $object->code_fournisseur; + if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").')'; + print '
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '; + + print '
    '; + + dol_fiche_end(); + + $modulepart = 'mymodule'; + //$permission = $user->rights->mymodule->create; + $permission = 1; + //$permtoedit = $user->rights->mymodule->create; + $permtoedit = 1; + $param = '&id=' . $object->id; + + //$relativepathwithnofile='myobject/' . dol_sanitizeFileName($object->id).'/'; + $relativepathwithnofile='myobject/' . dol_sanitizeFileName($object->ref).'/'; + + include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; +} +else +{ + accessforbidden('',0,0); +} + + +llxFooter(); +$db->close(); diff --git a/htdocs/modulebuilder/template/myobject_list.php b/htdocs/modulebuilder/template/myobject_list.php index 9ba043774e6..5716f88b4b1 100644 --- a/htdocs/modulebuilder/template/myobject_list.php +++ b/htdocs/modulebuilder/template/myobject_list.php @@ -27,8 +27,8 @@ //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); //if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test done when option MAIN_SECURITY_CSRF_WITH_TOKEN is on. //if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data //if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test //if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu @@ -58,19 +58,19 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; dol_include_once('/mymodule/class/myobject.class.php'); // Load traductions files requiredby by page -$langs->loadLangs(array("mymodule","other")); +$langs->loadLangs(array("mymodule@mymodule","other")); -$action = GETPOST('action','alpha'); -$massaction = GETPOST('massaction','alpha'); -$show_files = GETPOST('show_files','int'); -$confirm = GETPOST('confirm','alpha'); -$cancel = GETPOST('cancel', 'alpha'); -$toselect = GETPOST('toselect', 'array'); +$action = GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction','alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files','int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm','alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list $contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'myobjectlist'; // To manage different context of search +$backtopage = GETPOST('backtopage','alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss','aZ'); // Option for the css output (always '' except when 'print') $id = GETPOST('id','int'); -$backtopage = GETPOST('backtopage'); -$optioncss = GETPOST('optioncss','alpha'); // Load variable for pagination $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; @@ -99,7 +99,7 @@ if (! $sortorder) $sortorder="ASC"; $socid=0; if ($user->societe_id > 0) { - //$socid = $user->societe_id; + //$socid = $user->societe_id; accessforbidden(); } @@ -108,14 +108,14 @@ $search_all=trim(GETPOST("search_all",'alpha')); $search=array(); foreach($object->fields as $key => $val) { - if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); + if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); foreach($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; + if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; } // Definition of fields for list @@ -123,15 +123,15 @@ $arrayfields=array(); foreach($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled']); + if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled']); } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } } @@ -143,41 +143,41 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Put here all code to do according to value of "$action" parameter */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); -$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // 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)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - foreach($object->fields as $key => $val) - { - $search[$key]=''; - } - $toselect=''; - $search_array_options=array(); - } - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') - || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) - { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation - } + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + foreach($object->fields as $key => $val) + { + $search[$key]=''; + } + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } - // Mass actions - $objectclass='MyObject'; - $objectlabel='MyObject'; - $permtoread = $user->rights->mymodule->read; - $permtodelete = $user->rights->mymodule->delete; - $uploaddir = $conf->mymodule->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Mass actions + $objectclass='MyObject'; + $objectlabel='MyObject'; + $permtoread = $user->rights->mymodule->read; + $permtodelete = $user->rights->mymodule->delete; + $uploaddir = $conf->mymodule->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -202,40 +202,42 @@ $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("MyObjects")); $sql = 'SELECT '; foreach($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql.='t.'.$key.', '; } // Add fields from extrafields foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); // Add fields from hooks $parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook +$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; $sql=preg_replace('/, $/','', $sql); $sql.= " FROM ".MAIN_DB_PREFIX."myobject as t"; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."myobject_extrafields as ef on (t.rowid = ef.fk_object)"; -$sql.= " WHERE t.entity IN (".getEntity('myobject').")"; +if ($object->ismultientitymanaged == 1) $sql.= " WHERE t.entity IN (".getEntity('myobject').")"; +else $sql.=" WHERE 1 = 1"; foreach($search as $key => $val) { - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:($object->fields[$key]['type'] == 'integer'?1:0))); + $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); + if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); } if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_all); // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode_search=0; + if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); + } } // Add where from hooks $parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook +$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; /* If a group by is required @@ -264,12 +266,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql.= $db->plimit($limit+1, $offset); -dol_syslog($script_file, LOG_DEBUG); $resql=$db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -277,10 +278,10 @@ $num = $db->num_rows($resql); // Direct jump if only one record found if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/mymodule/myobject_card.php?id='.$id); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/mymodule/myobject_card.php?id='.$id); + exit; } @@ -307,24 +308,25 @@ jQuery(document).ready(function() { $arrayofselected=is_array($toselect)?$toselect:array(); $param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); foreach($search as $key => $val) { - $param.= '&search_'.$key.'='.urlencode($search[$key]); + $param.= '&search_'.$key.'='.urlencode($search[$key]); } -if ($optioncss != '') $param.='&optioncss='.$optioncss; +if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } +// List of mass actions available $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->mymodule->delete) $arrayofmassactions['delete']=$langs->trans("Delete"); if ($massaction == 'presend') $arrayofmassactions=array(); @@ -340,21 +342,21 @@ print ''; print ''; print ''; -print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } $moreforfilter = ''; -$moreforfilter.='
    '; +/*$moreforfilter.='
    '; $moreforfilter.= $langs->trans('MyFilter') . ': '; -$moreforfilter.= '
    '; +$moreforfilter.= '
    ';*/ $parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook +$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; else $moreforfilter = $hookmanager->resPrint; @@ -362,12 +364,12 @@ if (! empty($moreforfilter)) { print '
    '; print $moreforfilter; - print '
    '; + print ''; } $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=$form->showCheckAddButtons('checkforselect', 1); +$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''."\n"; @@ -378,48 +380,39 @@ print '
    '; foreach($object->fields as $key => $val) { - if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; - if (! empty($arrayfields['t.'.$key]['checked'])) print ''; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook +$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -// Rest of fields search -foreach($object->fields as $key => $val) -{ - if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; - if (! empty($arrayfields['t.'.$key]['checked'])) print ''; -} // Action column print ''."\n"; print ''; foreach($object->fields as $key => $val) { - if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; - if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print getTitleFieldOfList($langs->trans($extralabels[$key]), 0, $_SERVER["PHP_SELF"], $sortonfield, "", $param, ($align?'align="'.$align.'"':''), $sortfield, $sortorder)."\n"; - } + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook +$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -// Rest of fields title -foreach($object->fields as $key => $val) -{ - if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; - if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; -} print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; print ''."\n"; @@ -474,7 +458,7 @@ print ''."\n"; $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 + if (preg_match('/\$object/',$val)) $needToFetchEachLine++; // There is at least one compute field that use $object } @@ -484,142 +468,117 @@ $i=0; $totalarray=array(); while ($i < min($num, $limit)) { - $obj = $db->fetch_object($resql); - if ($obj) - { - // Store properties in $object - $object->id = $obj->rowid; - foreach($object->fields as $key => $val) - { - if (isset($obj->$key)) $object->$key = $obj->$key; - } + $obj = $db->fetch_object($resql); + if (empty($obj)) break; // Should not happen - // Show here line of result - print ''; - foreach($object->fields as $key => $val) - { - if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) - { - print ''; - if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour'); - elseif ($key == 'ref') print $object->getNomUrl(1); - elseif ($key == 'status') print $object->getLibStatut(3); - else print $obj->$key; - print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) - { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; - $totalarray['val']['t.'.$key] += $obj->$key; - } - } - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) + // Store properties in $object + $object->id = $obj->rowid; + foreach($object->fields as $key => $val) + { + if (isset($obj->$key)) $object->$key = $obj->$key; + } + + // Show here line of result + print ''; + foreach($object->fields as $key => $val) + { + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) + { + print ''; + print $object->showOutputField($val, $key, $obj->$key, ''); + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) - { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='ef.'.$tmpkey; - $totalarray['val']['ef.'.$tmpkey] += $obj->$tmpkey; - } + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + $totalarray['val']['t.'.$key] += $obj->$key; } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Rest of fields - foreach($object->fields as $key => $val) - { - if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) - { - print ''; - if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour'); - elseif ($key == 'status') print $object->getLibStatut(3); - else print $obj->$key; - print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) - { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; - $totalarray['val']['t.'.$key] += $obj->$key; - } - } - } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + } + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print ''; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, ''); + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='ef.'.$tmpkey; + $totalarray['val']['ef.'.$tmpkey] += $obj->$tmpkey; + } + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; - print ''; - } - $i++; + print ''; + + $i++; } // Show total line if (isset($totalarray['pos'])) { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if (! empty($totalarray['pos'][$i])) print ''; - else - { - if ($i == 1) - { - if ($num < $limit) print ''; - else print ''; - } - print ''; - } - } - print ''; + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if (! empty($totalarray['pos'][$i])) print ''; + else + { + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + else print ''; + } + } + print ''; } // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } - print ''; + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print ''; } $db->free($resql); $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook +$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) - { - $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 ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + { + $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 ''; $searchpicto=$form->showFilterButtons(); @@ -433,39 +426,30 @@ 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 ''; + 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 '
    '.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").'
    '.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").'
    '.$langs->trans("NoRecordFound").'
    '.$langs->trans("NoRecordFound").'
    '."\n"; @@ -627,27 +586,27 @@ print '
    '."\n"; print ''."\n"; -if ($nbtotalofrecords === '' || $nbtotalofrecords) +if (in_array('builddoc',$arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) - { - require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); - $formfile = new FormFile($db); + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); + $formfile = new FormFile($db); - // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->mymodule->read; - $delallowed=$user->rights->mymodule->create; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->mymodule->read; + $delallowed=$user->rights->mymodule->create; - print $formfile->showdocuments('massfilesarea_mymodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
    '.$langs->trans("ShowTempMassFilesArea").''; - } + print $formfile->showdocuments('massfilesarea_mymodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '
    '.$langs->trans("ShowTempMassFilesArea").''; + } } // End of page diff --git a/htdocs/modulebuilder/template/myobject_note.php b/htdocs/modulebuilder/template/myobject_note.php new file mode 100644 index 00000000000..782be1c5bb9 --- /dev/null +++ b/htdocs/modulebuilder/template/myobject_note.php @@ -0,0 +1,163 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/modulebuilder/template/myobject_note.php + * \ingroup mymodule + * \brief Car with notes on MyObject + */ + +// Load Dolibarr environment +$res=0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"); +// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME +$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; +while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } +if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include(substr($tmp, 0, ($i+1))."/main.inc.php"); +if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"); +// Try main.inc.php using relative path +if (! $res && file_exists("../main.inc.php")) $res=@include("../main.inc.php"); +if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); +if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main.inc.php"); +if (! $res) die("Include of main fails"); + +dol_include_once('/mymodule/class/myobject.class.php'); +dol_include_once('/mymodule/lib/myobject.lib.php'); + +// Load traductions files requiredby by page +$langs->loadLangs(array("mymodule@mymodule","companies")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +// Initialize technical objects +$object=new MyObject($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectnote')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('myobject'); + +// Security check - Protection if external user +//if ($user->societe_id > 0) access_forbidden(); +//if ($user->societe_id > 0) $socid = $user->societe_id; +//$result = restrictedArea($user, 'mymodule', $id); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id > 0 || ! empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity] . "/" . $object->id; + +$permissionnote=1; +//$permissionnote=$user->rights->mymodule->creer; // Used by the include of actions_setnotes.inc.php + + +/* + * Actions + */ + +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + + +/* + * View + */ + +$form = new Form($db); + +//$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; +$help_url=''; +llxHeader('',$langs->trans('MyObject'),$help_url); + +if ($id > 0 || ! empty($ref)) +{ + $object->fetch_thirdparty(); + + $head = myobjectPrepareHead($object); + + dol_fiche_head($head, 'note', $langs->trans("MyObject"), -1, 'myobject@mymodule'); + + // Object card + // ------------------------------------------------------------ + $linkback = '' . $langs->trans("BackToList") . ''; + + $morehtmlref='
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->mymodule->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + }*/ + $morehtmlref.='
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + + + $cssclass="titlefield"; + include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; + + print '
    '; + + dol_fiche_end(); +} + + +llxFooter(); +$db->close(); diff --git a/htdocs/modulebuilder/template/sql/data.sql b/htdocs/modulebuilder/template/sql/data.sql index 1bcc30cb1fd..e3980b63c2e 100644 --- a/htdocs/modulebuilder/template/sql/data.sql +++ b/htdocs/modulebuilder/template/sql/data.sql @@ -13,6 +13,6 @@ -- You should have received a copy of the GNU General Public License -- along with this program. If not, see . -INSERT INTO llx_myobject VALUES ( +INSERT INTO llx_mymodule_myobject VALUES ( 1, 1, 'mydata' ); diff --git a/htdocs/modulebuilder/template/sql/llx_myobject.key.sql b/htdocs/modulebuilder/template/sql/llx_mymodule_myobject.key.sql similarity index 64% rename from htdocs/modulebuilder/template/sql/llx_myobject.key.sql rename to htdocs/modulebuilder/template/sql/llx_mymodule_myobject.key.sql index 4822d7c3ac4..6e301744fa6 100644 --- a/htdocs/modulebuilder/template/sql/llx_myobject.key.sql +++ b/htdocs/modulebuilder/template/sql/llx_mymodule_myobject.key.sql @@ -11,12 +11,14 @@ -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License --- along with this program. If not, see . +-- along with this program. If not, see http://www.gnu.org/licenses/. -- BEGIN MODULEBUILDER INDEXES -ALTER TABLE llx_myobject ADD UNIQUE INDEX idx_fieldobject (fieldobject); +ALTER TABLE llx_mymodule_myobject ADD INDEX idx_fieldobject (fieldobject); -- END MODULEBUILDER INDEXES ---ALTER TABLE llx_myobject ADD CONSTRAINT llx_myobject_field_id FOREIGN KEY (fk_field) REFERENCES llx_myotherobject(rowid); +--ALTER TABLE llx_mymodule_myobject ADD UNIQUE INDEX uk_mymodule_myobject_fieldxyz(fieldx, fieldy); + +--ALTER TABLE llx_mymodule_myobject ADD CONSTRAINT llx_mymodule_myobject_field_id FOREIGN KEY (fk_field) REFERENCES llx_myotherobject(rowid); diff --git a/htdocs/modulebuilder/template/sql/llx_myobject.sql b/htdocs/modulebuilder/template/sql/llx_mymodule_myobject.sql similarity index 89% rename from htdocs/modulebuilder/template/sql/llx_myobject.sql rename to htdocs/modulebuilder/template/sql/llx_mymodule_myobject.sql index 1c47004f4e7..0470739573a 100644 --- a/htdocs/modulebuilder/template/sql/llx_myobject.sql +++ b/htdocs/modulebuilder/template/sql/llx_mymodule_myobject.sql @@ -11,12 +11,12 @@ -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License --- along with this program. If not, see . +-- along with this program. If not, see http://www.gnu.org/licenses/. -CREATE TABLE llx_myobject( - rowid INTEGER AUTO_INCREMENT PRIMARY KEY, +CREATE TABLE llx_mymodule_myobject( -- BEGIN MODULEBUILDER FIELDS + rowid INTEGER AUTO_INCREMENT PRIMARY KEY, entity INTEGER DEFAULT 1 NOT NULL, label VARCHAR(255), qty INTEGER, diff --git a/htdocs/modulebuilder/template/sql/llx_myobject_extrafields.sql b/htdocs/modulebuilder/template/sql/llx_mymodule_myobject_extrafields.sql similarity index 88% rename from htdocs/modulebuilder/template/sql/llx_myobject_extrafields.sql rename to htdocs/modulebuilder/template/sql/llx_mymodule_myobject_extrafields.sql index 72c672a92f8..70b6afe9824 100644 --- a/htdocs/modulebuilder/template/sql/llx_myobject_extrafields.sql +++ b/htdocs/modulebuilder/template/sql/llx_mymodule_myobject_extrafields.sql @@ -11,9 +11,9 @@ -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License --- along with this program. If not, see . +-- along with this program. If not, see http://www.gnu.org/licenses/. -create table llx_myobject_extrafields +create table llx_mymodule_myobject_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, tms timestamp, diff --git a/htdocs/modulebuilder/template/sql/update_x.x.x-y.y.y.sql b/htdocs/modulebuilder/template/sql/update_x.x.x-y.y.y.sql index 494de5a2b17..1b42935ab47 100644 --- a/htdocs/modulebuilder/template/sql/update_x.x.x-y.y.y.sql +++ b/htdocs/modulebuilder/template/sql/update_x.x.x-y.y.y.sql @@ -11,4 +11,4 @@ -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License --- along with this program. If not, see . +-- along with this program. If not, see http://www.gnu.org/licenses/. diff --git a/htdocs/opensurvey/card.php b/htdocs/opensurvey/card.php index c634ca1ceaa..4d71efe6395 100644 --- a/htdocs/opensurvey/card.php +++ b/htdocs/opensurvey/card.php @@ -35,7 +35,7 @@ if (!$user->rights->opensurvey->read) accessforbidden(); // Initialisation des variables $action=GETPOST('action','aZ09'); -$cancel=GETPOST('cancel'); +$cancel=GETPOST('cancel','alpha'); $numsondage = ''; diff --git a/htdocs/opensurvey/results.php b/htdocs/opensurvey/results.php index 9bfb15b2c24..49f26e47cb0 100644 --- a/htdocs/opensurvey/results.php +++ b/htdocs/opensurvey/results.php @@ -520,7 +520,7 @@ if (GETPOST('ajoutsujet')) if (!$user->rights->opensurvey->write) accessforbidden(); print '
    '."\n"; - print ''; + print ''; print '
    '."\n"; print "

    "."\n"; @@ -600,7 +600,7 @@ if (GETPOST('ajoutsujet')) } if ($user->rights->opensurvey->write) { - print '
    '.$langs->trans("PollAdminDesc", img_picto('','delete'), $langs->trans("Add")).'
    '; + print '
    '.$langs->trans("PollAdminDesc", img_picto('','delete'), $langs->trans("Add")).'
    '; } $nbcolonnes=substr_count($object->sujet,',')+1; diff --git a/htdocs/opensurvey/wizard/create_survey.php b/htdocs/opensurvey/wizard/create_survey.php index 787bb7969fa..0dfc2505ce3 100644 --- a/htdocs/opensurvey/wizard/create_survey.php +++ b/htdocs/opensurvey/wizard/create_survey.php @@ -178,11 +178,11 @@ print ' '. $langs->trans( if ($_SESSION['allow_comments']) $allow_comments = 'checked'; if (isset($_POST['allow_comments'])) $allow_comments=GETPOST('allow_comments')?'checked':''; -print ' '.$langs->trans('CanComment').'
    '."\n"; +print ' '.$langs->trans('CanComment').'
    '."\n"; if ($_SESSION['allow_spy']) $allow_spy = 'checked'; if (isset($_POST['allow_spy'])) $allow_spy=GETPOST('allow_spy')?'checked':''; -print ' '.$langs->trans('CanSeeOthersVote').'
    '."\n"; +print ' '.$langs->trans('CanSeeOthersVote').'
    '."\n"; if (GETPOST('choix_sondage')) { diff --git a/htdocs/paybox/admin/paybox.php b/htdocs/paybox/admin/paybox.php index 56a8482fcfc..b5049becbdb 100644 --- a/htdocs/paybox/admin/paybox.php +++ b/htdocs/paybox/admin/paybox.php @@ -32,10 +32,11 @@ $servicename='PayBox'; $langs->load("admin"); $langs->load("other"); $langs->load("paybox"); +$langs->load("paypal"); if (!$user->admin) accessforbidden(); - + $action = GETPOST('action','alpha'); @@ -53,17 +54,24 @@ if ($action == 'setvalue' && $user->admin) if (! $result > 0) $error++; $result=dolibarr_set_const($db, "PAYBOX_PBX_IDENTIFIANT",GETPOST('PAYBOX_PBX_IDENTIFIANT','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYBOX_CREDITOR",GETPOST('PAYBOX_CREDITOR','alpha'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR",GETPOST('ONLINE_PAYMENT_CREDITOR','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYBOX_CSS_URL",GETPOST('PAYBOX_CSS_URL','alpha'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL",GETPOST('ONLINE_PAYMENT_CSS_URL','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYBOX_MESSAGE_OK",GETPOST('PAYBOX_MESSAGE_OK','alpha'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM",GETPOST('ONLINE_PAYMENT_MESSAGE_FORM','alpha'),'chaine',0,'',$conf->entity); + if (! $result > 0) $error++; + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_OK",GETPOST('ONLINE_PAYMENT_MESSAGE_OK','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYBOX_MESSAGE_KO",GETPOST('PAYBOX_MESSAGE_KO','alpha'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_KO",GETPOST('ONLINE_PAYMENT_MESSAGE_KO','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYBOX_PAYONLINE_SENDEMAIL",GETPOST('PAYBOX_PAYONLINE_SENDEMAIL'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_SENDEMAIL",GETPOST('ONLINE_PAYMENT_SENDEMAIL'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - + // Payment token for URL + $result=dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN",GETPOST('PAYMENT_SECURITY_TOKEN','alpha'),'chaine',0,'',$conf->entity); + if (! $result > 0) $error++; + $result=dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN_UNIQUE",GETPOST('PAYMENT_SECURITY_TOKEN_UNIQUE','alpha'),'chaine',0,'',$conf->entity); + if (! $result > 0) $error++; + if (! $error) { $db->commit(); @@ -170,38 +178,57 @@ print ''; print ''; print $langs->trans("VendorName").''; -print ''; +print ''; print '
    '.$langs->trans("Example").': '.$mysoc->name; print ''; print ''; print $langs->trans("CSSUrlForPaymentForm").''; -print ''; +print ''; print '
    '.$langs->trans("Example").': http://mysite/mycss.css'; print ''; +print ''; +print $langs->trans("MessageForm").''; +$doleditor=new DolEditor('ONLINE_PAYMENT_MESSAGE_FORM',$conf->global->ONLINE_PAYMENT_MESSAGE_FORM,'',100,'dolibarr_details','In',false,true,true,ROWS_2,'90%'); +$doleditor->Create(); +print ''; + print ''; print $langs->trans("MessageOK").''; -$doleditor=new DolEditor('PAYBOX_MESSAGE_OK',$conf->global->PAYBOX_MESSAGE_OK,'',100,'dolibarr_details','In',false,true,true,ROWS_2,'90%'); +$doleditor=new DolEditor('ONLINE_PAYMENT_MESSAGE_OK',$conf->global->ONLINE_PAYMENT_MESSAGE_OK,'',100,'dolibarr_details','In',false,true,true,ROWS_2,'90%'); $doleditor->Create(); print ''; print ''; print $langs->trans("MessageKO").''; -$doleditor=new DolEditor('PAYBOX_MESSAGE_KO',$conf->global->PAYBOX_MESSAGE_KO,'',100,'dolibarr_details','In',false,true,true,ROWS_2,'90%'); +$doleditor=new DolEditor('ONLINE_PAYMENT_MESSAGE_KO',$conf->global->ONLINE_PAYMENT_MESSAGE_KO,'',100,'dolibarr_details','In',false,true,true,ROWS_2,'90%'); $doleditor->Create(); print ''; print ''; -print $langs->trans("PAYBOX_PAYONLINE_SENDEMAIL").''; -print ''; +print $langs->trans("ONLINE_PAYMENT_SENDEMAIL").''; +print ''; print '   '.$langs->trans("Example").': myemail@myserver.com'; print ''; +// Payment token for URL +print ''; +print $langs->trans("SecurityToken").''; +print ''; +if (! empty($conf->use_javascript_ajax)) + print ' '.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"'); +print ''; + +print ''; +print $langs->trans("SecurityTokenIsUnique").''; +print $form->selectyesno("PAYMENT_SECURITY_TOKEN_UNIQUE",(empty($conf->global->PAYMENT_SECURITY_TOKEN)?0:$conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE),1); +print ''; + print ''; dol_fiche_end(); @@ -212,33 +239,7 @@ print ''; print '

    '; -print ''.$langs->trans("FollowingUrlAreAvailableToMakePayments").':

    '; -print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnFreeAmount",$servicename).':
    '; -print ''.DOL_MAIN_URL_ROOT.'/public/paybox/newpayment.php?amount=9.99&tag=your_free_tag'."
    \n"; -if (! empty($conf->commande->enabled)) -{ - print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnOrder",$servicename).':
    '; - print ''.DOL_MAIN_URL_ROOT.'/public/paybox/newpayment.php?source=order&ref=order_ref'."
    \n"; -} -if (! empty($conf->facture->enabled)) -{ - print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnInvoice",$servicename).':
    '; - print ''.DOL_MAIN_URL_ROOT.'/public/paybox/newpayment.php?source=invoice&ref=invoice_ref'."
    \n"; -// print $langs->trans("SetupPayBoxToHavePaymentCreatedAutomatically",$langs->transnoentitiesnoconv("FeatureNotYetAvailable"))."
    \n"; -} -if (! empty($conf->contrat->enabled)) -{ - print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnContractLine",$servicename).':
    '; - print ''.DOL_MAIN_URL_ROOT.'/public/paybox/newpayment.php?source=contractline&ref=contractline_ref'."
    \n"; -} -if (! empty($conf->adherent->enabled)) -{ - print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnMemberSubscription",$servicename).':
    '; - print ''.DOL_MAIN_URL_ROOT.'/public/paybox/newpayment.php?source=membersubscription&ref=member_ref'."
    \n"; -} - -print info_admin($langs->trans("YouCanAddTagOnUrl")); +include DOL_DOCUMENT_ROOT.'/core/tpl/onlinepaymentlinks.tpl.php'; llxFooter(); - $db->close(); diff --git a/htdocs/paypal/admin/paypal.php b/htdocs/paypal/admin/paypal.php index cc83dc10fab..3647ea7a4d5 100644 --- a/htdocs/paypal/admin/paypal.php +++ b/htdocs/paypal/admin/paypal.php @@ -26,6 +26,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -43,7 +44,7 @@ $action = GETPOST('action','alpha'); if ($action == 'setvalue' && $user->admin) { $db->begin(); - + $result=dolibarr_set_const($db, "PAYPAL_API_USER",GETPOST('PAYPAL_API_USER','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; $result=dolibarr_set_const($db, "PAYPAL_API_PASSWORD",GETPOST('PAYPAL_API_PASSWORD','alpha'),'chaine',0,'',$conf->entity); @@ -52,25 +53,28 @@ if ($action == 'setvalue' && $user->admin) if (! $result > 0) $error++; $result=dolibarr_set_const($db, "PAYPAL_SSLVERSION",GETPOST('PAYPAL_SSLVERSION','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYPAL_CREDITOR",GETPOST('PAYPAL_CREDITOR','alpha'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR",GETPOST('ONLINE_PAYMENT_CREDITOR','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; $result=dolibarr_set_const($db, "PAYPAL_API_INTEGRAL_OR_PAYPALONLY",GETPOST('PAYPAL_API_INTEGRAL_OR_PAYPALONLY','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYPAL_CSS_URL",GETPOST('PAYPAL_CSS_URL','alpha'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL",GETPOST('ONLINE_PAYMENT_CSS_URL','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYPAL_SECURITY_TOKEN",GETPOST('PAYPAL_SECURITY_TOKEN','alpha'),'chaine',0,'',$conf->entity); - if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYPAL_SECURITY_TOKEN_UNIQUE",GETPOST('PAYPAL_SECURITY_TOKEN_UNIQUE','alpha'),'chaine',0,'',$conf->entity); - if (! $result > 0) $error++; $result=dolibarr_set_const($db, "PAYPAL_ADD_PAYMENT_URL",GETPOST('PAYPAL_ADD_PAYMENT_URL','alpha'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYPAL_MESSAGE_OK",GETPOST('PAYPAL_MESSAGE_OK'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM",GETPOST('ONLINE_PAYMENT_MESSAGE_FORM'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYPAL_MESSAGE_KO",GETPOST('PAYPAL_MESSAGE_KO'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_OK",GETPOST('ONLINE_PAYMENT_MESSAGE_OK'),'chaine',0,'',$conf->entity); + if (! $result > 0) $error++; + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_KO",GETPOST('ONLINE_PAYMENT_MESSAGE_KO'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - $result=dolibarr_set_const($db, "PAYPAL_PAYONLINE_SENDEMAIL",GETPOST('PAYPAL_PAYONLINE_SENDEMAIL'),'chaine',0,'',$conf->entity); + $result=dolibarr_set_const($db, "ONLINE_PAYMENT_SENDEMAIL",GETPOST('ONLINE_PAYMENT_SENDEMAIL'),'chaine',0,'',$conf->entity); if (! $result > 0) $error++; - + // Payment token for URL + $result=dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN",GETPOST('PAYMENT_SECURITY_TOKEN','alpha'),'chaine',0,'',$conf->entity); + if (! $result > 0) $error++; + $result=dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN_UNIQUE",GETPOST('PAYMENT_SECURITY_TOKEN_UNIQUE','alpha'),'chaine',0,'',$conf->entity); + if (! $result > 0) $error++; + if (! $error) { $db->commit(); @@ -202,14 +206,14 @@ print ''; print ''; print $langs->trans("VendorName").''; -print ''; +print ''; print '   '.$langs->trans("Example").': '.$mysoc->name; print ''; print ''; print $langs->trans("CSSUrlForPaymentForm").''; -print ''; +print ''; print '   '.$langs->trans("Example").': http://mysite/mycss.css'; print ''; @@ -220,23 +224,30 @@ print $form->selectyesno("PAYPAL_ADD_PAYMENT_URL",$conf->global->PAYPAL_ADD_PAYM print ''; +print ''; +print $langs->trans("MessageForm").''; +$doleditor=new DolEditor('ONLINE_PAYMENT_MESSAGE_FORM',$conf->global->ONLINE_PAYMENT_MESSAGE_FORM,'',100,'dolibarr_details','In',false,true,true,ROWS_4,'90%'); +$doleditor->Create(); +print ''; + + print ''; print $langs->trans("MessageOK").''; -$doleditor=new DolEditor('PAYPAL_MESSAGE_OK',$conf->global->PAYPAL_MESSAGE_OK,'',100,'dolibarr_details','In',false,true,true,ROWS_4,'90%'); +$doleditor=new DolEditor('ONLINE_PAYMENT_MESSAGE_OK',$conf->global->ONLINE_PAYMENT_MESSAGE_OK,'',100,'dolibarr_details','In',false,true,true,ROWS_4,'90%'); $doleditor->Create(); print ''; print ''; print $langs->trans("MessageKO").''; -$doleditor=new DolEditor('PAYPAL_MESSAGE_KO',$conf->global->PAYPAL_MESSAGE_KO,'',100,'dolibarr_details','In',false,true,true,ROWS_4,'90%'); +$doleditor=new DolEditor('ONLINE_PAYMENT_MESSAGE_KO',$conf->global->ONLINE_PAYMENT_MESSAGE_KO,'',100,'dolibarr_details','In',false,true,true,ROWS_4,'90%'); $doleditor->Create(); print ''; print ''; -print $langs->trans("PAYPAL_PAYONLINE_SENDEMAIL").''; -print ''; +print $langs->trans("ONLINE_PAYMENT_SENDEMAIL").''; +print ''; print '   '.$langs->trans("Example").': myemail@myserver.com'; print ''; @@ -245,19 +256,18 @@ print ''.$langs->trans("UrlGenerationParameters").''; print ''.$langs->trans("Value").''; print "\n"; - +// Payment token for URL print ''; print $langs->trans("SecurityToken").''; -print ''; +print ''; if (! empty($conf->use_javascript_ajax)) print ' '.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"'); -print ''; + print ''; - -print ''; -print $langs->trans("SecurityTokenIsUnique").''; -print $form->selectyesno("PAYPAL_SECURITY_TOKEN_UNIQUE",(empty($conf->global->PAYPAL_SECURITY_TOKEN)?0:$conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE),1); -print ''; + print ''; + print $langs->trans("SecurityTokenIsUnique").''; + print $form->selectyesno("PAYMENT_SECURITY_TOKEN_UNIQUE",(empty($conf->global->PAYMENT_SECURITY_TOKEN)?0:$conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE),1); + print ''; print ''; @@ -272,7 +282,7 @@ print '

    '; // Help doc print ''.$langs->trans("InformationToFindParameters","Paypal").':
    '; if (! empty($conf->use_javascript_ajax)) - print ''.$langs->trans("ClickHere").'...'; + print ''.$langs->trans("ClickHere").'...'; $realpaypalurl='www.paypal.com'; $sandboxpaypalurl='developer.paypal.com'; @@ -290,128 +300,24 @@ print 'Your API authentication information can be found with following steps. We '; print '
    '; -print '

    '; - -$token=''; - - -// Url list -print ''.$langs->trans("FollowingUrlAreAvailableToMakePayments").':

    '; -print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnFreeAmount",$servicename).':
    '; -print ''.getPaypalPaymentUrl(1,'free')."

    \n"; -if (! empty($conf->commande->enabled)) -{ - print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnOrder",$servicename).':
    '; - print ''.getPaypalPaymentUrl(1,'order')."
    \n"; - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) - { - $langs->load("orders"); - print '
    '; - print $langs->trans("EnterRefToBuildUrl",$langs->transnoentitiesnoconv("Order")).': '; - print ''; - print ''; - if (GETPOST('generate_order_ref','alpha')) - { - print '
    -> '; - $url=getPaypalPaymentUrl(0,'order',GETPOST('generate_order_ref','alpha')); - print $url; - print "
    \n"; - } - print '
    '; - } - print '
    '; -} -if (! empty($conf->facture->enabled)) -{ - print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnInvoice",$servicename).':
    '; - print ''.getPaypalPaymentUrl(1,'invoice')."
    \n"; - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) - { - $langs->load("bills"); - print '
    '; - print $langs->trans("EnterRefToBuildUrl",$langs->transnoentitiesnoconv("Invoice")).': '; - print ''; - print ''; - if (GETPOST('generate_invoice_ref','alpha')) - { - print '
    -> '; - $url=getPaypalPaymentUrl(0,'invoice',GETPOST('generate_invoice_ref','alpha')); - print $url; - print "
    \n"; - } - print '
    '; - } - print '
    '; -} -if (! empty($conf->contrat->enabled)) -{ - print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnContractLine",$servicename).':
    '; - print ''.getPaypalPaymentUrl(1,'contractline')."
    \n"; - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) - { - $langs->load("contract"); - print '
    '; - print $langs->trans("EnterRefToBuildUrl",$langs->transnoentitiesnoconv("Contract")).': '; - print ''; - print ''; - if (GETPOST('generate_contract_ref')) - { - print '
    -> '; - $url=getPaypalPaymentUrl(0,'contractline',GETPOST('generate_contract_ref','alpha')); - print $url; - print "
    \n"; - } - print '
    '; - } - print '
    '; -} -if (! empty($conf->adherent->enabled)) -{ - print img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnMemberSubscription",$servicename).':
    '; - print ''.getPaypalPaymentUrl(1,'membersubscription')."
    \n"; - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) - { - $langs->load("members"); - print '
    '; - print $langs->trans("EnterRefToBuildUrl",$langs->transnoentitiesnoconv("Member")).': '; - print ''; - print ''; - if (GETPOST('generate_member_ref')) - { - print '
    -> '; - $url=getPaypalPaymentUrl(0,'membersubscription',GETPOST('generate_member_ref','alpha')); - print $url; - print "
    \n"; - } - print '
    '; - } - print '
    '; -} - -print info_admin($langs->trans("YouCanAddTagOnUrl")); - if (! empty($conf->use_javascript_ajax)) { print "\n".''; } +print '

    '; + +$token=''; + +include DOL_DOCUMENT_ROOT.'/core/tpl/onlinepaymentlinks.tpl.php'; + llxFooter(); $db->close(); diff --git a/htdocs/paypal/lib/paypal.lib.php b/htdocs/paypal/lib/paypal.lib.php index 944afd34b1a..ecdd2f4fc3e 100644 --- a/htdocs/paypal/lib/paypal.lib.php +++ b/htdocs/paypal/lib/paypal.lib.php @@ -93,7 +93,7 @@ function getPaypalPaymentUrl($mode,$type,$ref='',$amount='9.99',$freetag='your_f global $conf; $ref=str_replace(' ','',$ref); - + if ($type == 'free') { $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?amount='.($mode?'':'').$amount.($mode?'':'').'&tag='.($mode?'':'').$freetag.($mode?'':''); @@ -355,7 +355,7 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, if (! empty($desc)) $nvpstr = $nvpstr . "&DESC=" . urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC - $_SESSION["Payment_Amount"] = $paymentAmount; + $_SESSION["FinalPaymentAmt"] = $paymentAmount; $_SESSION["currencyCodeType"] = $currencyCodeType; $_SESSION["PaymentType"] = $paymentType; $_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR ']; // Payer ip @@ -535,7 +535,7 @@ function hash_call($methodName,$nvpStr) // TODO problem with triggers $API_version="56"; - if (! empty($conf->global->PAYPAL_API_SANDBOX)) + if (! empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox','alpha')) // We can force sand box with param 'forcesandbox' { $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp"; $API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="; diff --git a/htdocs/paypal/lib/paypalfunctions.lib.php b/htdocs/paypal/lib/paypalfunctions.lib.php index 64f0b638c7c..92b24ec60fb 100644 --- a/htdocs/paypal/lib/paypalfunctions.lib.php +++ b/htdocs/paypal/lib/paypalfunctions.lib.php @@ -48,7 +48,7 @@ $API_version="56"; ' For the sandbox, the URL is https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token= ' For the live site, the URL is https://www.paypal.com/webscr&cmd=_express-checkout&token= */ -if (! empty($conf->global->PAYPAL_API_SANDBOX)) +if (! empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox','alpha')) // We can force sand box with param 'forcesandbox' { $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp"; $API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="; diff --git a/htdocs/product/admin/product_extrafields.php b/htdocs/product/admin/product_extrafields.php index 304b0d68333..e7b6a0bd33c 100644 --- a/htdocs/product/admin/product_extrafields.php +++ b/htdocs/product/admin/product_extrafields.php @@ -39,7 +39,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/product/admin/product_lot_extrafields.php b/htdocs/product/admin/product_lot_extrafields.php index fb1cdfcb704..225b1fff45c 100644 --- a/htdocs/product/admin/product_lot_extrafields.php +++ b/htdocs/product/admin/product_lot_extrafields.php @@ -40,7 +40,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/product/ajax/products.php b/htdocs/product/ajax/products.php index 89e2b7a6b26..e24222da70e 100644 --- a/htdocs/product/ajax/products.php +++ b/htdocs/product/ajax/products.php @@ -51,6 +51,7 @@ $price_by_qty_rowid = GETPOST('pbq', 'int'); $finished = GETPOST('finished', 'int'); $alsoproductwithnosupplierprice = GETPOST('alsoproductwithnosupplierprice', 'int'); $warehouseStatus = GETPOST('warehousestatus', 'alpha'); +$hidepriceinlabel = GETPOST('hidepriceinlabel', 'int'); /* @@ -192,7 +193,7 @@ else $form = new Form($db); if (empty($mode) || $mode == 1) { // mode=1: customer - $arrayresult = $form->select_produits_list("", $htmlname, $type, 0, $price_level, $searchkey, $status, $finished, $outjson, $socid, '1', 0, '', 0, $warehouseStatus); + $arrayresult = $form->select_produits_list("", $htmlname, $type, 0, $price_level, $searchkey, $status, $finished, $outjson, $socid, '1', 0, '', $hidepriceinlabel, $warehouseStatus); } elseif ($mode == 2) { // mode=2: supplier $arrayresult = $form->select_produits_fournisseurs_list($socid, "", $htmlname, $type, "", $searchkey, $status, $outjson, 0, $alsoproductwithnosupplierprice); } diff --git a/htdocs/product/canvas/product/actions_card_product.class.php b/htdocs/product/canvas/product/actions_card_product.class.php index 53442d94d39..e33d1e10fd9 100644 --- a/htdocs/product/canvas/product/actions_card_product.class.php +++ b/htdocs/product/canvas/product/actions_card_product.class.php @@ -74,6 +74,7 @@ class ActionsCardProduct */ function assign_values(&$action, $id=0, $ref='') { + global $limit, $offset, $sortfield, $sortorder; global $conf, $langs, $user, $mysoc, $canvas; global $form, $formproduct; @@ -250,7 +251,7 @@ class ActionsCardProduct if ($action == 'list') { - $this->LoadListDatas($GLOBALS['limit'], $GLOBALS['offset'], $GLOBALS['sortfield'], $GLOBALS['sortorder']); + $this->LoadListDatas($limit, $offset, $sortfield, $sortorder); } } @@ -309,7 +310,7 @@ class ActionsCardProduct /** - * Fetch datas list + * Fetch datas list and save into ->list_datas * * @param int $limit Limit number of responses * @param int $offset Offset for first response diff --git a/htdocs/product/canvas/service/actions_card_service.class.php b/htdocs/product/canvas/service/actions_card_service.class.php index f053e6f8d0b..171e3960299 100644 --- a/htdocs/product/canvas/service/actions_card_service.class.php +++ b/htdocs/product/canvas/service/actions_card_service.class.php @@ -73,6 +73,7 @@ class ActionsCardService */ function assign_values(&$action, $id=0, $ref='') { + global $limit, $offset, $sortfield, $sortorder; global $conf, $langs, $user, $mysoc, $canvas; global $form, $formproduct; @@ -229,7 +230,7 @@ class ActionsCardService if ($action == 'list') { - $this->LoadListDatas($GLOBALS['limit'], $GLOBALS['offset'], $GLOBALS['sortfield'], $GLOBALS['sortorder']); + $this->LoadListDatas($limit, $offset, $sortfield, $sortorder); } } @@ -287,7 +288,7 @@ class ActionsCardService } /** - * Fetch datas list + * Fetch datas list and save into ->list_datas * * @param int $limit Limit number of responses * @param int $offset Offset for first response @@ -298,7 +299,7 @@ class ActionsCardService function LoadListDatas($limit, $offset, $sortfield, $sortorder) { global $conf; - global $search_categ,$sall,$sref,$sbarcode,$snom,$catid; + global $search_categ,$sall,$sref,$search_barcode,$snom,$catid; $this->getFieldList(); @@ -320,7 +321,7 @@ class ActionsCardService $sql.= " AND (p.ref LIKE '%".$this->db->escape($sall)."%' OR p.label LIKE '%".$this->db->escape($sall)."%' OR p.description LIKE '%".$this->db->escape($sall)."%' OR p.note LIKE '%".$this->db->escape($sall)."%')"; } if ($sref) $sql.= " AND p.ref LIKE '%".$sref."%'"; - if ($sbarcode) $sql.= " AND p.barcode LIKE '%".$sbarcode."%'"; + if ($search_barcode) $sql.= " AND p.barcode LIKE '%".$search_barcode."%'"; if ($snom) $sql.= " AND p.label LIKE '%".$this->db->escape($snom)."%'"; if (isset($_GET["tosell"]) && dol_strlen($_GET["tosell"]) > 0) { diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 8c6a2aaeebf..4d4cc401022 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -69,7 +69,7 @@ $id=GETPOST('id', 'int'); $ref=GETPOST('ref', 'alpha'); $type=GETPOST('type','int'); $action=(GETPOST('action','alpha') ? GETPOST('action','alpha') : 'view'); -$cancel=GETPOST('cancel'); +$cancel=GETPOST('cancel','alpha'); $confirm=GETPOST('confirm','alpha'); $socid=GETPOST('socid','int'); $duration_value = GETPOST('duration_value'); @@ -110,7 +110,7 @@ if (! empty($canvas)) // Security check $fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); -$fieldtype = (! empty($ref) ? 'ref' : 'rowid'); +$fieldtype = (! empty($id) ? 'rowid' : 'ref'); $result=restrictedArea($user,'produit|service',$fieldvalue,'product&product','','',$fieldtype,$objcanvas); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -281,9 +281,9 @@ if (empty($reshook)) $object->barcode_type_coder = $stdobject->barcode_type_coder; $object->barcode_type_label = $stdobject->barcode_type_label; - $object->description = dol_htmlcleanlastbr(GETPOST('desc')); + $object->description = dol_htmlcleanlastbr(GETPOST('desc','none')); $object->url = GETPOST('url'); - $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private')); + $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private','none')); $object->note = $object->note_private; // deprecated $object->customcode = GETPOST('customcode'); $object->country_id = GETPOST('country_id'); @@ -340,7 +340,7 @@ if (empty($reshook)) if ($id > 0) { // Category association - $categories = GETPOST('categories'); + $categories = GETPOST('categories', 'array'); $object->setCategories($categories); header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); @@ -358,7 +358,7 @@ if (empty($reshook)) // Update a product or service if ($action == 'update' && ($user->rights->produit->creer || $user->rights->service->creer)) { - if (GETPOST('cancel')) + if (GETPOST('cancel','alpha')) { $action = ''; } @@ -370,11 +370,11 @@ if (empty($reshook)) $object->ref = $ref; $object->label = GETPOST('label'); - $object->description = dol_htmlcleanlastbr(GETPOST('desc')); + $object->description = dol_htmlcleanlastbr(GETPOST('desc','none')); $object->url = GETPOST('url'); if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { - $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private')); + $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private','none')); $object->note = $object->note_private; } $object->customcode = GETPOST('customcode'); @@ -444,7 +444,7 @@ if (empty($reshook)) if ($object->update($object->id, $user) > 0) { // Category association - $categories = GETPOST('categories'); + $categories = GETPOST('categories', 'array'); $object->setCategories($categories); $action = 'view'; @@ -977,7 +977,7 @@ else // Description (used in invoice, propal...) print ''.$langs->trans("Description").''; - $doleditor = new DolEditor('desc', GETPOST('desc'), '', 160, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%'); + $doleditor = new DolEditor('desc', GETPOST('desc','none'), '', 160, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%'); $doleditor->Create(); print ""; @@ -990,11 +990,11 @@ else // Stock min level if ($type != 1 && ! empty($conf->stock->enabled)) { - print ''.$langs->trans("StockLimit").''; + print ''.$form->textwithpicto($langs->trans("StockLimit"), $langs->trans("StockLimitDesc"), 1).''; print ''; print ''; // Stock desired level - print ''.$langs->trans("DesiredStock").''; + print ''.$form->textwithpicto($langs->trans("DesiredStock"), $langs->trans("DesiredStockDesc"), 1).''; print ''; print ''; } @@ -1092,7 +1092,7 @@ else print ''.$langs->trans("NoteNotVisibleOnBill").''; // We use dolibarr_details as type of DolEditor here, because we must not accept images as description is included into PDF and not accepted by TCPDF. - $doleditor = new DolEditor('note_private', GETPOST('note_private'), '', 140, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_8, '90%'); + $doleditor = new DolEditor('note_private', GETPOST('note_private','none'), '', 140, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_8, '90%'); $doleditor->Create(); print ""; @@ -1496,7 +1496,7 @@ else dol_fiche_head($head, 'card', $titre, -1, $picto); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter=" fk_product_type = ".$object->type; $shownav = 1; @@ -1764,7 +1764,7 @@ else } // Custom code - if (empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) + if (! $object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) { print ''.$langs->trans("CustomCode").''.$object->customcode.''; diff --git a/htdocs/product/class/api_products.class.php b/htdocs/product/class/api_products.class.php index 0d6694ac569..7b297fcbdc4 100644 --- a/htdocs/product/class/api_products.class.php +++ b/htdocs/product/class/api_products.class.php @@ -16,24 +16,24 @@ */ use Luracast\Restler\RestException; - + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; /** * API class for products * - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} */ class Products extends DolibarrApi { /** - * @var array $FIELDS Mandatory fields, checked when create and update object + * @var array $FIELDS Mandatory fields, checked when create and update object */ static $FIELDS = array( 'ref', - 'label' + 'label' ); /** @@ -53,30 +53,30 @@ class Products extends DolibarrApi /** * Get properties of a product object - * + * * Return an array with product informations * * @param int $id ID of product * @return array|mixed data without useless information - * + * * @throws RestException * TODO implement getting a product by ref or by $ref_ext */ function get($id) - { + { if(! DolibarrApiAccess::$user->rights->produit->lire) { throw new RestException(401); } - + $result = $this->product->fetch($id); if( ! $result ) { throw new RestException(404, 'Product not found'); } - + if( ! DolibarrApi::_checkAccessToResource('product',$this->product->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + $this->product->load_stock(); return $this->_cleanObjectDatas($this->product); @@ -84,9 +84,9 @@ class Products extends DolibarrApi /** * List products - * + * * Get a list of products - * + * * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list @@ -96,11 +96,11 @@ class Products extends DolibarrApi * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)" * @return array Array of product objects */ - function index($sortfield = "t.ref", $sortorder = 'ASC', $limit = 0, $page = 0, $mode=0, $category=0, $sqlfilters = '') { + function index($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode=0, $category=0, $sqlfilters = '') { global $db, $conf; - + $obj_ret = array(); - + $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : ''; $sql = "SELECT t.rowid, t.ref, t.ref_ext"; @@ -121,7 +121,7 @@ class Products extends DolibarrApi // Show services if ($mode == 2) $sql.= " AND t.fk_product_type = 1"; // Add sql filters - if ($sqlfilters) + if ($sqlfilters) { if (! DolibarrApi::_checkFilters($sqlfilters)) { @@ -130,7 +130,7 @@ class Products extends DolibarrApi $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - + $sql.= $db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) @@ -165,10 +165,10 @@ class Products extends DolibarrApi } return $obj_ret; } - + /** * Create product object - * + * * @param array $request_data Request data * @return int ID of product */ @@ -179,35 +179,35 @@ class Products extends DolibarrApi } // Check mandatory fields $result = $this->_validate($request_data); - + foreach($request_data as $field => $value) { $this->product->$field = $value; } if ($this->product->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating product", array_merge(array($this->product->error), $this->product->errors)); } - + return $this->product->id; } /** * Update product - * + * * @param int $id Id of product to update - * @param array $request_data Datas - * @return int + * @param array $request_data Datas + * @return int */ function put($id, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->produit->creer) { throw new RestException(401); } - + $result = $this->product->fetch($id); if( ! $result ) { throw new RestException(404, 'Product not found'); } - + if( ! DolibarrApi::_checkAccessToResource('product',$this->product->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -216,16 +216,16 @@ class Products extends DolibarrApi if ($field == 'id') continue; $this->product->$field = $value; } - + if($this->product->update($id, DolibarrApiAccess::$user,1,'update')) return $this->get ($id); - + return false; } - + /** * Delete product - * + * * @param int $id Product ID * @return array */ @@ -238,18 +238,18 @@ class Products extends DolibarrApi if( ! $result ) { throw new RestException(404, 'Product not found'); } - + if( ! DolibarrApi::_checkAccessToResource('product',$this->product->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + // The Product::delete() method uses the global variable $user. global $user; $user = DolibarrApiAccess::$user; return $this->product->delete(DolibarrApiAccess::$user); } - + /** * Get categories for a product * @@ -263,9 +263,25 @@ class Products extends DolibarrApi * * @url GET {id}/categories */ - function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { - $categories = new Categories(); - return $categories->getListForItem($sortfield, $sortorder, $limit, $page, 'product', $id); + function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) + { + if (! DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $categories = new Categorie($this->db); + + $result = $categories->getListForItem($id, 'product', $sortfield, $sortorder, $limit, $page); + + if (empty($result)) { + throw new RestException(404, 'No category found'); + } + + if ($result < 0) { + throw new RestException(503, 'Error when retrieve category list : '.$categories->error); + } + + return $result; } /** @@ -275,17 +291,17 @@ class Products extends DolibarrApi * @return array Array of cleaned object properties */ function _cleanObjectDatas($object) { - + $object = parent::_cleanObjectDatas($object); - + unset($object->regeximgext); - + return $object; } - + /** * Validate fields before create or update object - * + * * @param array $data Datas to validate * @return array * @throws RestException diff --git a/htdocs/product/class/html.formproduct.class.php b/htdocs/product/class/html.formproduct.class.php index 1c4c3249791..68e80454b22 100644 --- a/htdocs/product/class/html.formproduct.class.php +++ b/htdocs/product/class/html.formproduct.class.php @@ -1,6 +1,6 @@ - * Copyright (C) 2016 Francis Appels + * Copyright (C) 2015-2017 Francis Appels * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -34,6 +34,7 @@ class FormProduct // Cache arrays var $cache_warehouses=array(); + var $cache_lot=array(); /** @@ -219,10 +220,9 @@ class FormProduct include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; $comboenhancement = ajax_combobox($htmlname, $events); $out.= $comboenhancement; - $nodatarole=($comboenhancement?' data-role="none"':''); } - $out.=''; if ($empty) $out.=''; foreach($this->cache_warehouses as $id => $arraytypes) { @@ -330,5 +330,157 @@ class FormProduct return $return; } -} + /** + * Return list of lot numbers (stock from product_batch) with stock location and stock qty + * + * @param int $selected Id of preselected lot stock id ('' for no value, 'ifone'=select value if one value otherwise no value) + * @param string $htmlname Name of html select html + * @param string $filterstatus lot status filter, following comma separated filter options can be used + * @param int $empty 1=Can be empty, 0 if not + * @param int $disabled 1=Select is disabled + * @param int $fk_product show lot numbers of product with id fk_product. All from objectLines if 0. + * @param int $fk_entrepot filter lot numbers for warehouse with id fk_entrepot. All if 0. + * @param array $objectLines Only cache lot numbers for products in lines of object. If no lines only for fk_product. If no fk_product, all. + * @param string $empty_label Empty label if needed (only if $empty=1) + * @param int $forcecombo 1=Force combo iso ajax select2 + * @param array $events Events to add to select2 + * @param string $morecss Add more css classes to HTML select + * + * @return string HTML select + */ + function selectLotStock($selected='',$htmlname='batch_id',$filterstatus='',$empty=0,$disabled=0,$fk_product=0,$fk_entrepot=0,$objectLines = array(),$empty_label='', $forcecombo=0, $events=array(), $morecss='minwidth200') + { + global $langs; + dol_syslog(get_class($this)."::selectLot $selected, $htmlname, $filterstatus, $empty, $disabled, $fk_product, $fk_entrepot, $empty_label, $showstock, $forcecombo, $morecss",LOG_DEBUG); + + $out=''; + $productIdArray = array(); + if (! is_array($objectLines) || ! count($objectLines)) + { + if (! empty($fk_product)) $productIdArray[] = $fk_product; + } + else + { + foreach ($objectLines as $line) { + if ($line->fk_product) $productIdArray[] = $line->fk_product; + } + } + + $nboflot = $this->loadLotStock($productIdArray); + + if ($conf->use_javascript_ajax && ! $forcecombo) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $comboenhancement = ajax_combobox($htmlname, $events); + $out.= $comboenhancement; + } + + $out.=''; + if ($disabled) $out.=''; + + return $out; + } + + /** + * Load in cache array list of lot available in stock from a given list of products + * + * @param array $productIdArray array of product id's from who to get lot numbers. A + * + * @return int Nb of loaded lines, 0 if nothing loaded, <0 if KO + */ + private function loadLotStock($productIdArray = array()) + { + global $conf, $langs; + + $cacheLoaded = false; + if (empty($productIdArray)) + { + // only Load lot stock for given products + $this->cache_lot = array(); + return 0; + } + if (count($productIdArray) && count($this->cache_lot)) + { + // check cache already loaded for product id's + foreach ($productIdArray as $productId) + { + $cacheLoaded = ! empty($this->cache_lot[$productId]) ? true : false; + } + } + if ($cacheLoaded) + { + return count($this->cache_lot); + } + else + { + // clear cache + $this->cache_lot = array(); + $productIdList = implode(',', $productIdArray); + $sql = "SELECT pb.batch, pb.rowid, ps.fk_entrepot, pb.qty, e.label, ps.fk_product"; + $sql.= " FROM ".MAIN_DB_PREFIX."product_batch as pb"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.rowid = pb.fk_product_stock"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on e.rowid = ps.fk_entrepot AND e.entity IN (".getEntity('stock').")"; + if (!empty($productIdList)) + { + $sql.= " WHERE ps.fk_product IN (".$productIdList.")"; + } + $sql.= " ORDER BY e.label, pb.batch"; + + dol_syslog(get_class($this).'::loadLotStock', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $this->cache_lot[$obj->fk_product][$obj->rowid]['id'] =$obj->rowid; + $this->cache_lot[$obj->fk_product][$obj->rowid]['batch']=$obj->batch; + $this->cache_lot[$obj->fk_product][$obj->rowid]['entrepot_id']=$obj->fk_entrepot; + $this->cache_lot[$obj->fk_product][$obj->rowid]['entrepot_label']=$obj->label; + $this->cache_lot[$obj->fk_product][$obj->rowid]['qty'] = $obj->qty; + $i++; + } + + return $num; + } + else + { + dol_print_error($this->db); + return -1; + } + } + } +} \ No newline at end of file diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 05adfc1b5c5..e2ea5d8cb9f 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -47,8 +47,7 @@ class Product extends CommonObject public $table_element='product'; public $fk_element='fk_product'; protected $childtables=array('supplier_proposaldet', 'propaldet','commandedet','facturedet','contratdet','facture_fourn_det','commande_fournisseurdet'); // To test if we can delete object - protected $isnolinkedbythird = 1; // No field fk_soc - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe /** * {@inheritdoc} @@ -536,12 +535,12 @@ class Product extends CommonObject $sql.= ", ".$this->type; $sql.= ", ".price2num($price_ht); $sql.= ", ".price2num($price_ttc); - $sql.= ", '".$this->price_base_type."'"; + $sql.= ", '".$this->db->escape($this->price_base_type)."'"; $sql.= ", ".$this->status; $sql.= ", ".$this->status_buy; - $sql.= ", '".$this->accountancy_code_buy."'"; - $sql.= ", '".$this->accountancy_code_sell."'"; - $sql.= ", '".$this->canvas."'"; + $sql.= ", '".$this->db->escape($this->accountancy_code_buy)."'"; + $sql.= ", '".$this->db->escape($this->accountancy_code_sell)."'"; + $sql.= ", '".$this->db->escape($this->canvas)."'"; $sql.= ", ".((! isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'null' : (int) $this->finished); $sql.= ", ".((empty($this->status_batch) || $this->status_batch < 0)? '0':$this->status_batch); $sql.= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit); @@ -853,8 +852,8 @@ class Product extends CommonObject $sql.= ", recuperableonly = " . $this->tva_npr; $sql.= ", localtax1_tx = " . $this->localtax1_tx; $sql.= ", localtax2_tx = " . $this->localtax2_tx; - $sql.= ", localtax1_type = " . ($this->localtax1_type!=''?"'".$this->localtax1_type."'":"'0'"); - $sql.= ", localtax2_type = " . ($this->localtax2_type!=''?"'".$this->localtax2_type."'":"'0'"); + $sql.= ", localtax1_type = " . ($this->localtax1_type!=''?"'".$this->db->escape($this->localtax1_type)."'":"'0'"); + $sql.= ", localtax2_type = " . ($this->localtax2_type!=''?"'".$this->db->escape($this->localtax2_type)."'":"'0'"); $sql.= ", barcode = ". (empty($this->barcode)?"null":"'".$this->db->escape($this->barcode)."'"); $sql.= ", fk_barcode_type = ". (empty($this->barcode_type)?"null":$this->db->escape($this->barcode_type)); @@ -863,19 +862,19 @@ class Product extends CommonObject $sql.= ", tobuy = " . $this->status_buy; $sql.= ", tobatch = " . ((empty($this->status_batch) || $this->status_batch < 0) ? '0' : $this->status_batch); $sql.= ", finished = " . ((! isset($this->finished) || $this->finished < 0) ? "null" : (int) $this->finished); - $sql.= ", weight = " . ($this->weight!='' ? "'".$this->weight."'" : 'null'); - $sql.= ", weight_units = " . ($this->weight_units!='' ? "'".$this->weight_units."'": 'null'); - $sql.= ", length = " . ($this->length!='' ? "'".$this->length."'" : 'null'); - $sql.= ", length_units = " . ($this->length_units!='' ? "'".$this->length_units."'" : 'null'); - $sql.= ", width= " . ($this->width!='' ? "'".$this->width."'" : 'null'); - $sql.= ", width_units = " . ($this->width_units!='' ? "'".$this->width_units."'" : 'null'); - $sql.= ", height = " . ($this->height!='' ? "'".$this->height."'" : 'null'); - $sql.= ", height_units = " . ($this->height_units!='' ? "'".$this->height_units."'" : 'null'); - $sql.= ", surface = " . ($this->surface!='' ? "'".$this->surface."'" : 'null'); - $sql.= ", surface_units = " . ($this->surface_units!='' ? "'".$this->surface_units."'" : 'null'); - $sql.= ", volume = " . ($this->volume!='' ? "'".$this->volume."'" : 'null'); - $sql.= ", volume_units = " . ($this->volume_units!='' ? "'".$this->volume_units."'" : 'null'); - $sql.= ", seuil_stock_alerte = " . ((isset($this->seuil_stock_alerte) && $this->seuil_stock_alerte != '') ? "'".$this->seuil_stock_alerte."'" : "null"); + $sql.= ", weight = " . ($this->weight!='' ? "'".$this->db->escape($this->weight)."'" : 'null'); + $sql.= ", weight_units = " . ($this->weight_units!='' ? "'".$this->db->escape($this->weight_units)."'": 'null'); + $sql.= ", length = " . ($this->length!='' ? "'".$this->db->escape($this->length)."'" : 'null'); + $sql.= ", length_units = " . ($this->length_units!='' ? "'".$this->db->escape($this->length_units)."'" : 'null'); + $sql.= ", width= " . ($this->width!='' ? "'".$this->db->escape($this->width)."'" : 'null'); + $sql.= ", width_units = " . ($this->width_units!='' ? "'".$this->db->escape($this->width_units)."'" : 'null'); + $sql.= ", height = " . ($this->height!='' ? "'".$this->db->escape($this->height)."'" : 'null'); + $sql.= ", height_units = " . ($this->height_units!='' ? "'".$this->db->escape($this->height_units)."'" : 'null'); + $sql.= ", surface = " . ($this->surface!='' ? "'".$this->db->escape($this->surface)."'" : 'null'); + $sql.= ", surface_units = " . ($this->surface_units!='' ? "'".$this->db->escape($this->surface_units)."'" : 'null'); + $sql.= ", volume = " . ($this->volume!='' ? "'".$this->db->escape($this->volume)."'" : 'null'); + $sql.= ", volume_units = " . ($this->volume_units!='' ? "'".$this->db->escape($this->volume_units)."'" : 'null'); + $sql.= ", seuil_stock_alerte = " . ((isset($this->seuil_stock_alerte) && $this->seuil_stock_alerte != '') ? "'".$this->db->escape($this->seuil_stock_alerte)."'" : "null"); $sql.= ", description = '" . $this->db->escape($this->description) ."'"; $sql.= ", url = " . ($this->url?"'".$this->db->escape($this->url)."'":'null'); $sql.= ", customcode = '" . $this->db->escape($this->customcode) ."'"; @@ -1439,8 +1438,8 @@ class Product extends CommonObject // Add new price $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_price(price_level,date_price, fk_product, fk_user_author, price, price_ttc, price_base_type,tosell, tva_tx, default_vat_code, recuperableonly,"; $sql.= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) "; - $sql.= " VALUES(".($level?$level:1).", '".$this->db->idate($now)."',".$this->id.",".$user->id.",".$this->price.",".$this->price_ttc.",'".$this->price_base_type."',".$this->status.",".$this->tva_tx.", ".($this->default_vat_code?("'".$this->default_vat_code."'"):"null").",".$this->tva_npr.","; - $sql.= " ".$this->localtax1_tx.", ".$this->localtax2_tx.", '".$this->localtax1_type."', '".$this->localtax2_type."', ".$this->price_min.",".$this->price_min_ttc.",".$this->price_by_qty.",".$conf->entity.",".($this->fk_price_expression > 0?$this->fk_price_expression:'null'); + $sql.= " VALUES(".($level?$level:1).", '".$this->db->idate($now)."',".$this->id.",".$user->id.",".$this->price.",".$this->price_ttc.",'".$this->db->escape($this->price_base_type)."',".$this->status.",".$this->tva_tx.", ".($this->default_vat_code?("'".$this->db->escape($this->default_vat_code)."'"):"null").",".$this->tva_npr.","; + $sql.= " ".$this->localtax1_tx.", ".$this->localtax2_tx.", '".$this->db->escape($this->localtax1_type)."', '".$this->db->escape($this->localtax2_type)."', ".$this->price_min.",".$this->price_min_ttc.",".$this->price_by_qty.",".$conf->entity.",".($this->fk_price_expression > 0?$this->fk_price_expression:'null'); $sql.= ")"; dol_syslog(get_class($this)."::_log_price", LOG_DEBUG); @@ -2135,6 +2134,49 @@ class Product extends CommonObject } + /** + * Charge tableau des stats propale pour le produit/service + * + * @param int $socid Id thirdparty + * @return array Tableau des stats + */ + function load_stats_proposal_supplier($socid=0) + { + global $conf; + global $user; + + $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,"; + $sql.= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty"; + $sql.= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as pd"; + $sql.= ", ".MAIN_DB_PREFIX."supplier_proposal as p"; + $sql.= ", ".MAIN_DB_PREFIX."societe as s"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql.= " WHERE p.rowid = pd.fk_supplier_proposal"; + $sql.= " AND p.fk_soc = s.rowid"; + $sql.= " AND p.entity IN (".getEntity('supplier_proposal').")"; + $sql.= " AND pd.fk_product = ".$this->id; + if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + //$sql.= " AND pr.fk_statut != 0"; + if ($socid > 0) $sql.= " AND p.fk_soc = ".$socid; + + $result = $this->db->query($sql); + if ( $result ) + { + $obj=$this->db->fetch_object($result); + $this->stats_proposal_supplier['suppliers']=$obj->nb_suppliers; + $this->stats_proposal_supplier['nb']=$obj->nb; + $this->stats_proposal_supplier['rows']=$obj->nb_rows; + $this->stats_proposal_supplier['qty']=$obj->qty?$obj->qty:0; + return 1; + } + else + { + $this->error=$this->db->error(); + return -1; + } + } + + /** * Charge tableau des stats commande client pour le produit/service * @@ -3373,12 +3415,13 @@ class Product extends CommonObject /** * Return clicable link of object (with eventually picto) * - * @param int $withpicto Add picto into link - * @param string $option Where point the link ('stock', 'composition', 'category', 'supplier', '') - * @param int $maxlength Maxlength of ref - * @return string String with URL + * @param int $withpicto Add picto into link + * @param string $option Where point the link ('stock', 'composition', 'category', 'supplier', '') + * @param int $maxlength Maxlength of ref + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - function getNomUrl($withpicto=0,$option='',$maxlength=0) + function getNomUrl($withpicto=0, $option='', $maxlength=0, $save_lastsearch_value=-1) { global $conf, $langs, $hookmanager; include_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; @@ -3415,7 +3458,6 @@ class Product extends CommonObject if ($this->nbphoto > 0) $label .= '
    ' . $tmpphoto; } - $linkclose=''; if (empty($notooltip)) { @@ -3426,7 +3468,7 @@ class Product extends CommonObject } $linkclose.= ' title="'.dol_escape_htmltag($label, 1, 1).'"'; - $linkclose.=' class="classfortooltip"'; + $linkclose.= ' class="classfortooltip"'; if (! is_object($hookmanager)) { @@ -3449,15 +3491,25 @@ class Product extends CommonObject $url = DOL_URL_ROOT.'/product/card.php?id='.$this->id; } + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + $linkstart = ''; $linkend=''; + $result.=$linkstart; if ($withpicto) { - if ($this->type == Product::TYPE_PRODUCT) $result.=($linkstart.img_object(($notooltip?'':$label), 'product', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' '); - if ($this->type == Product::TYPE_SERVICE) $result.=($linkstart.img_object(($notooltip?'':$label), 'service', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' '); + if ($this->type == Product::TYPE_PRODUCT) $result.=(img_object(($notooltip?'':$label), 'product', ($notooltip?'class="paddingright"':'class="paddingright classfortooltip"'), 0, 0, $notooltip?0:1)); + if ($this->type == Product::TYPE_SERVICE) $result.=(img_object(($notooltip?'':$label), 'service', ($notooltip?'class="paddinright"':'class="paddingright classfortooltip"'), 0, 0, $notooltip?0:1)); } - $result.=$linkstart.$newref.$linkend; + $result.= $newref; + $result.= $linkend; return $result; } @@ -3545,14 +3597,11 @@ class Product extends CommonObject case 2: return $this->LibStatut($status,3,2).' '.$this->LibStatut($status,1,2); case 3: - if ($status == 0 ) + if ($status == 0) { return img_picto($langs->trans('ProductStatusNotOnBatch'),'statut5'); } - else - { - return img_picto($langs->trans('ProductStatusOnBatch'),'statut4'); - } + return img_picto($langs->trans('ProductStatusOnBatch'),'statut4'); case 4: return $this->LibStatut($status,3,2).' '.$this->LibStatut($status,0,2); case 5: @@ -4024,31 +4073,7 @@ class Product extends CommonObject $filearray=array_merge($filearray, $filearrayold); } - $filearrayindatabase = dol_dir_list_in_database($relativedir, '', null, 'name', SORT_ASC); - - //var_dump($filearray); - //var_dump($filearrayindatabase); - - // Complete filearray with properties found into $filearrayindatabase - foreach($filearray as $key => $val) - { - $found=0; - // Search if it exists into $filearrayindatabase - foreach($filearrayindatabase as $key2 => $val2) - { - if ($filearrayindatabase[$key2]['name'] == $filearray[$key]['name']) - { - $filearray[$key]['position_name']=($filearrayindatabase[$key2]['position']?$filearrayindatabase[$key2]['position']:'0').'_'.$filearrayindatabase[$key2]['name']; - $filearray[$key]['position']=$filearrayindatabase[$key2]['position']; - $filearray[$key]['cover']=$filearrayindatabase[$key2]['cover']; - $filearray[$key]['acl']=$filearrayindatabase[$key2]['acl']; - $filearray[$key]['rowid']=$filearrayindatabase[$key2]['rowid']; - $filearray[$key]['label']=$filearrayindatabase[$key2]['label']; - $found=1; - break; - } - } - } + completeFileArrayWithDatabaseInfo($filearray, $relativedir); if (count($filearray)) { diff --git a/htdocs/product/class/productbatch.class.php b/htdocs/product/class/productbatch.class.php index 5ab70506693..64a43485604 100644 --- a/htdocs/product/class/productbatch.class.php +++ b/htdocs/product/class/productbatch.class.php @@ -154,7 +154,7 @@ class Productbatch extends CommonObject $sql.= " pl.sellby"; $sql.= " FROM ".MAIN_DB_PREFIX."product_batch as t INNER JOIN ".MAIN_DB_PREFIX."product_stock w on t.fk_product_stock = w.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl on pl.fk_product = w.fk_product and pl.batch = t.batch"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl on pl.fk_product = w.fk_product and pl.batch = t.batch"; $sql.= " WHERE t.rowid = ".$id; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -205,9 +205,9 @@ class Productbatch extends CommonObject // TODO Check qty is ok for stock move. Negative may not be allowed. if ($this->qty < 0) { - + } - + // Update request $sql = "UPDATE ".MAIN_DB_PREFIX.self::$_table_element." SET"; $sql.= " fk_product_stock=".(isset($this->fk_product_stock)?$this->fk_product_stock:"null").","; @@ -435,7 +435,7 @@ class Productbatch extends CommonObject if (! empty($eatby)) array_push($where," eatby = '".$this->db->idate($eatby)."'"); // deprecated if (! empty($sellby)) array_push($where," sellby = '".$this->db->idate($sellby)."'"); // deprecated - + if (! empty($batch_number)) $sql.= " AND batch = '".$this->db->escape($batch_number)."'"; if (! empty($where)) $sql.= " AND (".implode(" OR ",$where).")"; @@ -493,7 +493,7 @@ class Productbatch extends CommonObject $sql.= " t.import_key"; if ($fk_product > 0) { - $sql.= ", pl.eatby as eatby, pl.sellby as sellby"; + $sql.= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby"; // TODO May add extrafields to ? } $sql.= " FROM ".MAIN_DB_PREFIX."product_batch as t"; @@ -517,6 +517,7 @@ class Productbatch extends CommonObject $tmp = new Productbatch($db); $tmp->id = $obj->rowid; + $tmp->lotid = $obj->lotid; $tmp->tms = $db->jdate($obj->tms); $tmp->fk_product_stock = $obj->fk_product_stock; $tmp->sellby = $db->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby); diff --git a/htdocs/product/class/productcustomerprice.class.php b/htdocs/product/class/productcustomerprice.class.php index 4ff018bf031..5b41cb0f02b 100644 --- a/htdocs/product/class/productcustomerprice.class.php +++ b/htdocs/product/class/productcustomerprice.class.php @@ -161,19 +161,19 @@ class Productcustomerprice extends CommonObject $sql .= ") VALUES ("; $sql .= " " . $conf->entity . ","; $sql .= " '" . $this->db->idate(dol_now()) . "',"; - $sql .= " " . (! isset($this->fk_product) ? 'NULL' : "'" . $this->fk_product . "'") . ","; - $sql .= " " . (! isset($this->fk_soc) ? 'NULL' : "'" . $this->fk_soc . "'") . ","; - $sql .= " " . (empty($this->price) ? '0' : "'" . $this->price . "'") . ","; - $sql .= " " . (empty($this->price_ttc) ? '0' : "'" . $this->price_ttc . "'") . ","; - $sql .= " " . (empty($this->price_min) ? '0' : "'" . $this->price_min . "'") . ","; - $sql .= " " . (empty($this->price_min_ttc) ? '0' : "'" . $this->price_min_ttc . "'") . ","; + $sql .= " " . (! isset($this->fk_product) ? 'NULL' : "'" . $this->db->escape($this->fk_product) . "'") . ","; + $sql .= " " . (! isset($this->fk_soc) ? 'NULL' : "'" . $this->db->escape($this->fk_soc) . "'") . ","; + $sql .= " " . (empty($this->price) ? '0' : "'" . $this->db->escape($this->price) . "'") . ","; + $sql .= " " . (empty($this->price_ttc) ? '0' : "'" . $this->db->escape($this->price_ttc) . "'") . ","; + $sql .= " " . (empty($this->price_min) ? '0' : "'" . $this->db->escape($this->price_min) . "'") . ","; + $sql .= " " . (empty($this->price_min_ttc) ? '0' : "'" . $this->db->escape($this->price_min_ttc) . "'") . ","; $sql .= " " . (! isset($this->price_base_type) ? 'NULL' : "'" . $this->db->escape($this->price_base_type) . "'") . ","; $sql .= " ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null").","; $sql .= " " . (! isset($this->tva_tx) ? 'NULL' : (empty($this->tva_tx)?0:$this->tva_tx)) . ","; - $sql .= " " . (! isset($this->recuperableonly) ? 'NULL' : "'" . $this->recuperableonly . "'") . ","; - $sql .= " " . (empty($this->localtax1_type) ? "'0'" : "'" . $this->localtax1_type . "'") . ","; + $sql .= " " . (! isset($this->recuperableonly) ? 'NULL' : "'" . $this->db->escape($this->recuperableonly) . "'") . ","; + $sql .= " " . (empty($this->localtax1_type) ? "'0'" : "'" . $this->db->escape($this->localtax1_type) . "'") . ","; $sql .= " " . (! isset($this->localtax1_tx) ? 'NULL' : (empty($this->localtax1_tx)?0:$this->localtax1_tx)) . ","; - $sql .= " " . (empty($this->localtax2_type) ? "'0'" : "'" . $this->localtax2_type . "'") . ","; + $sql .= " " . (empty($this->localtax2_type) ? "'0'" : "'" . $this->db->escape($this->localtax2_type) . "'") . ","; $sql .= " " . (! isset($this->localtax2_tx) ? 'NULL' : (empty($this->localtax2_tx)?0:$this->localtax2_tx)) . ","; $sql .= " " . $user->id . ","; $sql .= " " . (! isset($this->import_key) ? 'NULL' : "'" . $this->db->escape($this->import_key) . "'") . ""; @@ -664,8 +664,8 @@ class Productcustomerprice extends CommonObject $sql .= " recuperableonly=" . (isset($this->recuperableonly) ? $this->recuperableonly : "null") . ","; $sql .= " localtax1_tx=" . (isset($this->localtax1_tx) ? (empty($this->localtax1_tx)?0:$this->localtax1_tx) : "null") . ","; $sql .= " localtax2_tx=" . (isset($this->localtax2_tx) ? (empty($this->localtax2_tx)?0:$this->localtax2_tx) : "null") . ","; - $sql .= " localtax1_type=" . (! empty($this->localtax1_type) ? "'".$this->localtax1_type."'": "'0'") . ","; - $sql .= " localtax2_type=" . (! empty($this->localtax2_type) ? "'".$this->localtax2_type."'": "'0'") . ","; + $sql .= " localtax1_type=" . (! empty($this->localtax1_type) ? "'".$this->db->escape($this->localtax1_type)."'": "'0'") . ","; + $sql .= " localtax2_type=" . (! empty($this->localtax2_type) ? "'".$this->db->escape($this->localtax2_type)."'": "'0'") . ","; $sql .= " fk_user=" . $user->id . ","; $sql .= " import_key=" . (isset($this->import_key) ? "'" . $this->db->escape($this->import_key) . "'" : "null") . ""; @@ -680,15 +680,12 @@ class Productcustomerprice extends CommonObject if (! $error) { if (! $notrigger) { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action calls a trigger. - - // // Call triggers - // include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - // $interface=new Interfaces($this->db); - // $result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - // if ($result < 0) { $error++; $this->errors=$interface->errors; } - // // End call triggers + // Call triggers + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers('PRODUCT_CUSTOMER_PRICE_UPDATE',$this,$user,$langs,$conf); + if ($result < 0) { $error++; $this->errors=$interface->errors; } + // End call triggers } } diff --git a/htdocs/product/class/propalmergepdfproduct.class.php b/htdocs/product/class/propalmergepdfproduct.class.php index 865589692fb..87fdd132878 100644 --- a/htdocs/product/class/propalmergepdfproduct.class.php +++ b/htdocs/product/class/propalmergepdfproduct.class.php @@ -33,7 +33,7 @@ class Propalmergepdfproduct extends CommonObject { var $element='propal_merge_pdf_product'; //!< Id that identify managed objects var $table_element='propal_merge_pdf_product'; //!< Name of table without prefix where object is stored - + var $fk_product; var $file_name; var $fk_user_author; @@ -41,10 +41,10 @@ class Propalmergepdfproduct extends CommonObject var $datec=''; var $tms=''; var $lang; - + var $lines=array(); - + /** @@ -72,7 +72,7 @@ class Propalmergepdfproduct extends CommonObject $error=0; // Clean parameters - + if (isset($this->fk_product)) $this->fk_product=trim($this->fk_product); if (isset($this->file_name)) $this->file_name=trim($this->file_name); if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author); @@ -80,14 +80,14 @@ class Propalmergepdfproduct extends CommonObject if (isset($this->lang)) $this->lang=trim($this->lang); if (isset($this->import_key)) $this->import_key=trim($this->import_key); - + // Check parameters // Put here code to add control on parameters values // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal_merge_pdf_product("; - + $sql.= "fk_product,"; $sql.= "file_name,"; if ($conf->global->MAIN_MULTILANGS) { @@ -97,10 +97,10 @@ class Propalmergepdfproduct extends CommonObject $sql.= "fk_user_mod,"; $sql.= "datec"; - + $sql.= ") VALUES ("; - - $sql.= " ".(! isset($this->fk_product)?'NULL':"'".$this->fk_product."'").","; + + $sql.= " ".(! isset($this->fk_product)?'NULL':"'".$this->db->escape($this->fk_product)."'").","; $sql.= " ".(! isset($this->file_name)?'NULL':"'".$this->db->escape($this->file_name)."'").","; if ($conf->global->MAIN_MULTILANGS) { $sql.= " ".(! isset($this->lang)?'NULL':"'".$this->db->escape($this->lang)."'").","; @@ -109,7 +109,7 @@ class Propalmergepdfproduct extends CommonObject $sql.= " ".$user->id.","; $sql.= " '".$this->db->idate(dol_now())."'"; - + $sql.= ")"; $this->db->begin(); @@ -164,10 +164,10 @@ class Propalmergepdfproduct extends CommonObject function fetch($id) { global $langs,$conf; - + $sql = "SELECT"; $sql.= " t.rowid,"; - + $sql.= " t.fk_product,"; $sql.= " t.file_name,"; $sql.= " t.lang,"; @@ -177,7 +177,7 @@ class Propalmergepdfproduct extends CommonObject $sql.= " t.tms,"; $sql.= " t.import_key"; - + $sql.= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t"; $sql.= " WHERE t.rowid = ".$id; @@ -190,7 +190,7 @@ class Propalmergepdfproduct extends CommonObject $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; - + $this->fk_product = $obj->fk_product; $this->file_name = $obj->file_name; if ($conf->global->MAIN_MULTILANGS) { @@ -202,7 +202,7 @@ class Propalmergepdfproduct extends CommonObject $this->tms = $this->db->jdate($obj->tms); $this->import_key = $obj->import_key; - + } $this->db->free($resql); @@ -215,7 +215,7 @@ class Propalmergepdfproduct extends CommonObject return -1; } } - + /** * Load object in memory from the database * @@ -226,10 +226,10 @@ class Propalmergepdfproduct extends CommonObject function fetch_by_product($product_id, $lang='') { global $langs,$conf; - + $sql = "SELECT"; $sql.= " t.rowid,"; - + $sql.= " t.fk_product,"; $sql.= " t.file_name,"; $sql.= " t.lang,"; @@ -238,14 +238,14 @@ class Propalmergepdfproduct extends CommonObject $sql.= " t.datec,"; $sql.= " t.tms,"; $sql.= " t.import_key"; - - + + $sql.= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t"; $sql.= " WHERE t.fk_product = ".$product_id; if ($conf->global->MAIN_MULTILANGS && !empty($lang)) { $sql.= " AND t.lang = '".$lang."'"; } - + dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -253,11 +253,11 @@ class Propalmergepdfproduct extends CommonObject if ($this->db->num_rows($resql)) { while($obj = $this->db->fetch_object($resql)) { - + $line = new PropalmergepdfproductLine(); - + $line->id = $obj->rowid; - + $line->fk_product = $obj->fk_product; $line->file_name = $obj->file_name; if ($conf->global->MAIN_MULTILANGS) { @@ -268,21 +268,21 @@ class Propalmergepdfproduct extends CommonObject $line->datec = $this->db->jdate($obj->datec); $line->tms = $this->db->jdate($obj->tms); $line->import_key = $obj->import_key; - - + + if ($conf->global->MAIN_MULTILANGS) { $this->lines[$obj->file_name.'_'.$obj->lang]=$line; }else { $this->lines[$obj->file_name]=$line; } - - + + } - - + + } $this->db->free($resql); - + return 1; } else @@ -307,21 +307,21 @@ class Propalmergepdfproduct extends CommonObject $error=0; // Clean parameters - + if (isset($this->fk_product)) $this->fk_product=trim($this->fk_product); if (isset($this->file_name)) $this->file_name=trim($this->file_name); if (isset($this->fk_user_mod)) $this->fk_user_mod=trim($this->fk_user_mod); if (isset($this->lang)) $this->lang=trim($this->lang); - - + + // Check parameters // Put here code to add a control on parameters values // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."propal_merge_pdf_product SET"; - + $sql.= " fk_product=".(isset($this->fk_product)?$this->fk_product:"null").","; $sql.= " file_name=".(isset($this->file_name)?"'".$this->db->escape($this->file_name)."'":"null").","; if ($conf->global->MAIN_MULTILANGS) { @@ -329,7 +329,7 @@ class Propalmergepdfproduct extends CommonObject } $sql.= " fk_user_mod=".$user->id; - + $sql.= " WHERE rowid=".$this->id; $this->db->begin(); @@ -430,7 +430,7 @@ class Propalmergepdfproduct extends CommonObject return 1; } } - + /** * Delete object in database * @@ -444,16 +444,16 @@ class Propalmergepdfproduct extends CommonObject { global $conf, $langs; $error=0; - + $this->db->begin(); - + if (! $error) { if (! $notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. - + //// Call triggers //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; //$interface=new Interfaces($this->db); @@ -462,21 +462,21 @@ class Propalmergepdfproduct extends CommonObject //// End call triggers } } - + if (! $error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product"; $sql.= " WHERE fk_product=".$product_id; - + if ($conf->global->MAIN_MULTILANGS && !empty($lang_id)) { $sql.= " AND lang='".$lang_id."'"; } - + dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } } - + // Commit or rollback if ($error) { @@ -494,7 +494,7 @@ class Propalmergepdfproduct extends CommonObject return 1; } } - + /** * Delete object in database * @@ -505,16 +505,16 @@ class Propalmergepdfproduct extends CommonObject { global $conf, $langs; $error=0; - + $this->db->begin(); - + if (! $error) { if (! $notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. - + //// Call triggers //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; //$interface=new Interfaces($this->db); @@ -523,17 +523,17 @@ class Propalmergepdfproduct extends CommonObject //// End call triggers } } - + if (! $error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product"; $sql.= " WHERE fk_product=".$this->fk_product." AND file_name='".$this->db->escape($this->file_name)."'"; - + dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } } - + // Commit or rollback if ($error) { @@ -617,7 +617,7 @@ class Propalmergepdfproduct extends CommonObject function initAsSpecimen() { $this->id=0; - + $this->fk_product=''; $this->file_name=''; $this->fk_user_author=''; @@ -626,7 +626,7 @@ class Propalmergepdfproduct extends CommonObject $this->tms=''; $this->import_key=''; - + } } @@ -637,7 +637,7 @@ class Propalmergepdfproduct extends CommonObject class PropalmergepdfproductLine { var $id; - + var $fk_product; var $file_name; var $lang; diff --git a/htdocs/product/composition/card.php b/htdocs/product/composition/card.php index 946ce1be7a8..a6cc3427243 100644 --- a/htdocs/product/composition/card.php +++ b/htdocs/product/composition/card.php @@ -203,7 +203,7 @@ if ($id > 0 || ! empty($ref)) */ if ($user->rights->produit->lire || $user->rights->service->lire) { - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; @@ -552,7 +552,8 @@ if ($id > 0 || ! empty($ref)) // check if a product is not already a parent product of this one $prod_arbo=new Product($db); $prod_arbo->id=$objp->rowid; - if ($prod_arbo->type==Product::TYPE_ASSEMBLYKIT || $prod_arbo->type== Product::TYPE_STOCKKIT) + // This type is not supported (not required to have virtual products working). + if ($prod_arbo->type == Product::TYPE_ASSEMBLYKIT || $prod_arbo->type == Product::TYPE_STOCKKIT) { $is_pere=0; $prod_arbo->get_sousproduits_arbo(); diff --git a/htdocs/product/document.php b/htdocs/product/document.php index 53bbbfeeabb..fd67cd72504 100644 --- a/htdocs/product/document.php +++ b/htdocs/product/document.php @@ -212,7 +212,7 @@ if ($object->id) } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter=" fk_product_type = ".$object->type; $shownav = 1; diff --git a/htdocs/product/fournisseurs.php b/htdocs/product/fournisseurs.php index cb295012795..6124bc9161a 100644 --- a/htdocs/product/fournisseurs.php +++ b/htdocs/product/fournisseurs.php @@ -308,7 +308,7 @@ if ($id > 0 || $ref) dol_fiche_head($head, 'suppliers', $titre, -1, $picto); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter=" fk_product_type = ".$object->type; $shownav = 1; diff --git a/htdocs/product/index.php b/htdocs/product/index.php index 8f2ef96a4f5..3e29bf4e041 100644 --- a/htdocs/product/index.php +++ b/htdocs/product/index.php @@ -134,6 +134,8 @@ while ($objp = $db->fetch_object($result)) $prodser[$objp->fk_product_type][$status]=$objp->total; } + +print '
    '; print ''; print ''; if (! empty($conf->product->enabled)) @@ -188,11 +190,13 @@ print ''; + print ''; print ''; print ''; } else { // TVA - print ''; - if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) print ''; + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) print ''; else print ''; print ''; @@ -1436,7 +1439,7 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ print ''; print $conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print ''; + if (empty($conf->global->PRODUIT_MULTIPRICES)) print ''; print ''; print ''; if (! empty($conf->dynamicprices->enabled)) { @@ -1563,10 +1566,8 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); - $page = GETPOST("page", 'int'); - if ($page == - 1) { - $page = 0; - } + $page = (GETPOST("page",'int')?GETPOST("page", 'int'):0); + if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -1605,7 +1606,7 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print ''; // VAT - print ''; @@ -1694,7 +1695,7 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print ''; // VAT - print ''; @@ -1798,7 +1799,7 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") print ''; @@ -1919,7 +1920,7 @@ var_dump($prodcustprice);exit; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") print ''; diff --git a/htdocs/product/reassort.php b/htdocs/product/reassort.php index e3983344cff..b61b9043d95 100644 --- a/htdocs/product/reassort.php +++ b/htdocs/product/reassort.php @@ -44,7 +44,7 @@ $sref=GETPOST("sref"); $snom=GETPOST("snom"); $sall=GETPOST('sall', 'alphanohtml'); $type=GETPOST("type","int"); -$sbarcode=GETPOST("sbarcode"); +$search_barcode=GETPOST("search_barcode"); $catid=GETPOST('catid','int'); $toolowstock=GETPOST('toolowstock'); $tosell = GETPOST("tosell"); @@ -135,7 +135,7 @@ if (dol_strlen($type)) } } if ($sref) $sql.= natural_search('p.ref', $ref); -if ($sbarcode) $sql.= natural_search('p.barcode', $sbarcode); +if ($search_barcode) $sql.= natural_search('p.barcode', $search_barcode); if ($snom) $sql.= natural_search('p.label', $snom); if (! empty($tosell)) $sql.= " AND p.tosell = ".$tosell; if (! empty($tobuy)) $sql.= " AND p.tobuy = ".$tobuy; diff --git a/htdocs/product/reassortlot.php b/htdocs/product/reassortlot.php index 490986b155e..cf4e889e89e 100644 --- a/htdocs/product/reassortlot.php +++ b/htdocs/product/reassortlot.php @@ -28,6 +28,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; @@ -46,7 +47,7 @@ $sref=GETPOST("sref"); $snom=GETPOST("snom"); $sall=GETPOST('sall', 'alphanohtml'); $type=GETPOST("type","int"); -$sbarcode=GETPOST("sbarcode",'alpha'); +$search_barcode=GETPOST("search_barcode",'alpha'); $search_warehouse=GETPOST('search_warehouse','alpha'); $search_batch=GETPOST('search_batch','alpha'); $catid=GETPOST('catid','int'); @@ -115,7 +116,7 @@ $sql.= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desire $sql.= ' ps.fk_entrepot,'; $sql.= ' e.label as warehouse_ref, e.lieu as warehouse_lieu, e.fk_parent as warehouse_parent,'; $sql.= ' pb.batch, pb.eatby as oldeatby, pb.sellby as oldsellby,'; -$sql.= ' pl.eatby, pl.sellby,'; +$sql.= ' pl.rowid as lotid, pl.eatby, pl.sellby,'; $sql.= ' SUM(pb.qty) as stock_physique, COUNT(pb.rowid) as nbinbatchtable'; $sql.= ' FROM '.MAIN_DB_PREFIX.'product as p'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as ps on p.rowid = ps.fk_product'; // Detail for each warehouse @@ -140,7 +141,7 @@ if (dol_strlen($type)) } } if ($sref) $sql.= natural_search("p.ref", $sref); -if ($sbarcode) $sql.= natural_search("p.barcode", $sbarcode); +if ($search_barcode) $sql.= natural_search("p.barcode", $search_barcode); if ($snom) $sql.= natural_search("p.label", $snom); if (! empty($tosell)) $sql.= " AND p.tosell = ".$tosell; if (! empty($tobuy)) $sql.= " AND p.tobuy = ".$tobuy; @@ -157,7 +158,7 @@ $sql.= " p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p. $sql.= " ps.fk_entrepot,"; $sql.= " e.label, e.lieu, e.fk_parent,"; $sql.= " pb.batch, pb.eatby, pb.sellby,"; -$sql.= " pl.eatby, pl.sellby"; +$sql.= " pl.rowid, pl.eatby, pl.sellby"; if ($toolowstock) $sql.= " HAVING SUM(".$db->ifsql('ps.reel IS NULL', '0', 'ps.reel').") < p.seuil_stock_alerte"; // Not used yet $sql.= $db->order($sortfield,$sortorder); @@ -306,6 +307,7 @@ if ($resql) print "\n"; $product_static=new Product($db); + $product_lot_static=new Productlot($db); $warehousetmp=new Entrepot($db); while ($i < min($num,$limit)) @@ -336,6 +338,13 @@ if ($resql) $product_static->type=$objp->fk_product_type; $product_static->entity=$objp->entity; + $product_lot_static->batch=$objp->batch; + $product_lot_static->product_id=$objp->rowid; + $product_lot_static->id=$objp->lotid; + $product_lot_static->eatby=$objp->eatby; + $product_lot_static->sellby=$objp->sellby; + + $warehousetmp->id=$objp->fk_entrepot; $warehousetmp->ref=$objp->warehouse_ref; $warehousetmp->label=$objp->warehouse_ref; @@ -372,7 +381,15 @@ if ($resql) print $warehousetmp->getNomUrl(1); } print ''; - print ''; + + // Lot + print ''; + print ''; print ''; print ''; print "\n"; print '"; + print dol_print_date($db->jdate($objp->date_commande), 'dayhour').""; print '\n"; print '\n"; print ''; diff --git a/htdocs/product/stats/commande_fournisseur.php b/htdocs/product/stats/commande_fournisseur.php index daf2a9c3654..4526af86f96 100644 --- a/htdocs/product/stats/commande_fournisseur.php +++ b/htdocs/product/stats/commande_fournisseur.php @@ -51,13 +51,13 @@ $hookmanager->initHooks(array ( $mesg = ''; -$sortfield = GETPOST("sortfield", 'alpha'); -$sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); -if ($page == - 1) { - $page = 0; -} -$offset = $conf->liste_limit * $page; +// Load variable for pagination +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) @@ -107,7 +107,7 @@ if ($id > 0 || ! empty($ref)) { print $hookmanager->resPrint; if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; @@ -236,7 +236,7 @@ if ($id > 0 || ! empty($ref)) { print ''; print "\n"; print '"; + print dol_print_date($db->jdate($objp->date_commande), 'dayhour') . ""; print '\n"; print '\n"; print ''; diff --git a/htdocs/product/stats/contrat.php b/htdocs/product/stats/contrat.php index f9eed565903..7882f251dbd 100644 --- a/htdocs/product/stats/contrat.php +++ b/htdocs/product/stats/contrat.php @@ -90,7 +90,7 @@ if ($id > 0 || ! empty($ref)) print $hookmanager->resPrint; if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; @@ -190,7 +190,7 @@ if ($id > 0 || ! empty($ref)) print ''; print "\n"; print ""; + print dol_print_date($db->jdate($objp->date_contrat), 'dayhour').""; //print "\n"; //print ''; diff --git a/htdocs/product/stats/facture.php b/htdocs/product/stats/facture.php index 8cdc0efd5c0..794d939bc6e 100644 --- a/htdocs/product/stats/facture.php +++ b/htdocs/product/stats/facture.php @@ -117,7 +117,7 @@ if ($id > 0 || ! empty($ref)) print $hookmanager->resPrint; if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; @@ -251,7 +251,7 @@ if ($id > 0 || ! empty($ref)) print ''; print "\n"; print '"; + print dol_print_date($db->jdate($objp->datef),'dayhour').""; print '\n"; print '\n"; print ''; diff --git a/htdocs/product/stats/facture_fournisseur.php b/htdocs/product/stats/facture_fournisseur.php index 586741496c2..2e6b8d19677 100644 --- a/htdocs/product/stats/facture_fournisseur.php +++ b/htdocs/product/stats/facture_fournisseur.php @@ -102,7 +102,7 @@ if ($id > 0 || ! empty($ref)) print $hookmanager->resPrint; if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; @@ -229,7 +229,7 @@ if ($id > 0 || ! empty($ref)) print ''; print "\n"; print '"; + print dol_print_date($db->jdate($objp->datef), 'dayhour') . ""; print '\n"; print '\n"; print ''; diff --git a/htdocs/product/stats/propal.php b/htdocs/product/stats/propal.php index a5801c422e0..3173a04ee55 100644 --- a/htdocs/product/stats/propal.php +++ b/htdocs/product/stats/propal.php @@ -48,11 +48,13 @@ $hookmanager->initHooks(array ('productstatspropal')); $mesg = ''; -$sortfield = GETPOST("sortfield", 'alpha'); -$sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); -if ($page == - 1) { $page = 0;} -$offset = $conf->liste_limit * $page; +// Load variable for pagination +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) $sortorder = "DESC"; @@ -100,7 +102,7 @@ if ($id > 0 || ! empty($ref)) print $hookmanager->resPrint; if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; @@ -230,7 +232,7 @@ if ($id > 0 || ! empty($ref)) $societestatic->fetch($objp->socid); print ''; print '"; + print dol_print_date($db->jdate($objp->datep), 'dayhour') . ""; print "\n"; print '' . "\n"; print ''; diff --git a/htdocs/product/stats/supplier_proposal.php b/htdocs/product/stats/supplier_proposal.php new file mode 100644 index 00000000000..07e8015d846 --- /dev/null +++ b/htdocs/product/stats/supplier_proposal.php @@ -0,0 +1,268 @@ + + * Copyright (C) 2004-2009 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/product/stats/supplier_proposal.php + * \ingroup product service propal + * \brief Page des stats des propals pour un produit + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/supplier_proposal/class/supplier_proposal.class.php'; +require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; + +$langs->load("products"); +$langs->load("companies"); + +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); + +// Security check +$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); +$fieldtype = (! empty($ref) ? 'ref' : 'rowid'); +$socid=''; +if (! empty($user->societe_id)) $socid=$user->societe_id; +$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array ('productstatspropal')); + +$mesg = ''; + +// Load variable for pagination +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortorder) $sortorder = "DESC"; +if (! $sortfield) $sortfield = "p.date_valid"; + +$search_month = GETPOST('search_month', 'aplha'); +$search_year = GETPOST('search_year', 'int'); + +if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','alpha')) { + $search_month = ''; + $search_year = ''; +} + +/* + * View + */ + +$propalstatic = new SupplierProposal($db); +$societestatic=new Societe($db); + +$form = new Form($db); +$formother = new FormOther($db); + +if ($id > 0 || ! empty($ref)) +{ + $product = new Product($db); + $result = $product->fetch($id, $ref); + + $object = $product; + + $parameters = array ('id' => $id); + $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + llxHeader("", "", $langs->trans("CardProduct" . $product->type)); + + if ($result > 0) + { + $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, -1, $picto); + + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + $linkback = ''.$langs->trans("BackToList").''; + + $shownav = 1; + if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; + + dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); + + print '
    '; + + print '
    '; + print '
    '.$langs->trans("Statistics").'
    '.$langs->trans("Total").''; print ''; print ''; print ''; print '
    '.$langs->trans("Categories").'
    '; @@ -246,6 +250,7 @@ if (! empty($conf->categorie->enabled) && ! empty($conf->global->CATEGORY_GRAPHS print $total; print '
    '; + print ''; } print '
    '; @@ -281,6 +286,7 @@ if ($result) if (isset($_GET["type"]) && $_GET["type"] == 0) $transRecordedType = $langs->trans("LastRecordedProducts",$max); if (isset($_GET["type"]) && $_GET["type"] == 1) $transRecordedType = $langs->trans("LastRecordedServices",$max); + print '
    '; print ''; $colnb=5; @@ -355,6 +361,7 @@ if ($result) $db->free($result); print "
    "; + print '
    '; print '
    '; } } diff --git a/htdocs/product/info.php b/htdocs/product/info.php index c8af676ed0a..1887e96df47 100644 --- a/htdocs/product/info.php +++ b/htdocs/product/info.php @@ -94,7 +94,7 @@ if ($id > 0 || $ref) dol_fiche_head($head, 'info', $titre, -1, $picto); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter=" fk_product_type = ".$object->type; $shownav = 1; diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index 8d3acdecbc1..4b5a74ed3dd 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -1,6 +1,5 @@ - * Copyright (C) ---Put here your own copyright and developer email--- * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,43 +16,14 @@ */ /** - * \file product/inventory/card.php + * \file htdocs/product/inventory/card.php * \ingroup inventory - * \brief This file is an example of a php page - * Put here some comments + * \brief Inventory card */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) - -// Load Dolibarr environment -$res=0; -// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"); -// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include(substr($tmp, 0, ($i+1))."/main.inc.php"); -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"); -// Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include("../main.inc.php"); -if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); -if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main.inc.php"); -if (! $res) die("Include of main fails"); - -include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'); -dol_include_once('/inventory/class/inventory.class.php'); +require '../../main.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +include_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php'; // Load traductions files requiredby by page $langs->loadLangs(array("inventory","other")); @@ -100,8 +70,6 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be inclu /* * ACTIONS - * - * Put here all code to do according to value of "action" parameter */ $parameters=array(); @@ -112,109 +80,12 @@ if (empty($reshook)) { $error=0; - if ($cancel) - { - if ($action != 'addlink') - { - $urltogo=$backtopage?$backtopage:dol_buildpath('/inventory/inventory_list.php',1); - header("Location: ".$urltogo); - exit; - } - if ($id > 0 || ! empty($ref)) $ret = $object->fetch($id,$ref); - $action=''; - } + $permissiontoadd = $user->rights->inventory->create; + $permissiontodelete = $user->rights->inventory->delete; + $backurlforlist = dol_buildpath('/inventory/inventory_list.php',1); - // Action to add record - if ($action == 'add' && ! empty($user->rights->inventory->create)) - { - foreach ($object->fields as $key => $val) - { - if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'import_key'))) continue; // Ignore special fields - - $object->$key=GETPOST($key,'alpha'); - if ($val['notnull'] && $object->$key == '') - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv($val['label'])), null, 'errors'); - } - } - - if (! $error) - { - $result=$object->createCommon($user); - if ($result > 0) - { - // Creation OK - $urltogo=$backtopage?$backtopage:dol_buildpath('/inventory/inventory_list.php',1); - header("Location: ".$urltogo); - exit; - } - else - { - // Creation KO - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); - $action='create'; - } - } - else - { - $action='create'; - } - } - - // Action to update record - if ($action == 'update' && ! empty($user->rights->inventory->create)) - { - foreach ($object->fields as $key => $val) - { - $object->$key=GETPOST($key,'alpha'); - if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'import_key'))) continue; - if ($val['notnull'] && $object->$key == '') - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv($val['label'])), null, 'errors'); - } - } - - if (! $error) - { - $result=$object->updateCommon($user); - if ($result > 0) - { - $action='view'; - } - else - { - // Creation KO - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); - $action='edit'; - } - } - else - { - $action='edit'; - } - } - - // Action to delete - if ($action == 'confirm_delete' && ! empty($user->rights->inventory->delete)) - { - $result=$object->deleteCommon($user); - if ($result > 0) - { - // Delete OK - setEventMessages("RecordDeleted", null, 'mesgs'); - header("Location: ".dol_buildpath('/inventory/inventory_list.php',1)); - exit; - } - else - { - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); - } - } + // Actions cancel, add, update or delete + include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; } @@ -222,8 +93,6 @@ if (empty($reshook)) /* * VIEW - * - * Put here all code to build page */ $form=new Form($db); @@ -249,7 +118,7 @@ jQuery(document).ready(function() { // Part to create if ($action == 'create') { - print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("Inventory"))); + print load_fiche_titre($langs->trans("NewInventory", $langs->transnoentitiesnoconv("MyInventory"))); print '
    '; print ''; @@ -261,18 +130,49 @@ if ($action == 'create') print ''."\n"; foreach($object->fields as $key => $val) { - if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'import_key'))) continue; - print ''; + print ''.$langs->trans($val['label']).''; + if ($val['notnull'] > 0) print ' fieldrequired'; + if ($val['type'] == 'text') print ' tdtop'; + print '"'; + print '>'; + print $langs->trans($val['label']); + print ''; + print ''; + print ''; } + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + print '
    '; + $defaultcss='minwidth100'; + if ($val['type'] == 'text') + { + print ''; + } + elseif (is_array($val['arrayofkeyval'])) + { + print $form->selectarray($key, $val['arrayofkeyval'], GETPOST($key, 'int')); + } + else + { + $cssforinput = empty($val['css'])?$defaultcss:$val['css']; + print ''; + } + print '
    '."\n"; dol_fiche_end(); - print '
     
    '; + print '
    '; + print ''; + print '  '; + print ''; // Cancel for create doe not post form + print '
    '; print '
    '; } @@ -292,8 +192,40 @@ if (($id || $ref) && $action == 'edit') dol_fiche_head(); print ''."\n"; - // print ''; - // LIST_OF_TD_LABEL_FIELDS_EDIT + foreach($object->fields as $key => $val) + { + if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'fk_user_modif', 'import_key'))) continue; + + print ''.$langs->trans($val['label']).''; + print ''; + print ''; + } + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + print '
    '.$langs->trans("Label").'
    '; + $defaultcss='minwidth100'; + if ($val['type'] == 'text') + { + print ''; + } + elseif (is_array($val['arrayofkeyval'])) + { + print $form->selectarray($key, $val['arrayofkeyval'], GETPOST($key, 'int')!=''?GETPOST($key, 'int'):$object->$key); + } + else + { + $cssforinput = empty($val['css'])?$defaultcss:$val['css']; + print ''; + } + print '
    '; dol_fiche_end(); @@ -307,6 +239,7 @@ if (($id || $ref) && $action == 'edit') + // Part to show record if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { @@ -470,7 +403,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Documents $comref = dol_sanitizeFileName($object->ref); $relativepath = $comref . '/' . $comref . '.pdf'; - $filedir = $conf->inventory->dir_output . '/' . $comref; + $filedir = $conf->product->dir_output . '/inventory/' . $comref; $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; $genallowed = $user->rights->inventory->read; $delallowed = $user->rights->inventory->create; @@ -487,132 +420,24 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // List of actions on element include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'order', $socid); + $somethingshown = $formactions->showactions($object, 'order', $socid, 1); print '
    '; } + //Select mail models is same action as presend /* - * Action presend - */ - /* - if ($action == 'presend') - { - $object->fetch_projet(); + if (GETPOST('modelselected')) $action = 'presend'; - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($conf->commande->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; + // Presend form + $modelmail='inventory'; + $defaulttopic='InformationMessage'; + $diroutput = $conf->product->dir_output.'/inventory'; + $trackid = 'stockinv'.$object->id; - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - - if (!empty($newlang)) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($newlang); - $outputlangs->load('commercial'); - } - - // Build document if it not exists - if (! $file || ! is_readable($file)) { - $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) { - dol_print_error($db, $object->error, $object->errors); - exit(); - } - $fileparams = dol_most_recent_file($conf->commande->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - } - - print '
    '; - print '
    '; - print '
    '; - print load_fiche_titre($langs->trans('SendOrderByMail')); - - dol_fiche_head(''); - - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - $formmail->trackid='ord'.$object->id; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'ord'.$object->id); - } - $formmail->withfrom = 1; - $liste = array(); - foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) - $liste [$key] = $value; - $formmail->withto = GETPOST('sendto') ? GETPOST('sendto') : $liste; - $formmail->withtocc = $liste; - $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; - if (empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->trans('SendOrderRef', '__ORDERREF__'); - } else if (! empty($object->ref_client)) { - $formmail->withtopic = $outputlangs->trans('SendOrderRef', '__ORDERREF__ (__REFCLIENT__)'); - } - $formmail->withfile = 2; - $formmail->withbody = 1; - $formmail->withdeliveryreceipt = 1; - $formmail->withcancel = 1; - // Tableau des substitutions - $formmail->setSubstitFromObject($object); - $formmail->substit ['__ORDERREF__'] = $object->ref; - - $custcontact = ''; - $contactarr = array(); - $contactarr = $object->liste_contact(- 1, 'external'); - - if (is_array($contactarr) && count($contactarr) > 0) - { - foreach ($contactarr as $contact) - { - if ($contact['libelle'] == $langs->trans('TypeContact_commande_external_CUSTOMER')) { // TODO Use code and not label - $contactstatic = new Contact($db); - $contactstatic->fetch($contact ['id']); - $custcontact = $contactstatic->getFullName($langs, 1); - } - } - - if (! empty($custcontact)) { - $formmail->substit['__CONTACTCIVNAME__'] = $custcontact; - } - } - - // Tableau des parametres complementaires - $formmail->param['action'] = 'send'; - $formmail->param['models'] = 'order_send'; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['orderid'] = $object->id; - $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; - - // Init list of files - if (GETPOST("mode") == 'init') { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file, basename($file), dol_mimetype($file)); - } - - // Show form - print $formmail->get_form(); - - dol_fiche_end(); - }*/ + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; + */ } diff --git a/htdocs/product/inventory/class/inventory.class.php b/htdocs/product/inventory/class/inventory.class.php index 3fc42f15f70..9b48c5164d4 100644 --- a/htdocs/product/inventory/class/inventory.class.php +++ b/htdocs/product/inventory/class/inventory.class.php @@ -44,14 +44,10 @@ class Inventory extends CommonObject */ public $table_element = 'inventory'; - /** - * @var array Does this field is linked to a thirdparty ? - */ - protected $isnolinkedbythird = 1; /** * @var array Does inventory support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe */ - protected $ismultientitymanaged = 1; + public $ismultientitymanaged = 1; /** * @var string String with name of icon for inventory */ @@ -77,16 +73,16 @@ class Inventory extends CommonObject 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',), 'ref' => array('type'=>'varchar(64)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>'Reference of object',), 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,), - 'fk_warehouse' => array('type'=>'integer', 'label'=>'', 'visible'=>1, 'enabled'=>1, 'index'=>1,), - 'date_inventory' => array('type'=>'date', 'label'=>'', 'visible'=>1, 'enabled'=>1,), - 'title' => array('type'=>'varchar(255)', 'label'=>'', 'visible'=>1, 'enabled'=>1,), + 'title' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>25, 'css'=>'minwidth300'), + 'fk_warehouse' => array('type'=>'integer', 'label'=>'Warehouse', 'visible'=>1, 'enabled'=>1, 'index'=>1,), + 'date_inventory' => array('type'=>'date', 'label'=>'DateValue', 'visible'=>1, 'enabled'=>1,), 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'index'=>1,), 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-1, 'enabled'=>1, 'position'=>500,), - 'date_validation' => array('type'=>'datetime', 'label'=>'DateValidation', 'visible'=>-1, 'enabled'=>1, 'position'=>500,), - 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), - 'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-1, 'enabled'=>1, 'position'=>500,), - 'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-1, 'enabled'=>1, 'position'=>500,), - 'fk_user_valid' => array('type'=>'integer', 'label'=>'UserValid', 'visible'=>-1, 'enabled'=>1, 'position'=>500,), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>501, 'notnull'=>1,), + 'date_validation' => array('type'=>'datetime', 'label'=>'DateValidation', 'visible'=>-1, 'enabled'=>1, 'position'=>502,), + 'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-1, 'enabled'=>1, 'position'=>510,), + 'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-1, 'enabled'=>1, 'position'=>511,), + 'fk_user_valid' => array('type'=>'integer', 'label'=>'UserValidation', 'visible'=>-1, 'enabled'=>1, 'position'=>512,), 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'index'=>1,), ); @@ -140,7 +136,12 @@ class Inventory extends CommonObject */ public function __construct(DoliDB $db) { + global $conf; + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; } diff --git a/htdocs/product/inventory/list.php b/htdocs/product/inventory/list.php index 0fea44f0f83..39be799db47 100644 --- a/htdocs/product/inventory/list.php +++ b/htdocs/product/inventory/list.php @@ -1,6 +1,5 @@ - * Copyright (C) ---Put here your own copyright and developer email--- * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,45 +16,16 @@ */ /** - * \file product/inventory/list.php + * \file htdocs/product/inventory/list.php * \ingroup inventory - * \brief List page for monmodule + * \brief List page for inventory */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) - - -// Load Dolibarr environment -$res=0; -// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"); -// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include(substr($tmp, 0, ($i+1))."/main.inc.php"); -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"); -// Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include("../main.inc.php"); -if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); -if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main.inc.php"); -if (! $res) die("Include of main fails"); - -require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'); +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -dol_include_once('/inventory/class/inventory.class.php'); +require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php'; // Load traductions files requiredby by page $langs->loadLangs(array("inventory","other")); @@ -69,7 +39,7 @@ $toselect = GETPOST('toselect', 'array'); $contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'inventorylist'; // To manage different context of search $id = GETPOST('id','int'); -$backtopage = GETPOST('backtopage'); +$backtopage = GETPOST('backtopage','alpha'); $optioncss = GETPOST('optioncss','alpha'); // Load variable for pagination @@ -130,7 +100,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -143,8 +113,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Put here all code to do according to value of "$action" parameter */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -177,7 +147,7 @@ if (empty($reshook)) $permtoread = $user->rights->inventory->read; $permtodelete = $user->rights->inventory->delete; $uploaddir = $conf->inventory->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + //include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // TODO to fix for product module } @@ -264,7 +234,7 @@ if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && { $obj = $db->fetch_object($resql); $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/inventory/inventory_card.php?id='.$id); + header("Location: ".DOL_URL_ROOT.'/inventory/card.php?id='.$id); exit; } @@ -363,7 +333,6 @@ print ''; foreach($object->fields as $key => $val) { - if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; $align=''; if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; @@ -396,15 +365,6 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab $parameters=array('arrayfields'=>$arrayfields); $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -// Rest of fields search -foreach($object->fields as $key => $val) -{ - if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; - if (! empty($arrayfields['t.'.$key]['checked'])) print ''; -} // Action column print ''."\n"; print ''; foreach($object->fields as $key => $val) { - if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; $align=''; if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; @@ -442,15 +401,6 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab $parameters=array('arrayfields'=>$arrayfields); $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -// Rest of fields title -foreach($object->fields as $key => $val) -{ - if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; - if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; - if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; -} print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; print ''."\n"; @@ -483,7 +433,6 @@ while ($i < min($num, $limit)) print ''; foreach($object->fields as $key => $val) { - if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; $align=''; if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; @@ -531,29 +480,6 @@ while ($i < min($num, $limit)) $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - // Rest of fields - foreach($object->fields as $key => $val) - { - if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) - { - print ''; - if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour'); - elseif ($key == 'status') print $object->getLibStatut(3); - else print $obj->$key; - print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) - { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; - $totalarray['val']['t.'.$key] += $obj->$key; - } - } - } // Action column print '
    '; $searchpicto=$form->showFilterButtons(); @@ -418,7 +378,6 @@ print '
    '; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined diff --git a/htdocs/product/inventory/tpl/inventory.tpl.php b/htdocs/product/inventory/tpl/inventory.tpl.php index 05de0f4c002..c09328c3363 100644 --- a/htdocs/product/inventory/tpl/inventory.tpl.php +++ b/htdocs/product/inventory/tpl/inventory.tpl.php @@ -1,12 +1,12 @@ @@ -76,37 +76,37 @@
    - + - +

    - +
    Cet inventaire est validé
    - + - + $row) { - + + foreach ($lines as $k=>$row) { + $total_pmp+=$row['pmp_stock']; $total_pa+=$row['pa_stock']; $total_pmp_actual+=$row['pmp_actual']; $total_pa_actual+=$row['pa_actual']; - + if($i%20 === 0) { _headerList($view); @@ -126,18 +126,18 @@ if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ echo ''; $total_current_pa+=$row['current_pa_stock']; - } - + } + ?> rights->stock->changePMP)) { - echo ''; + echo ''; } ?> @@ -145,8 +145,8 @@ if(!empty($conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA)){ echo ''; $total_current_pa_actual+=$row['current_pa_actual']; - } - + } + ?> @@ -154,25 +154,25 @@ -
    '.price($row['current_pa_stock']).'    - + '.$row['pmp_new'].''.$row['pmp_new'].''.price($row['current_pa_actual']).'
    - + status != 1) { ?>
    trans('Modify') ?> - rights->stock->changePMP)) { echo ''.$langs->trans('ApplyPMP').''; } - + if ($can_validate == 1) { ?> trans('RegulateStock') ?> @@ -193,13 +193,13 @@ trans('Delete') ?> - +

    Date de création : getDate('datec') ?> -
    Dernière mise à jour : getDate('tms') ?>

    - +
    Dernière mise à jour : getDate('tms') ?>

    + + - diff --git a/htdocs/product/list-with-listview.php b/htdocs/product/list-with-listview.php deleted file mode 100644 index 11cefe0bdbf..00000000000 --- a/htdocs/product/list-with-listview.php +++ /dev/null @@ -1,704 +0,0 @@ - - * Copyright (C) 2004-2016 Laurent Destailleur - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2012-2016 Marcos García - * Copyright (C) 2013-2016 Juanjo Menent - * Copyright (C) 2013-2015 Raphaël Doursenaud - * Copyright (C) 2013 Jean Heimburger - * Copyright (C) 2013 Cédric Salvador - * Copyright (C) 2013 Florian Henry - * Copyright (C) 2013 Adolfo segura - * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2016 Ferran Marcet - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/product/list.php - * \ingroup produit - * \brief Page to list products and services - */ - -require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT.'/product/inventory/listview.class.php'; -require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -if (! empty($conf->categorie->enabled)) - require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - -$langs->load("products"); -$langs->load("stocks"); -$langs->load("suppliers"); -$langs->load("companies"); -if (! empty($conf->productbatch->enabled)) $langs->load("productbatch"); - -$action=GETPOST('action','alpha'); -$massaction=GETPOST('massaction','alpha'); -$show_files=GETPOST('show_files','int'); -$confirm=GETPOST('confirm','alpha'); -$toselect = GETPOST('toselect', 'array'); - -$sref=GETPOST("sref"); -$sbarcode=GETPOST("sbarcode"); -$snom=GETPOST("snom"); -$sall=GETPOST("sall"); -$type= (int) GETPOST("type","int"); -$search_sale = GETPOST("search_sale"); -$search_categ = GETPOST("search_categ",'int'); -$tosell = GETPOST("tosell", 'int'); -$tobuy = GETPOST("tobuy", 'int'); -$fourn_id = GETPOST("fourn_id",'int'); -$catid = GETPOST('catid','int'); -$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'); - -//Show/hide child products. Hidden by default -if (!$_POST) { - $search_hidechildproducts = 'on'; -} else { - $search_hidechildproducts = GETPOST('search_hidechildproducts'); -} - -$diroutputmassaction=$conf->product->dir_output . '/temp/massgeneration/'.$user->id; - -$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); -$page = (GETPOST("page",'int')?GETPOST("page", 'int'):0); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 -$offset = $limit * $page; -$pageprev = $page - 1; -$pagenext = $page + 1; -if (! $sortfield) $sortfield="p.ref"; -if (! $sortorder) $sortorder="ASC"; - -// Initialize context for list -$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'productservicelist'; -if ((string) $type == '1') { $contextpage='servicelist'; if ($search_type=='') $search_type='1'; } -if ((string) $type == '0') { $contextpage='productlist'; if ($search_type=='') $search_type='0'; } - -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array($contextpage)); -$extrafields = new ExtraFields($db); -$form=new Form($db); - -// fetch optionals attributes and labels -$extralabels = $extrafields->fetch_name_optionals_label('product'); -$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); - -if (empty($action)) $action='list'; - -// Get object canvas (By default, this is not defined, so standard usage of dolibarr) -$canvas=GETPOST("canvas"); -$objcanvas=null; -if (! empty($canvas)) -{ - require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; - $objcanvas = new Canvas($db,$action); - $objcanvas->getCanvas('product','list',$canvas); -} - -// Security check -if ($type=='0') $result=restrictedArea($user,'produit','','','','','',$objcanvas); -else if ($type=='1') $result=restrictedArea($user,'service','','','','','',$objcanvas); -else $result=restrictedArea($user,'produit|service','','','','','',$objcanvas); - -// Define virtualdiffersfromphysical -$virtualdiffersfromphysical=0; -if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) -{ - $virtualdiffersfromphysical=1; // According to increase/decrease stock options, virtual and physical stock may differs. -} - -// List of fields to search into when doing a "search in all" -$fieldstosearchall = array( - 'p.ref'=>"Ref", - 'pfp.ref_fourn'=>"RefSupplier", - 'p.label'=>"ProductLabel", - 'p.description'=>"Description", - "p.note"=>"Note", -); -// multilang -if (! empty($conf->global->MAIN_MULTILANGS)) -{ - $fieldstosearchall['pl.label']='ProductLabelTranslated'; - $fieldstosearchall['pl.description']='ProductDescriptionTranslated'; - $fieldstosearchall['pl.note']='ProductNoteTranslated'; -} -if (! empty($conf->barcode->enabled)) { - $fieldstosearchall['p.barcode']='Gencod'; -} - -if (empty($conf->global->PRODUIT_MULTIPRICES)) -{ - $titlesellprice=$langs->trans("SellingPrice"); - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) - { - $titlesellprice=$form->textwithpicto($langs->trans("SellingPrice"), $langs->trans("DefaultPriceRealPriceMayDependOnCustomer")); - } -} - -// Definition of fields for lists -$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.duration'=>array('label'=>$langs->trans("Duration"), 'checked'=>($contextpage != 'productlist'), 'enabled'=>(! empty($conf->service->enabled))), - 'p.price'=>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))), - 'p.seuil_stock_alerte'=>array('label'=>$langs->trans("StockLimit"), 'checked'=>0, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical)), - 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(! empty($conf->productbatch->enabled))), - 'p.accountancy_code_sell'=>array('label'=>$langs->trans("ProductAccountancySellCode"), 'checked'=>0), - 'p.accountancy_code_buy'=>array('label'=>$langs->trans("ProductAccountancyBuyCode"), 'checked'=>0), - 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'p.tosell'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Sell").')', 'checked'=>1, 'position'=>1000), - 'p.tobuy'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Buy").')', 'checked'=>1, 'position'=>1000) -); -// Extra fields -if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) -{ - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key]); - } -} - - - -/* - * Actions - */ - -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } - -$parameters=array(); -$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)) -{ - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $sall=""; - $sref=""; - $snom=""; - $sbarcode=""; - $search_categ=0; - $tosell=""; - $tobuy=""; - $search_tobatch=''; - $search_accountancy_code_sell=''; - $search_accountancy_code_buy=''; - $search_array_options=array(); - } - - // Mass actions - $objectclass='Product'; - if ((string) $type == '1') { $objectlabel='Services'; } - if ((string) $type == '0') { $objectlabel='Products'; } - - $permtoread = $user->rights->produit->lire; - $permtodelete = $user->rights->produit->supprimer; - $uploaddir = $conf->product->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; -} - - -/* - * View - */ - -$htmlother=new FormOther($db); - -if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) -{ - $objcanvas->assign_values($action); // This must contains code to load data (must call LoadListDatas($limit, $offset, $sortfield, $sortorder)) - $objcanvas->display_canvas($action); // This is code to show template -} -else -{ - $title=$langs->trans("ProductsAndServices"); - - if (isset($type)) - { - if ($type==1) - { - $texte = $langs->trans("Services"); - } - else - { - $texte = $langs->trans("Products"); - } - } - 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.= ' 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, p.tms,'; - //$sql.= ' pfp.ref_fourn as ref_supplier, '; - $sql.= ' MIN(pfp.unitprice) as minsellprice'; - if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($type === 0)) { - $sql .= ', pac.rowid prod_comb_id'; - } - // Add fields from extrafields - foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : ''); - // Add fields from hooks - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook - $sql.=$hookmanager->resPrint; - $sql.= ' FROM '.MAIN_DB_PREFIX.'product as p'; - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields as ef on (p.rowid = ef.fk_object)"; - if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; // We'll need this table joined to the select in order to filter by categ - $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)) { - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid"; - } - - $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; - 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 ($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); - if ($sbarcode) $sql .= natural_search('p.barcode', $sbarcode); - if (isset($tosell) && dol_strlen($tosell) > 0 && $tosell!=-1) $sql.= " AND p.tosell = ".$db->escape($tosell); - if (isset($tobuy) && dol_strlen($tobuy) > 0 && $tobuy!=-1) $sql.= " AND p.tobuy = ".$db->escape($tobuy); - if (dol_strlen($canvas) > 0) $sql.= " AND p.canvas = '".$db->escape($canvas)."'"; - if ($catid > 0) $sql.= " AND cp.fk_categorie = ".$catid; - if ($catid == -2) $sql.= " AND cp.fk_categorie IS NULL"; - if ($search_categ > 0) $sql.= " AND cp.fk_categorie = ".$db->escape($search_categ); - if ($search_categ == -2) $sql.= " AND cp.fk_categorie IS NULL"; - if ($fourn_id > 0) $sql.= " AND pfp.fk_soc = ".$fourn_id; - if ($search_tobatch != '' && $search_tobatch >= 0) $sql.= " AND p.tobatch = ".$db->escape($search_tobatch); - if ($search_accountancy_code_sell) $sql.= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); - 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)) { - $sql .= " AND pac.rowid IS NULL"; - } - - // Add where from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } - } - // Add where from hooks - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook - $sql.=$hookmanager->resPrint; - $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)) { - $sql .= ', pac.rowid'; - } - // Add fields from extrafields - foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); - // Add fields from hooks - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldSelect',$parameters); // Note that $action and $object may have been modified by hook - $sql.=$hookmanager->resPrint; - - // TODO put these functions into product.lib.php if this go from demo to core - /** - * Function return formated sell price - * - * @param int $fk_object rowid of product - * @return string - */ - function list_get_product_sellprice($fk_object) { - global $langs,$conf, $user; - - $object = Listview::getCachedOjbect('Product', $fk_object); - if($object === false) return ''; - - if ($object->status) - { - if ($object->price_base_type == 'TTC') return price($object->price_ttc).' '.$langs->trans("TTC"); - else return price($object->price).' '.$langs->trans("HT"); - } - return ''; - } - - /** - * Function return formated product status sell or buy - * - * @param int $fk_object rowid of product - * @param string $field concerned field status|status_buy - * @param int $type for libstatus - * @return string - */ - function list_get_product_status($fk_object, $field, $type) { - global $conf, $user; - - $object = Listview::getCachedOjbect('Product', $fk_object); - - if($object === false) return ''; - - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - return ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); - } else { - return $object->LibStatut($object->{$field},5,$type); - } - - } - - /** - * Function return formated ref - * - * @param int $fk_object rowid of product - * @return string - */ - function list_get_product_ref($fk_object) { - global $conf, $user; - - $object = Listview::getCachedOjbect('Product', $fk_object); - - if($object === false) return ''; - - return $object->getNomUrl(1,'',24); - } - - /** - * Function return formated extrafield - * - * @param int $fk_object rowid of product - * @param string $key extrafield to output - * @return string - */ - function list_get_product_extrafield($fk_object, $key) { - global $extrafields; - - $object = Listview::getCachedOjbect('Product', $fk_object); - if($object === false) return ''; - - return $extrafields->showOutputField($key, $object->array_options['options_'.$key], '', 1); - } - - /** - * Function return formated virtual stock - * - * @param int $fk_object rowid of product - * @return string - */ - function list_get_product_virtual_stock($fk_object) { - global $langs; - - $object = Listview::getCachedOjbect('Product', $fk_object); - if($object === false) return ''; - - $object->load_stock('nobatch'); - - $out = ''; - if ($object->type != 1) - { - if ($object->seuil_stock_alerte != '' && $object->stock_theorique < (float) $object->seuil_stock_alerte) $out.= img_warning($langs->trans("StockTooLow")).' '; - $out.= (double) $object->stock_theorique; - } - - return $out; - } - - /** - * Function return formated stock - * - * @param int $fk_object rowid of product - * @return string - */ - function list_get_product_stock($fk_object) { - global $langs; - - $object = Listview::getCachedOjbect('Product', $fk_object); - if($object === false) return ''; - - $out = ''; - if ($object->type != 1) - { - if ($object->seuil_stock_alerte != '' && $object->stock_reel< (float) $object->seuil_stock_alerte) $out.= img_warning($langs->trans("StockTooLow")).' '; - $out.= (double) $object->stock_reel; - } - - return $out; - } - /** - * Function return formated min buy price - * - * @param int $fk_object rowid of product - * @return string - */ - function list_get_product_minbuyprice($fk_object) { - global $conf, $user, $langs,$db,$form; - - $out = ''; - - $object = Listview::getCachedOjbect('Product', $fk_object); - if($object === false || empty($object->status_buy) ) return ''; - - $product_fourn =new ProductFournisseur($db); - if ($product_fourn->find_min_price_product_fournisseur($fk_object) > 0) - { - if ($product_fourn->product_fourn_price_id > 0) - { - if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) - { - $htmltext=$product_fourn->display_price_product_fournisseur(1, 1, 0, 1); - $out.= $form->textwithpicto(price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"),$htmltext); - } - else $out.= price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"); - } - } - return $out; - } - - // array of customized field function - $arrayeval = array( - 'tobuy'=>'list_get_product_status(@rowid@, "status_buy",1)' - ,'tosell'=>'list_get_product_status(@rowid@, "status",0)' - ,'ref'=>'list_get_product_ref(@rowid@)' - ,'label'=>'dol_trunc("@val@",40)' - ,'price'=>'list_get_product_sellprice(@rowid@)' - ,'stock_virtual'=>'list_get_product_virtual_stock(@rowid@)' - ,'stock'=>'list_get_product_stock(@rowid@)' - ,'minbuyprice'=>'list_get_product_minbuyprice(@rowid@)' - ); - - // defined list align for field - $arrayalign = array( - 'price'=>'right' - ,'tobuy'=>'right' - ,'tosell'=>'right' - ,'desiredstock'=>'right' - ,'stock'=>'right' - ,'stock_virtual'=>'right' - ,'minbuyprice'=>'right' - ,'datec'=>'center' - ,'tms'=>'center' - ); - - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListMoreFields',$parameters); // Note that $action and $object may have been modified by hook - if($reshook) { - $arrayfields = $hookmanager->resArray; - } - - // init title, hidden field (allowed into selected fields), and position - $arrayhide = $arraytitle = $arrayposition = array(); - foreach($arrayfields as $k=>$data) { - if(!isset($data['enabled']) || $data['enabled']) { - list($t,$f) = explode('.',$k); - if(empty($f))$f = $k; - $arraytitle[$f]=$data['label']; - if(empty($data['checked'])) $arrayhide[] = $f; - $arrayposition[$f] = empty($data['position']) ? 0 : $data['position']; - } - } - - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayalign[$key]=$extrafields->getAlignFlag($key); - $arrayeval[$key] = 'list_get_product_extrafield(@rowid@, "'.$key.'")'; - } - } - // List of mass actions available - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), - ); - if ($user->rights->produit->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); - - // Filter on categories - $moreforfilter=''; - if (! empty($conf->categorie->enabled)) - { - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('Categories'). ': '; - $moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT,$search_categ,'search_categ',1); - $moreforfilter.='
    '; - } - - //Show/hide child products. Hidden by default - if (!empty($conf->variants->enabled) && $type === 0) { - $moreforfilter.='
    '; - $moreforfilter.= ''; - $moreforfilter.= ' '; - $moreforfilter.='
    '; - } - - if ($moreforfilter) - { - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - - if(!empty($hookmanager->resPrint)) { - $moreforfilter.=$hookmanager->resPrint; - } - - } - - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($search_categ > 0) $param.="&search_categ=".urlencode($search_categ); - if ($sref) $param="&sref=".urlencode($sref); - if ($search_ref_supplier) $param="&search_ref_supplier=".urlencode($search_ref_supplier); - if ($sbarcode) $param.=($sbarcode?"&sbarcode=".urlencode($sbarcode):""); - if ($snom) $param.="&snom=".urlencode($snom); - if ($sall) $param.="&sall=".urlencode($sall); - if ($tosell != '') $param.="&tosell=".urlencode($tosell); - if ($tobuy != '') $param.="&tobuy=".urlencode($tobuy); - 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_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); - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - //var_dump($arraytitle,$arrayhide); - $list=new Listview($db, 'product'); - $listHTML = $list->render($sql,array( - 'list'=>array( - 'title'=>$texte - ,'image'=>'title_products.png' - ,'massactions'=>$arrayofmassactions - ,'param_url'=>$param - ,'messageNothing'=>'' - ) - ,'limit'=>array( - 'nbLine'=>$limit - ) - ,'sortfield'=>$sortfield - ,'sortorder'=>$sortorder - ,'title'=>$arraytitle // column definition title (only defined where abble to show) - ,'position'=>array( - 'text-align'=>$arrayalign - ,'rank'=>$arrayposition - ) - ,'allow-fields-select'=>1 // allow to select hidden fields - ,'head_search'=>$moreforfilter //custom search on head - ,'no-auto-sql-search'=>1 //disabled auto completion sql for search and pager url, use dolibarr style for migration of product list - ,'translate'=>array() - ,'search'=>array( - 'ref'=>array('search_type'=>true, 'table'=>'p', 'fieldname'=>'sref') - ,'label'=>array('search_type'=>true, 'table'=>'p', 'fieldname'=>'snom') - ,'tosell'=>array('search_type'=> array('0'=>$langs->trans('ProductStatusNotOnSellShort'),'1'=>$langs->trans('ProductStatusOnSellShort')), 'fieldname'=>'tosell') - ,'tobuy'=>array('search_type'=> array('0'=>$langs->trans('ProductStatusNotOnBuyShort'),'1'=>$langs->trans('ProductStatusOnBuyShort')), 'fieldname'=>'tobuy') - ,'barcode'=>array('search_type'=>true, 'table'=>'p', 'fieldname'=>'sbarcode') - ,'accountancy_code_sell'=>array('search_type'=>true, 'table'=>'p', 'fieldname'=>'search_accountancy_code_sell') - ,'accountancy_code_buy'=>array('search_type'=>true, 'table'=>'p', 'fieldname'=>'search_accountancy_code_buy') - ) - ,'type'=>array( - 'datec'=>'datetime' - ,'tms'=>'datetime' - ) - ,'hide'=>$arrayhide - ,'eval'=>$arrayeval - )); - - $num = $list->totalRow; - - $arrayofselected=is_array($toselect)?$toselect:array(); - - if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { - $id = $list->TField[0]->rowid; - header("Location: ".DOL_URL_ROOT.'/product/card.php?id='.$id); - exit; - } - - $helpurl=''; - if (isset($type)) - { - if ($type == 0) - { - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; - } - else if ($type == 1) - { - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; - } - } - - llxHeader('',$title,$helpurl,''); - - // Displays product removal confirmation - if (GETPOST('delprod')) { - setEventMessages($langs->trans("ProductDeleted", GETPOST('delprod')), null, 'mesgs'); - } - - print '
    '; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - echo $listHTML; - - print '
    '; - -} - - -llxFooter(); -$db->close(); diff --git a/htdocs/product/list.php b/htdocs/product/list.php index 5561d5778f6..837f7f291e3 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -52,21 +52,21 @@ $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); $sall=GETPOST('sall', 'alphanohtml'); -$sref=GETPOST("sref"); -$sbarcode=GETPOST("sbarcode"); -$snom=GETPOST("snom"); +$search_ref=GETPOST("search_ref"); +$search_barcode=GETPOST("search_barcode"); +$search_label=GETPOST("search_label"); $search_type = GETPOST("search_type",'int'); $search_sale = GETPOST("search_sale"); $search_categ = GETPOST("search_categ",'int'); -$tosell = GETPOST("tosell", 'int'); -$tobuy = GETPOST("tobuy", 'int'); +$search_tosell = GETPOST("search_tosell", 'int'); +$search_tobuy = GETPOST("search_tobuy", 'int'); $fourn_id = GETPOST("fourn_id",'int'); $catid = GETPOST('catid','int'); $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=GETPOST("type","int"); //Show/hide child products. Hidden by default if (!$_POST) { @@ -109,9 +109,9 @@ $canvas=GETPOST("canvas"); $objcanvas=null; if (! empty($canvas)) { - require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; - $objcanvas = new Canvas($db,$action); - $objcanvas->getCanvas('product','list',$canvas); + require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; + $objcanvas = new Canvas($db,$action); + $objcanvas->getCanvas('product','list',$canvas); } // Security check @@ -123,16 +123,16 @@ else $result=restrictedArea($user,'produit|service','','','','','',$objcanvas); $virtualdiffersfromphysical=0; if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { - $virtualdiffersfromphysical=1; // According to increase/decrease stock options, virtual and physical stock may differs. + $virtualdiffersfromphysical=1; // According to increase/decrease stock options, virtual and physical stock may differs. } // List of fields to search into when doing a "search in all" $fieldstosearchall = array( 'p.ref'=>"Ref", - 'pfp.ref_fourn'=>"RefSupplier", + 'pfp.ref_fourn'=>"RefSupplier", 'p.label'=>"ProductLabel", 'p.description'=>"Description", - "p.note"=>"Note", + "p.note"=>"Note", ); // multilang if (! empty($conf->global->MAIN_MULTILANGS)) @@ -156,34 +156,34 @@ if (empty($conf->global->PRODUIT_MULTIPRICES)) // Definition of fields for lists $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.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.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.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))), + 'p.minbuyprice'=>array('label'=>$langs->trans("BuyingPriceMinShort"), 'checked'=>1, 'enabled'=>(! empty($user->rights->fournisseur->lire))), 'p.numbuyprice'=>array('label'=>$langs->trans("BuyingPriceNumShort"), 'checked'=>0, 'enabled'=>(! empty($user->rights->fournisseur->lire))), 'p.pmp'=>array('label'=>$langs->trans("PMPValueShort"), 'checked'=>0, 'enabled'=>(! empty($user->rights->fournisseur->lire))), 'p.seuil_stock_alerte'=>array('label'=>$langs->trans("StockLimit"), 'checked'=>0, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical)), - 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(! empty($conf->productbatch->enabled))), + 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), + 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), + 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical)), + 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(! empty($conf->productbatch->enabled))), 'p.accountancy_code_sell'=>array('label'=>$langs->trans("ProductAccountancySellCode"), 'checked'=>0), 'p.accountancy_code_buy'=>array('label'=>$langs->trans("ProductAccountancyBuyCode"), 'checked'=>0), 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'p.tosell'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Sell").')', 'checked'=>1, 'position'=>1000), - 'p.tobuy'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Buy").')', 'checked'=>1, 'position'=>1000) + 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'p.tosell'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Sell").')', 'checked'=>1, 'position'=>1000), + 'p.tobuy'=>array('label'=>$langs->trans("Status").' ('.$langs->trans("Buy").')', 'checked'=>1, 'position'=>1000) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -193,8 +193,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters, $object, $action); // Note that $action and $object may have been modified by some hooks @@ -202,35 +202,35 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $sall=""; - $sref=""; - $snom=""; - $sbarcode=""; - $search_categ=0; - $tosell=""; - $tobuy=""; - $search_tobatch=''; - $search_type=''; - $search_accountancy_code_sell=''; - $search_accountancy_code_buy=''; - $search_array_options=array(); - } + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $sall=""; + $search_ref=""; + $search_label=""; + $search_barcode=""; + $search_categ=0; + $search_tosell=""; + $search_tobuy=""; + $search_tobatch=''; + $search_type=''; + $search_accountancy_code_sell=''; + $search_accountancy_code_buy=''; + $search_array_options=array(); + } - // Mass actions - $objectclass='Product'; - if ((string) $search_type == '1') { $objectlabel='Services'; } - if ((string) $search_type == '0') { $objectlabel='Products'; } + // Mass actions + $objectclass='Product'; + if ((string) $search_type == '1') { $objectlabel='Services'; } + if ((string) $search_type == '0') { $objectlabel='Products'; } - $permtoread = $user->rights->produit->lire; - $permtodelete = $user->rights->produit->supprimer; - $uploaddir = $conf->product->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + $permtoread = $user->rights->produit->lire; + $permtodelete = $user->rights->produit->supprimer; + $uploaddir = $conf->product->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -243,7 +243,7 @@ $htmlother=new FormOther($db); if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { $objcanvas->assign_values($action); // This must contains code to load data (must call LoadListDatas($limit, $offset, $sortfield, $sortorder)) - $objcanvas->display_canvas($action); // This is code to show template + $objcanvas->display_canvas($action); // This is code to show template } else { @@ -265,24 +265,24 @@ else $texte = $langs->trans("ProductsAndServices"); } - $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, p.pmp,'; - //$sql.= ' pfp.ref_fourn as ref_supplier, '; - $sql.= ' MIN(pfp.unitprice) as minsellprice'; + $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, p.pmp,'; + //$sql.= ' pfp.ref_fourn as ref_supplier, '; + $sql.= ' MIN(pfp.unitprice) as minsellprice'; if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= ', pac.rowid prod_comb_id'; } // Add fields from extrafields - foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : ''); // Add fields from hooks $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; - $sql.= ' FROM '.MAIN_DB_PREFIX.'product as p'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'product as p'; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields as ef on (p.rowid = ef.fk_object)"; - if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; // We'll need this table joined to the select in order to filter by categ + if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; // We'll need this table joined to the select in order to filter by categ $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() ."'"; @@ -292,27 +292,27 @@ else $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; 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($search_type) && $search_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); - if ($sbarcode) $sql .= natural_search('p.barcode', $sbarcode); - if (isset($tosell) && dol_strlen($tosell) > 0 && $tosell!=-1) $sql.= " AND p.tosell = ".$db->escape($tosell); - if (isset($tobuy) && dol_strlen($tobuy) > 0 && $tobuy!=-1) $sql.= " AND p.tobuy = ".$db->escape($tobuy); - if (dol_strlen($canvas) > 0) $sql.= " AND p.canvas = '".$db->escape($canvas)."'"; - if ($catid > 0) $sql.= " AND cp.fk_categorie = ".$catid; - if ($catid == -2) $sql.= " AND cp.fk_categorie IS NULL"; - if ($search_categ > 0) $sql.= " AND cp.fk_categorie = ".$db->escape($search_categ); - if ($search_categ == -2) $sql.= " AND cp.fk_categorie IS NULL"; - if ($fourn_id > 0) $sql.= " AND pfp.fk_soc = ".$fourn_id; - if ($search_tobatch != '' && $search_tobatch >= 0) $sql.= " AND p.tobatch = ".$db->escape($search_tobatch); - if ($search_accountancy_code_sell) $sql.= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); - if ($search_accountancy_code_buy) $sql.= natural_search('p.accountancy_code_buy', $search_accountancy_code_buy); - // Add where from extra fields + // if the type is not 1, we show all products (type = 0,2,3) + if (dol_strlen($search_type) && $search_type != '-1') + { + if ($search_type == 1) $sql.= " AND p.fk_product_type = 1"; + else $sql.= " AND p.fk_product_type <> 1"; + } + if ($search_ref) $sql .= natural_search('p.ref', $search_ref); + if ($search_label) $sql .= natural_search('p.label', $search_label); + if ($search_barcode) $sql .= natural_search('p.barcode', $search_barcode); + if (isset($search_tosell) && dol_strlen($search_tosell) > 0 && $search_tosell!=-1) $sql.= " AND p.tosell = ".$db->escape($search_tosell); + if (isset($search_tobuy) && dol_strlen($search_tobuy) > 0 && $search_tobuy!=-1) $sql.= " AND p.tobuy = ".$db->escape($search_tobuy); + if (dol_strlen($canvas) > 0) $sql.= " AND p.canvas = '".$db->escape($canvas)."'"; + if ($catid > 0) $sql.= " AND cp.fk_categorie = ".$catid; + if ($catid == -2) $sql.= " AND cp.fk_categorie IS NULL"; + if ($search_categ > 0) $sql.= " AND cp.fk_categorie = ".$db->escape($search_categ); + if ($search_categ == -2) $sql.= " AND cp.fk_categorie IS NULL"; + if ($fourn_id > 0) $sql.= " AND pfp.fk_soc = ".$fourn_id; + if ($search_tobatch != '' && $search_tobatch >= 0) $sql.= " AND p.tobatch = ".$db->escape($search_tobatch); + if ($search_accountancy_code_sell) $sql.= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); + if ($search_accountancy_code_buy) $sql.= natural_search('p.accountancy_code_buy', $search_accountancy_code_buy); + // Add where from extra fields if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= " AND pac.rowid IS NULL"; @@ -321,171 +321,171 @@ else // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; - $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, p.pmp'; + $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, p.pmp'; if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= ', pac.rowid'; } // Add fields from extrafields - foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); + foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); // Add fields from hooks $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldSelect',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; - //if (GETPOST("toolowstock")) $sql.= " HAVING SUM(s.reel) < p.seuil_stock_alerte"; // Not used yet - $sql.= $db->order($sortfield,$sortorder); + //if (GETPOST("toolowstock")) $sql.= " HAVING SUM(s.reel) < p.seuil_stock_alerte"; // Not used yet + $sql.= $db->order($sortfield,$sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); } - $sql.= $db->plimit($limit + 1, $offset); + $sql.= $db->plimit($limit + 1, $offset); - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $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->rowid; - header("Location: ".DOL_URL_ROOT.'/product/card.php?id='.$id); - exit; - } + if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) + { + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/product/card.php?id='.$id); + exit; + } - $helpurl=''; - if ($search_type != '') - { - if ($search_type == 0) - { - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; - } - else if ($search_type == 1) - { - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; - } - } + $helpurl=''; + if ($search_type != '') + { + if ($search_type == 0) + { + $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + } + else if ($search_type == 1) + { + $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + } + } - llxHeader('',$title,$helpurl,''); + llxHeader('',$title,$helpurl,''); - // Displays product removal confirmation - if (GETPOST('delprod')) { - setEventMessages($langs->trans("ProductDeleted", GETPOST('delprod')), null, 'mesgs'); - } + // Displays product removal confirmation + if (GETPOST('delprod')) { + setEventMessages($langs->trans("ProductDeleted", GETPOST('delprod')), null, 'mesgs'); + } - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($search_categ > 0) $param.="&search_categ=".urlencode($search_categ); - if ($sref) $param="&sref=".urlencode($sref); - if ($search_ref_supplier) $param="&search_ref_supplier=".urlencode($search_ref_supplier); - if ($sbarcode) $param.=($sbarcode?"&sbarcode=".urlencode($sbarcode):""); - if ($snom) $param.="&snom=".urlencode($snom); - if ($sall) $param.="&sall=".urlencode($sall); - if ($tosell != '') $param.="&tosell=".urlencode($tosell); - if ($tobuy != '') $param.="&tobuy=".urlencode($tobuy); - 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 ($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); - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); + if ($sall) $param.="&sall=".urlencode($sall); + if ($search_categ > 0) $param.="&search_categ=".urlencode($search_categ); + if ($search_ref) $param="&search_ref=".urlencode($search_ref); + if ($search_ref_supplier) $param="&search_ref_supplier=".urlencode($search_ref_supplier); + if ($search_barcode) $param.=($search_barcode?"&search_barcode=".urlencode($search_barcode):""); + if ($search_label) $param.="&search_label=".urlencode($search_label); + if ($search_tosell != '') $param.="&search_tosell=".urlencode($search_tosell); + if ($search_tobuy != '') $param.="&search_tobuy=".urlencode($search_tobuy); + 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 ($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); + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } - // List of mass actions available - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), - ); - if ($user->rights->produit->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + // List of mass actions available + $arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), + ); + if ($user->rights->produit->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); print '
    '; - if ($optioncss != '') print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; print ''; print ''; - print ''; - print ''; - if (empty($arrayfields['p.fk_product_type']['checked'])) 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); + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_products.png', 0, '', '', $limit); - if (! empty($catid)) - { - print "
    "; - $c = new Categorie($db); - $ways = $c->print_all_ways(' > ','product/list.php'); - print " > ".$ways[0]."
    \n"; - print "

    "; - } + if (! empty($catid)) + { + print "
    "; + $c = new Categorie($db); + $ways = $c->print_all_ways(' > ','product/list.php'); + print " > ".$ways[0]."
    \n"; + print "

    "; + } - if (! empty($canvas) && file_exists(DOL_DOCUMENT_ROOT.'/product/canvas/'.$canvas.'/actions_card_'.$canvas.'.class.php')) - { - $fieldlist = $object->field_list; - $datas = $object->list_datas; - $picto='title.png'; - $title_picto = img_picto('',$picto); - $title_text = $title; + if (! empty($canvas) && file_exists(DOL_DOCUMENT_ROOT.'/product/canvas/'.$canvas.'/actions_card_'.$canvas.'.class.php')) + { + $fieldlist = $object->field_list; + $datas = $object->list_datas; + $picto='title.png'; + $title_picto = img_picto('',$picto); + $title_text = $title; - // Default templates directory - $template_dir = DOL_DOCUMENT_ROOT . '/product/canvas/'.$canvas.'/tpl/'; - // Check if a custom template is present - if (file_exists(DOL_DOCUMENT_ROOT . '/theme/'.$conf->theme.'/tpl/product/'.$canvas.'/list.tpl.php')) - { - $template_dir = DOL_DOCUMENT_ROOT . '/theme/'.$conf->theme.'/tpl/product/'.$canvas.'/'; - } + // Default templates directory + $template_dir = DOL_DOCUMENT_ROOT . '/product/canvas/'.$canvas.'/tpl/'; + // Check if a custom template is present + if (file_exists(DOL_DOCUMENT_ROOT . '/theme/'.$conf->theme.'/tpl/product/'.$canvas.'/list.tpl.php')) + { + $template_dir = DOL_DOCUMENT_ROOT . '/theme/'.$conf->theme.'/tpl/product/'.$canvas.'/'; + } - include $template_dir.'list.tpl.php'; // Include native PHP templates - } - else - { - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + include $template_dir.'list.tpl.php'; // Include native PHP templates + } + else + { + if ($sall) + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } - // Filter on categories - $moreforfilter=''; - if (! empty($conf->categorie->enabled)) - { - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('Categories'). ': '; - $moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT,$search_categ,'search_categ',1); - $moreforfilter.='
    '; - } + // Filter on categories + $moreforfilter=''; + if (! empty($conf->categorie->enabled)) + { + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('Categories'). ': '; + $moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT,$search_categ,'search_categ',1); + $moreforfilter.='
    '; + } //Show/hide child products. Hidden by default if (!empty($conf->variants->enabled) && $search_type === 0) { @@ -508,328 +508,347 @@ else } $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); + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
    '; - print ''."\n"; + print '
    '; + print '
    '."\n"; - // Lines with input filters - print ''; - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - } - if (! empty($arrayfields['pfp.ref_fourn']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.label']['checked'])) - { - print ''; - } - // Type - if (! empty($arrayfields['p.fk_product_type']['checked'])) - { - print ''; + if (! empty($arrayfields['p.ref']['checked'])) + { + print ''; + } + if (! empty($arrayfields['pfp.ref_fourn']['checked'])) + { + print ''; + } + if (! empty($arrayfields['p.label']['checked'])) + { + print ''; + } + // Type + if (! empty($arrayfields['p.fk_product_type']['checked'])) + { + print ''; - } - // Barcode - if (! empty($arrayfields['p.barcode']['checked'])) - { - print ''; - } - // Duration + print $form->selectarray('search_type', $array, $search_type); + print ''; + } + // Barcode + if (! empty($arrayfields['p.barcode']['checked'])) + { + print ''; + } + // Duration if (! empty($arrayfields['p.duration']['checked'])) - { - print ''; - } - // Sell price + { + print ''; + } + // Sell price if (! empty($arrayfields['p.sellprice']['checked'])) - { - print ''; - } - // Minimum buying Price + { + print ''; + } + // Minimum buying Price if (! empty($arrayfields['p.minbuyprice']['checked'])) - { - print ''; - } + { + print ''; + } // Number buying Price if (! empty($arrayfields['p.numbuyprice']['checked'])) - { - print ''; - } + { + print ''; + } // WAP if (! empty($arrayfields['p.pmp']['checked'])) - { - print ''; - } - // Limit for alert + { + print ''; + } + // Limit for alert if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) - { - print ''; - } - // Desired stock + { + print ''; + } + // Desired stock if (! empty($arrayfields['p.desiredstock']['checked'])) - { - print ''; - } - // Stock + { + print ''; + } + // Stock if (! empty($arrayfields['p.stock']['checked'])) print ''; - // Stock + // Stock if (! empty($arrayfields['stock_virtual']['checked'])) print ''; // To batch if (! empty($arrayfields['p.tobatch']['checked'])) print ''; // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) print ''; - // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) print ''; - // Extra fields + if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) print ''; + // Accountancy code sell + if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) print ''; + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) print ''; + if (! empty($arrayfields["ef.".$key]['checked'])) { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } } } - // Fields from hook + // Fields from hook $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['p.datec']['checked'])) - { - print ''; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.tosell']['checked'])) - { - print ''; - } + $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print ''; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print ''; + } + if (! empty($arrayfields['p.tosell']['checked'])) + { + print ''; + } if (! empty($arrayfields['p.tobuy']['checked'])) - { - print ''; - } - print ''; + { + print ''; + } + print ''; - print ''; + print ''; - print ''; - 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); - if (! empty($arrayfields['p.minbuyprice']['checked'])) print_liste_field_titre($arrayfields['p.minbuyprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.numbuyprice']['checked'])) print_liste_field_titre($arrayfields['p.numbuyprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.pmp']['checked'])) print_liste_field_titre($arrayfields['p.pmp']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) print_liste_field_titre($arrayfields['p.seuil_stock_alerte']['label'], $_SERVER["PHP_SELF"],"p.seuil_stock_alerte","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.desiredstock']['checked'])) print_liste_field_titre($arrayfields['p.desiredstock']['label'], $_SERVER["PHP_SELF"],"p.desiredstock","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.stock']['checked'])) print_liste_field_titre($arrayfields['p.stock']['label'], $_SERVER["PHP_SELF"],"p.stock","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['stock_virtual']['checked'])) print_liste_field_titre($arrayfields['stock_virtual']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tobatch']['checked'])) print_liste_field_titre($arrayfields['p.tobatch']['label'], $_SERVER["PHP_SELF"],"p.tobatch","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) print_liste_field_titre($arrayfields['p.accountancy_code_sell']['label'], $_SERVER["PHP_SELF"],"p.accountancy_code_sell","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) print_liste_field_titre($arrayfields['p.accountancy_code_buy']['label'], $_SERVER["PHP_SELF"],"p.accountancy_code_buy","",$param,'',$sortfield,$sortorder); - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tosell']['checked'])) print_liste_field_titre($arrayfields['p.tosell']['label'],$_SERVER["PHP_SELF"],"p.tosell","",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tobuy']['checked'])) print_liste_field_titre($arrayfields['p.tobuy']['label'],$_SERVER["PHP_SELF"],"p.tobuy","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; + print ''; + 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); + if (! empty($arrayfields['p.minbuyprice']['checked'])) print_liste_field_titre($arrayfields['p.minbuyprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.numbuyprice']['checked'])) print_liste_field_titre($arrayfields['p.numbuyprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.pmp']['checked'])) print_liste_field_titre($arrayfields['p.pmp']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) print_liste_field_titre($arrayfields['p.seuil_stock_alerte']['label'], $_SERVER["PHP_SELF"],"p.seuil_stock_alerte","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.desiredstock']['checked'])) print_liste_field_titre($arrayfields['p.desiredstock']['label'], $_SERVER["PHP_SELF"],"p.desiredstock","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.stock']['checked'])) print_liste_field_titre($arrayfields['p.stock']['label'], $_SERVER["PHP_SELF"],"p.stock","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['stock_virtual']['checked'])) print_liste_field_titre($arrayfields['stock_virtual']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.tobatch']['checked'])) print_liste_field_titre($arrayfields['p.tobatch']['label'], $_SERVER["PHP_SELF"],"p.tobatch","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) print_liste_field_titre($arrayfields['p.accountancy_code_sell']['label'], $_SERVER["PHP_SELF"],"p.accountancy_code_sell","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) print_liste_field_titre($arrayfields['p.accountancy_code_buy']['label'], $_SERVER["PHP_SELF"],"p.accountancy_code_buy","",$param,'',$sortfield,$sortorder); + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } + } + // Hook fields + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['p.tosell']['checked'])) print_liste_field_titre($arrayfields['p.tosell']['label'],$_SERVER["PHP_SELF"],"p.tosell","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['p.tobuy']['checked'])) print_liste_field_titre($arrayfields['p.tobuy']['label'],$_SERVER["PHP_SELF"],"p.tobuy","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); + print "\n"; - $product_static=new Product($db); - $product_fourn =new ProductFournisseur($db); + $product_static=new Product($db); + $product_fourn =new ProductFournisseur($db); - $i = 0; - $totalarray=array(); - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); + $i = 0; + $totalarray=array(); + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); - // Multilangs - if (! empty($conf->global->MAIN_MULTILANGS)) // si l'option est active - { - $sql = "SELECT label"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$obj->rowid; - $sql.= " AND lang='". $langs->getDefaultLang() ."'"; - $sql.= " LIMIT 1"; + // Multilangs + if (! empty($conf->global->MAIN_MULTILANGS)) // si l'option est active + { + $sql = "SELECT label"; + $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql.= " WHERE fk_product=".$obj->rowid; + $sql.= " AND lang='". $langs->getDefaultLang() ."'"; + $sql.= " LIMIT 1"; - $result = $db->query($sql); - if ($result) - { - $objtp = $db->fetch_object($result); - if (! empty($objtp->label)) $obj->label = $objtp->label; - } - } + $result = $db->query($sql); + if ($result) + { + $objtp = $db->fetch_object($result); + if (! empty($objtp->label)) $obj->label = $objtp->label; + } + } - $product_static->id = $obj->rowid; - $product_static->ref = $obj->ref; - $product_static->ref_fourn = $obj->ref_supplier; - $product_static->label = $obj->label; - $product_static->type = $obj->fk_product_type; - $product_static->status_buy = $obj->tobuy; - $product_static->status = $obj->tosell; + $product_static->id = $obj->rowid; + $product_static->ref = $obj->ref; + $product_static->ref_fourn = $obj->ref_supplier; + $product_static->label = $obj->label; + $product_static->type = $obj->fk_product_type; + $product_static->status_buy = $obj->tobuy; + $product_static->status = $obj->tosell; $product_static->entity = $obj->entity; $product_static->pmp = $obj->pmp; if ((! empty($conf->stock->enabled) && $user->rights->stock->lire && $search_type != 1) || ! empty($conf->global->STOCK_DISABLE_OPTIM_LOAD)) // To optimize call of load_stock { - if ($obj->fk_product_type != 1 || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) // Not a service - { - $product_static->load_stock('nobatch'); // Load stock_reel + stock_warehouse. This also call load_virtual_stock() - } + if ($obj->fk_product_type != 1 || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) // Not a service + { + $product_static->load_stock('nobatch'); // Load stock_reel + stock_warehouse. This also call load_virtual_stock() + } } - print ''; + print ''; - // Ref - if (! empty($arrayfields['p.ref']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } - // Ref supplier - if (! empty($arrayfields['pfp.ref_fourn']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } - // Label - if (! empty($arrayfields['p.label']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Ref + if (! empty($arrayfields['p.ref']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + // Ref supplier + if (! empty($arrayfields['pfp.ref_fourn']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + // Label + if (! empty($arrayfields['p.label']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Type - if (! empty($arrayfields['p.fk_product_type']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Type + if (! empty($arrayfields['p.fk_product_type']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Barcode - if (! empty($arrayfields['p.barcode']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Barcode + if (! empty($arrayfields['p.barcode']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Duration - if (! empty($arrayfields['p.duration']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Duration + if (! empty($arrayfields['p.duration']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Sell price - if (! empty($arrayfields['p.sellprice']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Sell price + if (! empty($arrayfields['p.sellprice']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Better buy price - if (! empty($arrayfields['p.minbuyprice']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Better buy price + if (! empty($arrayfields['p.minbuyprice']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Number of buy prices if (! empty($arrayfields['p.numbuyprice']['checked'])) @@ -854,73 +873,73 @@ else print ''; } - // Limit alert - if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Desired stock - if (! empty($arrayfields['p.desiredstock']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Stock - if (! empty($arrayfields['p.stock']['checked'])) - { + // Limit alert + if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Desired stock + if (! empty($arrayfields['p.desiredstock']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Stock real + if (! empty($arrayfields['p.stock']['checked'])) + { print ''; - if (! $i) $totalarray['nbfield']++; - } - // Stock - if (! empty($arrayfields['stock_virtual']['checked'])) - { + print $product_static->stock_reel; + } + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Stock virtual + if (! empty($arrayfields['stock_virtual']['checked'])) + { print ''; - if (! $i) $totalarray['nbfield']++; - } - // Lot/Serial - if (! empty($arrayfields['p.tobatch']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Extra fields + print $product_static->stock_theorique; + } + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Lot/Serial + if (! empty($arrayfields['p.tobatch']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Accountancy code sell + if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Accountancy code sell + if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) @@ -934,81 +953,81 @@ else $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['p.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Status (to sell) - if (! empty($arrayfields['p.tosell']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status (to buy) - if (! empty($arrayfields['p.tobuy']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Action - print ''; - if (! $i) $totalarray['nbfield']++; + // Status (to sell) + if (! empty($arrayfields['p.tosell']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status (to buy) + if (! empty($arrayfields['p.tobuy']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Action + print ''; + if (! $i) $totalarray['nbfield']++; - print "\n"; - $i++; - } + print "\n"; + $i++; + } - $db->free($resql); + $db->free($resql); - print "
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + // Lines with input filters + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; $array=array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); - print $form->selectarray('search_type', $array, $search_type); - print ''; - print ''; - print ''; + print ''; + print ''; - print ' '; - print ''; + print ' '; + print ''; - print ''; + print ''; - print ' '; - print ''; + print ' '; + print ''; - print ' '; - print ''; + print ' '; + print ''; - print ' '; - print ''; + print ' '; + print ''; - print ' '; - print ''; + print ' '; + print ''; - print ' '; - print ''; + print ' '; + print '  '.$form->selectyesno($search_tobatch, '', '', '', 1).''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + { + $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 ''; + } + else + { + // for the type as 'checkbox', 'chkbxlst', 'sellist' we should use code instead of id (example: I declare a 'chkbxlst' to have a link with dictionnairy, I have to extend it with the 'code' instead 'rowid') + echo $extrafields->showInputField($key, $search_array_options['search_options_'.$key], '', '', 'search_'); + } + print ''; - print ''; - print ''; - print $form->selectarray('tosell', array('0'=>$langs->trans('ProductStatusNotOnSellShort'),'1'=>$langs->trans('ProductStatusOnSellShort')),$tosell,1); - print ''; + print ''; + print ''; + print $form->selectarray('search_tosell', array('0'=>$langs->trans('ProductStatusNotOnSellShort'),'1'=>$langs->trans('ProductStatusOnSellShort')),$search_tosell,1); + print ''; - print $form->selectarray('tobuy', array('0'=>$langs->trans('ProductStatusNotOnBuyShort'),'1'=>$langs->trans('ProductStatusOnBuyShort')),$tobuy,1); - print ''; - $searchpicto=$form->showFilterButtons(); - print $searchpicto; - print ''; + print $form->selectarray('search_tobuy', array('0'=>$langs->trans('ProductStatusNotOnBuyShort'),'1'=>$langs->trans('ProductStatusOnBuyShort')),$search_tobuy,1); + print ''; + $searchpicto=$form->showFilterButtons(); + print $searchpicto; + print '
    '; - print $product_static->getNomUrl(1,'',24); - print "'; - print $product_static->getNomUrl(1,'',24); - print "'.dol_trunc($obj->label,40).''; + print $product_static->getNomUrl(1); + print "'; + print $product_static->getNomUrl(1); + print "'.dol_trunc($obj->label,40).''.$obj->fk_product_type.''.$obj->fk_product_type.''.$obj->barcode.''.$obj->barcode.''; - if (preg_match('/([^a-z]+)[a-z]/i',$obj->duration)) - { - if (preg_match('/([^a-z]+)y/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationYear"); - elseif (preg_match('/([^a-z]+)m/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationMonth"); - elseif (preg_match('/([^a-z]+)w/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationWeek"); - elseif (preg_match('/([^a-z]+)d/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationDay"); - //elseif (preg_match('/([^a-z]+)h/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationHour"); - else print $obj->duration; - } - print ''; + if (preg_match('/([^a-z]+)[a-z]/i',$obj->duration)) + { + if (preg_match('/([^a-z]+)y/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationYear"); + elseif (preg_match('/([^a-z]+)m/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationMonth"); + elseif (preg_match('/([^a-z]+)w/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationWeek"); + elseif (preg_match('/([^a-z]+)d/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationDay"); + //elseif (preg_match('/([^a-z]+)h/i',$obj->duration,$regs)) print $regs[1].' '.$langs->trans("DurationHour"); + else print $obj->duration; + } + print ''; - if ($obj->tosell) - { - if ($obj->price_base_type == 'TTC') print price($obj->price_ttc).' '.$langs->trans("TTC"); - else print price($obj->price).' '.$langs->trans("HT"); - } - print ''; + if ($obj->tosell) + { + if ($obj->price_base_type == 'TTC') print price($obj->price_ttc).' '.$langs->trans("TTC"); + else print price($obj->price).' '.$langs->trans("HT"); + } + print ''; - if ($obj->tobuy && $obj->minsellprice != '') - { - //print price($obj->minsellprice).' '.$langs->trans("HT"); - if ($product_fourn->find_min_price_product_fournisseur($obj->rowid) > 0) - { - if ($product_fourn->product_fourn_price_id > 0) - { - if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) - { - $htmltext=$product_fourn->display_price_product_fournisseur(1, 1, 0, 1); - print $form->textwithpicto(price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"),$htmltext); - } - else print price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"); - } - } - } - print ''; + if ($obj->tobuy && $obj->minsellprice != '') + { + //print price($obj->minsellprice).' '.$langs->trans("HT"); + if ($product_fourn->find_min_price_product_fournisseur($obj->rowid) > 0) + { + if ($product_fourn->product_fourn_price_id > 0) + { + if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) + { + $htmltext=$product_fourn->display_price_product_fournisseur(1, 1, 0, 1); + print $form->textwithpicto(price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"),$htmltext); + } + else print price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"); + } + } + } + print ''; - if ($obj->fk_product_type != 1) - { - print $obj->seuil_stock_alerte; - } - print ''; - if ($obj->fk_product_type != 1) - { - print $obj->desiredstock; - } - print ''; + if ($obj->fk_product_type != 1) + { + print $obj->seuil_stock_alerte; + } + print ''; + if ($obj->fk_product_type != 1) + { + print $obj->desiredstock; + } + print ''; - if ($obj->fk_product_type != 1) - { + if ($obj->fk_product_type != 1) + { if ($obj->seuil_stock_alerte != '' && $product_static->stock_reel < (float) $obj->seuil_stock_alerte) print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' '; - print $product_static->stock_reel; - } - print ''; - if ($obj->fk_product_type != 1) - { + if ($obj->fk_product_type != 1) + { if ($obj->seuil_stock_alerte != '' && $product_static->stock_theorique < (float) $obj->seuil_stock_alerte) print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' '; - print $product_static->stock_theorique; - } - print ''; - print yn($obj->tobatch); - print ''.$obj->accountancy_code_sell.''.$obj->accountancy_code_buy.''; + print yn($obj->tobatch); + print ''.$obj->accountancy_code_sell.''.$obj->accountancy_code_buy.''; - print dol_print_date($obj->date_creation, 'dayhour'); - print ''; - print dol_print_date($obj->date_update, 'dayhour'); - print ''; + print dol_print_date($obj->date_creation, 'dayhour', 'tzuser'); + print ''; + print dol_print_date($obj->date_update, 'dayhour', 'tzuser'); + print ''; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - print ajax_object_onoff($product_static, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); - } else { - print $product_static->LibStatut($obj->tosell,5,0); - } - print ''; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - print ajax_object_onoff($product_static, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); - } else { - print $product_static->LibStatut($obj->tobuy,5,1); - } - 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 ''; + if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + print ajax_object_onoff($product_static, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); + } else { + print $product_static->LibStatut($obj->tosell,5,0); + } + print ''; + if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + print ajax_object_onoff($product_static, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); + } else { + print $product_static->LibStatut($obj->tobuy,5,1); + } + 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 "
    "; - } - print '
    '; - } - else - { - dol_print_error($db); - } + print "
    "; + print ""; + } + print ''; + } + else + { + dol_print_error($db); + } } diff --git a/htdocs/product/note.php b/htdocs/product/note.php index 19496eeb860..5e73548579c 100644 --- a/htdocs/product/note.php +++ b/htdocs/product/note.php @@ -93,7 +93,7 @@ if ($id > 0 || ! empty($ref)) dol_fiche_head($head, 'note', $titre, -1, $picto); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter=" fk_product_type = ".$object->type; $shownav = 1; diff --git a/htdocs/product/price.php b/htdocs/product/price.php index f16b716c9cc..e00973902dd 100644 --- a/htdocs/product/price.php +++ b/htdocs/product/price.php @@ -1,9 +1,9 @@ +/* Copyright (C) 2001-2007 Rodolphe Quiedeville * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005 Eric Seigne - * Copyright (C) 2005-2015 Regis Houssin - * Copyright (C) 2006 Andre Cianfarani + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2014 Florian Henry * Copyright (C) 2014-2016 Juanjo Menent * Copyright (C) 2014-2015 Philippe Grand @@ -690,7 +690,7 @@ $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); dol_fiche_head($head, 'price', $titre, -1, $picto); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter=" fk_product_type = ".$object->type; $shownav = 1; @@ -744,7 +744,7 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES)) if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility { // TVA - print '
    ' . $langs->trans("VATRate") . ''; + print '
    ' . $langs->trans("DefaultTaxRate") . ''; $positiverates=''; if (price2num($object->multiprices_tva_tx[$soc->price_level])) $positiverates.=($positiverates?'/':'').price2num($object->multiprices_tva_tx[$soc->price_level]); @@ -758,7 +758,7 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES)) else { // TVA - print '
    ' . $langs->trans("VATRate") . ''; + print '
    ' . $langs->trans("DefaultTaxRate") . ''; $positiverates=''; if (price2num($object->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($object->tva_tx); @@ -781,14 +781,14 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES)) if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility { // We show only vat for level 1 - print '
    ' . $langs->trans("VATRate") . '
    ' . $langs->trans("DefaultTaxRate") . '' . vatrate($object->multiprices_tva_tx[1], true) . '
    ' . $langs->trans("VATRate") . ''; + print '
    ' . $langs->trans("DefaultTaxRate") . ''; $positiverates=''; if (price2num($object->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($object->tva_tx); @@ -945,7 +945,7 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES)) else { // TVA - print '
    ' . $langs->trans("VATRate") . ''; + print '
    ' . $langs->trans("DefaultTaxRate") . ''; $positiverates=''; if (price2num($object->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($object->tva_tx); @@ -1123,7 +1123,7 @@ if ($action == 'edit_vat' && ($user->rights->produit->creer || $user->rights->se print ''; // VAT - print ''; @@ -1157,7 +1157,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) print '
    ' . $langs->trans("VATRate") . ''; + print '
    ' . $langs->trans("DefaultTaxRate") . ''; print $form->load_tva("tva_tx", $object->default_vat_code ? $object->tva_tx.' ('.$object->default_vat_code.')' : $object->tva_tx, $mysoc, '', $object->id, $object->tva_npr, $object->type, false, 1); print '
    '; // VAT - print ''; @@ -1240,6 +1240,9 @@ if ($action == 'edit_price' && $object->getRights()->creer) $parameters=array('colspan' => 2); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + $parameters=array('colspan' => 2); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print '
    ' . $langs->trans("VATRate") . ''; + print '
    ' . $langs->trans("DefaultTaxRate") . ''; print $form->load_tva("tva_tx", $object->default_vat_code ? $object->tva_tx.' ('.$object->default_vat_code.')' : $object->tva_tx, $mysoc, '', $object->id, $object->tva_npr, $object->type, false, 1); print '
    '; dol_fiche_end(); @@ -1295,7 +1298,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) print '
    '.$langs->trans("PriceLevel").''.$langs->trans("VATRate").''.$langs->trans("DefaultTaxRate").''.$langs->trans("SellingPrice").'' . $langs->trans("PriceBase") . '' . $langs->trans("VATRate") . '' . $langs->trans("DefaultTaxRate") . '' . $langs->trans("HT") . '' . $langs->trans("TTC") . '
    ' . $langs->trans("VATRate") . ''; + print '
    ' . $langs->trans("DefaultTaxRate") . ''; print $form->load_tva("tva_tx", $object->default_vat_code ? $object->tva_tx.' ('.$object->default_vat_code.')' : $object->tva_tx, $mysoc, '', $object->id, $object->tva_npr, $object->type, false, 1); print '
    ' . $langs->trans("VATRate") . ''; + print '
    ' . $langs->trans("DefaultTaxRate") . ''; print $form->load_tva("tva_tx", $prodcustprice->default_vat_code ? $prodcustprice->tva_tx.' ('.$prodcustprice->default_vat_code.')' : $prodcustprice->tva_tx, $mysoc, '', $object->id, $prodcustprice->recuperableonly, $object->type, false, 1); print '
    ' . $langs->trans("ThirdParty") . '' . $langs->trans("AppliedPricesFrom") . '' . $langs->trans("PriceBase") . '' . $langs->trans("VATRate") . '' . $langs->trans("DefaultTaxRate") . '' . $langs->trans("HT") . '' . $langs->trans("TTC") . '' . $langs->trans("INCT") . '' . $langs->trans("ThirdParty") . '' . $langs->trans("AppliedPricesFrom") . '' . $langs->trans("PriceBase") . '' . $langs->trans("VATRate") . '' . $langs->trans("DefaultTaxRate") . '' . $langs->trans("HT") . '' . $langs->trans("TTC") . '' . $langs->trans("INCT") . '
    '.$objp->batch.''; + if ($product_lot_static->batch) + { + print $product_lot_static->getNomUrl(1); + } + print ''.dol_print_date($db->jdate($objp->eatby), 'day').''.dol_print_date($db->jdate($objp->sellby), 'day').''; diff --git a/htdocs/product/stats/card.php b/htdocs/product/stats/card.php index 6389c5a8b8b..8f08e0b0317 100644 --- a/htdocs/product/stats/card.php +++ b/htdocs/product/stats/card.php @@ -138,7 +138,7 @@ if ($result && (! empty($id) || ! empty($ref))) dol_fiche_head($head, 'stats', $titre, -1, $picto); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, ($user->societe_id?0:1), 'ref', '', '', '', 0, '', '', 1); diff --git a/htdocs/product/stats/commande.php b/htdocs/product/stats/commande.php index 5a371554058..dc3d9a9b7d6 100644 --- a/htdocs/product/stats/commande.php +++ b/htdocs/product/stats/commande.php @@ -100,7 +100,7 @@ if ($id > 0 || ! empty($ref)) print $hookmanager->resPrint; if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; @@ -228,7 +228,7 @@ if ($id > 0 || ! empty($ref)) print ''.$societestatic->getNomUrl(1).'".$objp->code_client."'; - print dol_print_date($db->jdate($objp->date_commande))."'.$objp->qty."'.price($objp->total_ht)."'.$orderstatic->LibStatut($objp->statut,$objp->facture,5).'' . $societestatic->getNomUrl(1) . '" . $objp->code_client . "'; - print dol_print_date($db->jdate($objp->date_commande)) . "' . $objp->qty . "' . price($objp->total_ht) . "' . $supplierorderstatic->getLibStatut(4) . ''.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($objp->name,44).'".$objp->code_client.""; - print dol_print_date($db->jdate($objp->date_contrat))."".price($objp->total_ht)."'; print ''.($objp->nb_initial>0?$objp->nb_initial:'').''.$societestatic->getNomUrl(1).'".$objp->code_client."'; - print dol_print_date($db->jdate($objp->datef),'day')."'.$objp->qty."'.price($objp->total_ht)."'.$invoicestatic->LibStatut($objp->paye,$objp->statut,5,$paiement,$objp->type).'' . $societestatic->getNomUrl(1) . '" . $objp->code_client . "'; - print dol_print_date($db->jdate($objp->datef)) . "' . $objp->qty . "' . price($objp->total_ht) . "' . $supplierinvoicestatic->LibStatut($objp->paye, $objp->statut, 5) . ''.$societestatic->getNomUrl(1).''; - print dol_print_date($db->jdate($objp->datep)) . "" . $objp->qty . "' . price($objp->amount) . '' . $propalstatic->LibStatut($objp->statut, 5) . '
    '; + + show_stats_for_company($product, $socid); + + print "
    "; + + print '
    '; + print '
    '; + + dol_fiche_end(); + + + if ($user->rights->propale->lire) + { + $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, p.rowid as propalid, p.ref, d.total_ht as amount,"; + //$sql .= " p.ref_supplier,"; + $sql .= "p.date_valid, p.fk_statut as statut, d.rowid, d.qty"; + if (! $user->rights->societe->client->voir && ! $socid) + $sql .= ", sc.fk_soc, sc.fk_user "; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe as s"; + $sql .= "," . MAIN_DB_PREFIX . "supplier_proposal as p"; + $sql .= ", " . MAIN_DB_PREFIX . "supplier_proposaldet as d"; + if (! $user->rights->societe->client->voir && ! $socid) + $sql .= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; + $sql .= " WHERE p.fk_soc = s.rowid"; + $sql .= " AND p.entity IN (".getEntity('propal').")"; + $sql .= " AND d.fk_supplier_proposal = p.rowid"; + $sql .= " AND d.fk_product =" . $product->id; + if (! empty($search_month)) + $sql .= ' AND MONTH(p.datep) IN (' . $search_month . ')'; + if (! empty($search_year)) + $sql .= ' AND YEAR(p.datep) IN (' . $search_year . ')'; + if (! $user->rights->societe->client->voir && ! $socid) + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . $user->id; + if ($socid) + $sql .= " AND p.fk_soc = " . $socid; + $sql .= " ORDER BY $sortfield $sortorder "; + + // Calcul total qty and amount for global if full scan list + $total_ht = 0; + $total_qty = 0; + $totalrecords = 0; + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + $result = $db->query($sql); + if ($result) { + $totalrecords = $db->num_rows($result); + while ( $objp = $db->fetch_object($result) ) { + $total_ht += $objp->amount; + $total_qty += $objp->qty; + } + } + } + + $sql .= $db->plimit($conf->liste_limit + 1, $offset); + + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + + if (! empty($id)) + $option .= '&id=' . $product->id; + if (! empty($search_month)) + $option .= '&search_month=' . $search_month; + if (! empty($search_year)) + $option .= '&search_year=' . $search_year; + + print '
    ' . "\n"; + if (! empty($sortfield)) + print ''; + if (! empty($sortorder)) + print ''; + if (! empty($page)) { + print ''; + $option .= '&page=' . $page; + } + + print_barre_liste($langs->trans("Proposals"), $page, $_SERVER["PHP_SELF"], "&id=$product->id", $sortfield, $sortorder, '', $num, $totalrecords, ''); + print '
    '; + print '
    '; + print $langs->trans('Period') . ' (' . $langs->trans("DatePropal") . ') - '; + print $langs->trans('Month') . ': '; + print $langs->trans('Year') . ':' . $formother->selectyear($search_year ? $search_year : - 1, 'search_year', 1, 20, 5); + print '
    '; + print ''; + print ''; + print '
    '; + print '
    '; + print '
    '; + + $i = 0; + print '
    '; + print ''; + print ''; + print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.rowid", "", $option, '', $sortfield, $sortorder); + print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", $option, '', $sortfield, $sortorder); + print_liste_field_titre("DatePropal", $_SERVER["PHP_SELF"], "p.date_valid", "", $option, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", $option, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre("AmountHT", $_SERVER["PHP_SELF"], "p.total", "", $option, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); + print "\n"; + + if ($num > 0) + { + $var = True; + while ($i < $num && $i < $conf->liste_limit) + { + $objp = $db->fetch_object($result); + $var = ! $var; + + print ''; + print '\n"; + $societestatic->fetch($objp->socid); + print ''; + print '"; + print "\n"; + print '' . "\n"; + print ''; + print "\n"; + $i ++; + + if (! empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + $total_ht += $objp->total_ht; + $total_qty += $objp->qty; + } + } + } + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "
    '; + $propalstatic->id=$objp->propalid; + $propalstatic->ref=$objp->ref; + print $propalstatic->getNomUrl(1); + print "'.$societestatic->getNomUrl(1).''; + print dol_print_date($db->jdate($objp->date_valid), 'dayhour') . "" . $objp->qty . "' . price($objp->amount) . '' . $propalstatic->LibStatut($objp->statut, 5) . '
    ' . $langs->trans('Total') . '' . $total_qty . '' . price($total_ht) . '
    "; + print '
    '; + print '
    '; + } else { + dol_print_error($db); + } + $db->free($result); + } + } +} else { + dol_print_error(); +} + +llxFooter(); +$db->close(); diff --git a/htdocs/product/stock/card.php b/htdocs/product/stock/card.php index 0f843e97b61..c95e805c3f5 100644 --- a/htdocs/product/stock/card.php +++ b/htdocs/product/stock/card.php @@ -39,7 +39,7 @@ $langs->load("companies"); $langs->load("categories"); $action=GETPOST('action','aZ09'); -$cancel=GETPOST('cancel'); +$cancel=GETPOST('cancel','alpha'); $confirm=GETPOST('confirm'); $sortfield = GETPOST("sortfield",'alpha'); @@ -48,7 +48,7 @@ $id = GETPOST("id",'int'); if (! $sortfield) $sortfield="p.ref"; if (! $sortorder) $sortorder="DESC"; -$backtopage=GETPOST("backtopage"); +$backtopage=GETPOST('backtopage','alpha'); // Security check $result=restrictedArea($user,'stock'); diff --git a/htdocs/product/stock/class/api_stockmovements.class.php b/htdocs/product/stock/class/api_stockmovements.class.php index e1d1ccd7888..cb861f78575 100644 --- a/htdocs/product/stock/class/api_stockmovements.class.php +++ b/htdocs/product/stock/class/api_stockmovements.class.php @@ -23,13 +23,13 @@ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; /** * API class for stock movements * - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} */ class StockMovements extends DolibarrApi { /** - * @var array $FIELDS Mandatory fields, checked when create and update object + * @var array $FIELDS Mandatory fields, checked when create and update object */ static $FIELDS = array( 'product_id', @@ -59,21 +59,21 @@ class StockMovements extends DolibarrApi * * @param int $id ID of movement * @return array|mixed data without useless information - * + * * @throws RestException */ /* function get($id) - { + { if(! DolibarrApiAccess::$user->rights->stock->lire) { throw new RestException(401); } - + $result = $this->stockmovement->fetch($id); if( ! $result ) { throw new RestException(404, 'warehouse not found'); } - + if( ! DolibarrApi::_checkAccessToResource('warehouse',$this->stockmovement->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -93,21 +93,21 @@ class StockMovements extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') { global $db, $conf; - + $obj_ret = array(); - + if(! DolibarrApiAccess::$user->rights->stock->lire) { throw new RestException(401); } - + $sql = "SELECT t.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."stock_mouvement as t"; //$sql.= ' WHERE t.entity IN ('.getEntity('stock').')'; $sql.= ' WHERE 1 = 1'; // Add sql filters - if ($sqlfilters) + if ($sqlfilters) { if (! DolibarrApi::_checkFilters($sqlfilters)) { @@ -116,7 +116,7 @@ class StockMovements extends DolibarrApi $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - + $sql.= $db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) @@ -162,13 +162,13 @@ class StockMovements extends DolibarrApi * @param string $movementlabel Movement label {@example Inventory number 123} * @param string $price To update AWP (Average Weighted Price) when you make a stock increase (qty must be higher then 0). */ - - + + /** * Create stock movement object. * You can use the following message to test this RES API: * { "product_id": 1, "warehouse_id": 1, "qty": 1, "lot": "", "movementcode": "INV123", "movementlabel": "Inventory 123", "price": 0 } - * + * * @param array $request_data Request data * @return int ID of stock movement */ @@ -181,7 +181,7 @@ class StockMovements extends DolibarrApi // Check mandatory fields //$result = $this->_validate($request_data); - + foreach($request_data as $field => $value) { //$this->stockmovement->$field = $value; if ($field == 'product_id') $product_id = $value; @@ -192,7 +192,7 @@ class StockMovements extends DolibarrApi if ($field == 'movementlabel') $movementlabel = $value; if ($field == 'price') $price = $value; } - + // Type increase or decrease if ($qty >= 0) $type = 3; else $type = 2; @@ -200,16 +200,16 @@ class StockMovements extends DolibarrApi if($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, '', '', '', $lot) <= 0) { throw new RestException(503, 'Error when create stock movement : '.$this->stockmovement->error); } - + return $this->stockmovement->id; } /** * Update stock movement - * + * * @param int $id Id of warehouse to update - * @param array $request_data Datas - * @return int + * @param array $request_data Datas + * @return int */ /* function put($id, $request_data = NULL) @@ -217,12 +217,12 @@ class StockMovements extends DolibarrApi if(! DolibarrApiAccess::$user->rights->stock->creer) { throw new RestException(401); } - + $result = $this->stockmovement->fetch($id); if( ! $result ) { throw new RestException(404, 'stock movement not found'); } - + if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -231,13 +231,13 @@ class StockMovements extends DolibarrApi if ($field == 'id') continue; $this->stockmovement->$field = $value; } - + if($this->stockmovement->update($id, DolibarrApiAccess::$user)) return $this->get ($id); - + return false; }*/ - + /** * Delete stock movement * @@ -254,15 +254,15 @@ class StockMovements extends DolibarrApi if( ! $result ) { throw new RestException(404, 'stock movement not found'); } - + if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + if (! $this->stockmovement->delete(DolibarrApiAccess::$user)) { throw new RestException(401,'error when delete stock movement'); } - + return array( 'success' => array( 'code' => 200, @@ -270,9 +270,9 @@ class StockMovements extends DolibarrApi ) ); }*/ - - - + + + /** * Clean sensible object datas * @@ -280,9 +280,9 @@ class StockMovements extends DolibarrApi * @return array Array of cleaned object properties */ function _cleanObjectDatas($object) { - + $object = parent::_cleanObjectDatas($object); - + // Remove useless data unset($object->civility_id); unset($object->firstname); @@ -321,19 +321,19 @@ class StockMovements extends DolibarrApi unset($object->fk_project); unset($object->project); unset($object->canvas); - + //unset($object->eatby); Filled correctly in read mode //unset($object->sellby); Filled correctly in read mode - + return $object; } - + /** * Validate fields before create or update object - * + * * @param array|null $data Data to validate * @return array - * + * * @throws RestException */ function _validate($data) diff --git a/htdocs/product/stock/class/api_warehouses.class.php b/htdocs/product/stock/class/api_warehouses.class.php index 6eccf805b41..fd2dc4b2328 100644 --- a/htdocs/product/stock/class/api_warehouses.class.php +++ b/htdocs/product/stock/class/api_warehouses.class.php @@ -23,13 +23,13 @@ /** * API class for warehouses * - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} */ class Warehouses extends DolibarrApi { /** - * @var array $FIELDS Mandatory fields, checked when create and update object + * @var array $FIELDS Mandatory fields, checked when create and update object */ static $FIELDS = array( 'label', @@ -57,20 +57,20 @@ class Warehouses extends DolibarrApi * * @param int $id ID of warehouse * @return array|mixed data without useless information - * + * * @throws RestException */ function get($id) - { + { if(! DolibarrApiAccess::$user->rights->stock->lire) { throw new RestException(401); } - + $result = $this->warehouse->fetch($id); if( ! $result ) { throw new RestException(404, 'warehouse not found'); } - + if( ! DolibarrApi::_checkAccessToResource('warehouse',$this->warehouse->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -80,7 +80,7 @@ class Warehouses extends DolibarrApi /** * List warehouses - * + * * Get a list of warehouses * * @param string $sortfield Sort field @@ -92,20 +92,20 @@ class Warehouses extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') { global $db, $conf; - + $obj_ret = array(); - + if(! DolibarrApiAccess::$user->rights->stock->lire) { throw new RestException(401); } - + $sql = "SELECT t.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."entrepot as t"; $sql.= ' WHERE t.entity IN ('.getEntity('stock').')'; // Add sql filters - if ($sqlfilters) + if ($sqlfilters) { if (! DolibarrApi::_checkFilters($sqlfilters)) { @@ -114,7 +114,7 @@ class Warehouses extends DolibarrApi $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - + $sql.= $db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) @@ -154,7 +154,7 @@ class Warehouses extends DolibarrApi /** * Create warehouse object - * + * * @param array $request_data Request data * @return int ID of warehouse */ @@ -166,7 +166,7 @@ class Warehouses extends DolibarrApi // Check mandatory fields $result = $this->_validate($request_data); - + foreach($request_data as $field => $value) { $this->warehouse->$field = $value; } @@ -178,22 +178,22 @@ class Warehouses extends DolibarrApi /** * Update warehouse - * + * * @param int $id Id of warehouse to update - * @param array $request_data Datas - * @return int + * @param array $request_data Datas + * @return int */ function put($id, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->stock->creer) { throw new RestException(401); } - + $result = $this->warehouse->fetch($id); if( ! $result ) { throw new RestException(404, 'warehouse not found'); } - + if( ! DolibarrApi::_checkAccessToResource('stock',$this->warehouse->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -202,13 +202,13 @@ class Warehouses extends DolibarrApi if ($field == 'id') continue; $this->warehouse->$field = $value; } - + if($this->warehouse->update($id, DolibarrApiAccess::$user)) return $this->get ($id); - + return false; } - + /** * Delete warehouse * @@ -224,15 +224,15 @@ class Warehouses extends DolibarrApi if( ! $result ) { throw new RestException(404, 'warehouse not found'); } - + if( ! DolibarrApi::_checkAccessToResource('stock',$this->warehouse->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + if (! $this->warehouse->delete(DolibarrApiAccess::$user)) { throw new RestException(401,'error when delete warehouse'); } - + return array( 'success' => array( 'code' => 200, @@ -240,8 +240,8 @@ class Warehouses extends DolibarrApi ) ); } - - + + /** * Clean sensible object datas * @@ -249,22 +249,22 @@ class Warehouses extends DolibarrApi * @return array Array of cleaned object properties */ function _cleanObjectDatas($object) { - + $object = parent::_cleanObjectDatas($object); - + // Remove the subscriptions because they are handled as a subresource. //unset($object->subscriptions); - + return $object; } - - + + /** * Validate fields before create or update object - * + * * @param array|null $data Data to validate * @return array - * + * * @throws RestException */ function _validate($data) diff --git a/htdocs/product/stock/class/mouvementstock.class.php b/htdocs/product/stock/class/mouvementstock.class.php index 25e0e9e7fce..2c889d589df 100644 --- a/htdocs/product/stock/class/mouvementstock.class.php +++ b/htdocs/product/stock/class/mouvementstock.class.php @@ -38,13 +38,13 @@ class MouvementStock extends CommonObject * @var string Name of table without prefix where object is stored */ public $table_element = 'stock_mouvement'; - + public $product_id; public $warehouse_id; public $qty; public $type; - + public $tms = ''; public $datem = ''; public $price; @@ -54,8 +54,8 @@ class MouvementStock extends CommonObject public $origintype; public $inventorycode; public $batch; - - + + /** * Constructor @@ -67,7 +67,7 @@ class MouvementStock extends CommonObject $this->db = $db; } - + /** * Add a movement of stock (in one direction only) * @@ -174,7 +174,7 @@ class MouvementStock extends CommonObject { $tmparray=dol_getdate($eatby, true); $eatbywithouthour=dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); - if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) // We test date without hours and with hours for backward compatibility + if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) // We test date without hours and with hours for backward compatibility { // If found and eatby/sellby defined into table and provided and differs, return error $this->errors[]=$langs->trans("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->eatby), 'dayhour'), dol_print_date($eatby, 'dayhour')); @@ -202,7 +202,7 @@ class MouvementStock extends CommonObject $this->errors = $productlot->errors; $this->db->rollback(); return -5; - } + } } } if ($obj->sellby) @@ -242,7 +242,7 @@ class MouvementStock extends CommonObject } } } - + $i++; } } @@ -271,7 +271,7 @@ class MouvementStock extends CommonObject return -1; } } - + // Define if we must make the stock change (If product type is a service or if stock is used also for services) $movestock=0; if ($product->type != Product::TYPE_SERVICE || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) $movestock=1; @@ -298,7 +298,7 @@ class MouvementStock extends CommonObject $this->errors[] = $langs->trans('qtyToTranferLotIsNotEnough'); $this->db->rollback(); return -8; - } + } } else { @@ -311,8 +311,8 @@ class MouvementStock extends CommonObject return -8; } } - } - + } + if ($movestock && $entrepot_id > 0) // Change stock for current product, change for subproduct is done after { if(!empty($this->origin)) { // This is set by caller for tracking reason @@ -468,7 +468,7 @@ class MouvementStock extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$newpmp.", "; $sql.= " stock=(SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)"; $sql.= " WHERE rowid = ".$fk_product; - + dol_syslog(get_class($this)."::_create update AWP", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) @@ -477,7 +477,7 @@ class MouvementStock extends CommonObject $error = -4; } } - + // If stock is now 0, we can remove entry into llx_product_stock, but only if there is no child lines into llx_product_batch (detail of batch, because we can imagine // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot. $sql="DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE reel = 0 AND rowid NOT IN (SELECT fk_product_stock FROM ".MAIN_DB_PREFIX."product_batch as pb)"; @@ -512,7 +512,7 @@ class MouvementStock extends CommonObject } } - + /** * Load object in memory from the database @@ -524,7 +524,7 @@ class MouvementStock extends CommonObject public function fetch($id) { dol_syslog(__METHOD__, LOG_DEBUG); - + $sql = 'SELECT'; $sql .= ' t.rowid,'; $sql .= " t.tms,"; @@ -549,20 +549,20 @@ class MouvementStock extends CommonObject //} else { $sql .= ' AND t.rowid = ' . $id; //} - + $resql = $this->db->query($sql); if ($resql) { $numrows = $this->db->num_rows($resql); if ($numrows) { $obj = $this->db->fetch_object($resql); - + $this->id = $obj->rowid; - + $this->product_id = $obj->fk_product; $this->warehouse_id = $obj->fk_entrepot; $this->qty = $obj->value; $this->type = $obj->type_mouvement; - + $this->tms = $this->db->jdate($obj->tms); $this->datem = $this->db->jdate($obj->datem); $this->price = $obj->price; @@ -575,18 +575,18 @@ class MouvementStock extends CommonObject $this->eatby = $this->db->jdate($obj->eatby); $this->sellby = $this->db->jdate($obj->sellby); } - + // Retrieve all extrafields for invoice // fetch optionals attributes and labels require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields=new ExtraFields($this->db); $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); $this->fetch_optionals($this->id,$extralabels); - + // $this->fetch_lines(); - + $this->db->free($resql); - + if ($numrows) { return 1; } else { @@ -595,13 +595,13 @@ class MouvementStock extends CommonObject } else { $this->errors[] = 'Error ' . $this->db->lasterror(); dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR); - + return - 1; } } - - - + + + /** * Create movement in database for all subproducts @@ -676,7 +676,7 @@ class MouvementStock extends CommonObject function livraison($user, $fk_product, $entrepot_id, $qty, $price=0, $label='', $datem='', $eatby='', $sellby='', $batch='', $id_product_batch=0) { global $conf; - + $skip_batch = empty($conf->productbatch->enabled); return $this->_create($user, $fk_product, $entrepot_id, (0 - $qty), 2, $price, $label, '', $datem, $eatby, $sellby, $batch, $skip_batch, $id_product_batch); @@ -757,7 +757,7 @@ class MouvementStock extends CommonObject /** * Create or update batch record (update table llx_product_batch). No check is done here, done by parent. * - * @param array|int $dluo Could be either + * @param array|int $dluo Could be either * - int if row id of product_batch table * - or complete array('fk_product_stock'=>, 'batchnumber'=>) * @param int $qty Quantity of product with batch number. May be a negative amount. @@ -766,13 +766,13 @@ class MouvementStock extends CommonObject private function createBatch($dluo, $qty) { global $user; - + $pdluo=new Productbatch($this->db); $result=0; // Try to find an existing record with same batch number or id - if (is_numeric($dluo)) + if (is_numeric($dluo)) { $result=$pdluo->fetch($dluo); if (empty($pdluo->id)) @@ -783,21 +783,21 @@ class MouvementStock extends CommonObject $result = -2; } } - else if (is_array($dluo)) + else if (is_array($dluo)) { - if (isset($dluo['fk_product_stock'])) + if (isset($dluo['fk_product_stock'])) { $vfk_product_stock=$dluo['fk_product_stock']; $vbatchnumber = $dluo['batchnumber']; - + $result = $pdluo->find($vfk_product_stock,'','',$vbatchnumber); // Search on batch number only (eatby and sellby are deprecated here) } - else + else { dol_syslog(get_class($this)."::createBatch array param dluo must contain at least key fk_product_stock".$error, LOG_ERR); $result = -1; } - } + } else { dol_syslog(get_class($this)."::createBatch error invalid param dluo".$error, LOG_ERR); @@ -811,7 +811,7 @@ class MouvementStock extends CommonObject { //print "Avant ".$pdluo->qty." Apres ".($pdluo->qty + $qty)."
    "; $pdluo->qty += $qty; - if ($pdluo->qty == 0) + if ($pdluo->qty == 0) { $result=$pdluo->delete($user,1); } else { @@ -825,7 +825,7 @@ class MouvementStock extends CommonObject $pdluo->eatby = $veatby; $pdluo->sellby = $vsellby; $pdluo->batch = $vbatchnumber; - + $result=$pdluo->create($user,1); if ($result < 0) { @@ -834,21 +834,21 @@ class MouvementStock extends CommonObject } } } - + return $result; } /** * Return Url link of origin object - * + * * @param int $fk_origin Id origin * @param int $origintype Type origin * @return string */ - function get_origin($fk_origin, $origintype) + function get_origin($fk_origin, $origintype) { $origin=''; - + switch ($origintype) { case 'commande': require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; @@ -889,20 +889,20 @@ class MouvementStock extends CommonObject } if (empty($origin) || ! is_object($origin)) return ''; - + if ($origin->fetch($fk_origin) > 0) { return $origin->getNomUrl(1); } return ''; } - + /** * Set attribute origin to object - * + * * @param string $origin_element type of element * @param int $origin_id id of element - * + * * @return void */ function setOrigin($origin_element, $origin_id) @@ -941,7 +941,7 @@ class MouvementStock extends CommonObject // There is no specific properties. All data into insert are provided as method parameter. } - + /** * Return a link (with optionaly the picto) * Use this->id,this->lastname, this->firstname @@ -963,7 +963,7 @@ class MouvementStock extends CommonObject $label = '' . $langs->trans("Movement") . ' '.$this->id.''; $label.= '
    '; $label.= '' . $langs->trans('Label') . ': ' . $this->label; - $label.= '
    ' . $langs->trans('Qty') . ': ' .$this->qty; + $label.= '
    ' . $langs->trans('Qty') . ': ' .$this->qty; $label.= '
    '; $link = 'id . $linkend; return $result; } - + /** * Return label statut * @@ -990,7 +990,7 @@ class MouvementStock extends CommonObject { return $this->LibStatut($mode); } - + /** * Renvoi le libelle d'un status donne * diff --git a/htdocs/product/stock/class/productlot.class.php b/htdocs/product/stock/class/productlot.class.php index 78ea81bd41d..b34a656422c 100644 --- a/htdocs/product/stock/class/productlot.class.php +++ b/htdocs/product/stock/class/productlot.class.php @@ -46,7 +46,6 @@ class Productlot extends CommonObject public $picto='barcode'; - public $isnolinkedbythird = 1; public $ismultientitymanaged = 1; /** diff --git a/htdocs/product/stock/mouvement.php b/htdocs/product/stock/mouvement.php index 8659dfe8461..4b878c03260 100644 --- a/htdocs/product/stock/mouvement.php +++ b/htdocs/product/stock/mouvement.php @@ -51,7 +51,7 @@ $id=GETPOST('id','int'); $msid=GETPOST('msid','int'); $product_id=GETPOST("product_id"); $action=GETPOST('action','aZ09'); -$cancel=GETPOST('cancel'); +$cancel=GETPOST('cancel','alpha'); $idproduct = GETPOST('idproduct','int'); $year = GETPOST("year"); $month = GETPOST("month"); @@ -112,8 +112,8 @@ $object = new MouvementStock($db); // To be passed as parameter of executeHooks * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks diff --git a/htdocs/product/stock/product.php b/htdocs/product/stock/product.php index f45f2b30a56..faee4d05a6a 100644 --- a/htdocs/product/stock/product.php +++ b/htdocs/product/stock/product.php @@ -32,6 +32,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; @@ -50,15 +51,15 @@ $langs->load("stocks"); $langs->load("sendings"); if (! empty($conf->productbatch->enabled)) $langs->load("productbatch"); -$backtopage=GETPOST('backtopage'); +$backtopage=GETPOST('backtopage','alpha'); $action=GETPOST('action','aZ09'); -$cancel=GETPOST('cancel'); +$cancel=GETPOST('cancel','alpha'); $id=GETPOST('id', 'int'); $ref=GETPOST('ref', 'alpha'); $stocklimit = GETPOST('seuil_stock_alerte'); $desiredstock = GETPOST('desiredstock'); -$cancel = GETPOST('cancel'); +$cancel = GETPOST('cancel','alpha'); $fieldid = isset($_GET["ref"])?'ref':'rowid'; $d_eatby=dol_mktime(0, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); $d_sellby=dol_mktime(0, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); @@ -543,7 +544,7 @@ if ($id > 0 || $ref) dol_htmloutput_events(); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; if ($user->societe_id && ! in_array('stock', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; @@ -614,7 +615,7 @@ if ($id > 0 || $ref) } // Stock alert threshold - print ''.$form->editfieldkey("StockLimit",'seuil_stock_alerte',$object->seuil_stock_alerte,$object,$user->rights->produit->creer).''; + print ''.$form->editfieldkey($form->textwithpicto($langs->trans("StockLimit"), $langs->trans("StockLimitDesc"), 1),'seuil_stock_alerte',$object->seuil_stock_alerte,$object,$user->rights->produit->creer).''; print $form->editfieldval("StockLimit",'seuil_stock_alerte',$object->seuil_stock_alerte,$object,$user->rights->produit->creer,'string'); print ''; @@ -823,6 +824,8 @@ $sql.= " AND ps.fk_product = ".$object->id; $sql.= " ORDER BY e.label"; $entrepotstatic=new Entrepot($db); +$product_lot_static=new Productlot($db); + $total=0; $totalvalue=$totalvaluesell=0; @@ -867,6 +870,11 @@ if ($resql) if ($details<0) dol_print_error($db); foreach ($details as $pdluo) { + $product_lot_static->id = $pdluo->lotid; + $product_lot_static->batch = $pdluo->batch; + $product_lot_static->eatby = $pdluo->eatby; + $product_lot_static->sellby = $pdluo->sellby; + if ($action == 'editline' && GETPOST('lineid','int') == $pdluo->id) { //Current line edit print "\n".''; @@ -896,7 +904,9 @@ if ($resql) // Do not use this, or data will be wrong (bad tracking of movement label, inventory code, ... //print 'id.'#'.$pdluo->id.'">'; //print img_edit().''; - print ''.$pdluo->batch.''; + print ''; + print $product_lot_static->getNomUrl(1); + print ''; print ''. dol_print_date($pdluo->eatby,'day') .''; print ''. dol_print_date($pdluo->sellby,'day') .''; print ''.$pdluo->qty.($pdluo->qty<0?' '.img_warning():'').''; @@ -936,7 +946,6 @@ if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE)) { print '

    '; print_titre($langs->trans('AddNewProductStockWarehouse')); - //print '
    '; print '
    '; print ''; diff --git a/htdocs/product/stock/productlot_card.php b/htdocs/product/stock/productlot_card.php index 77466ead2c8..3a8f4cbff4e 100644 --- a/htdocs/product/stock/productlot_card.php +++ b/htdocs/product/stock/productlot_card.php @@ -45,7 +45,7 @@ $langs->load("productbatch"); // Get parameters $id = GETPOST('id','int'); $action = GETPOST('action','alpha'); -$backtopage = GETPOST('backtopage'); +$backtopage = GETPOST('backtopage','alpha'); $batch = GETPOST('batch','alpha'); $productid = GETPOST('productid','int'); $ref = GETPOST('ref','alpha'); // ref is productid_batch @@ -136,9 +136,11 @@ if (empty($reshook)) // some hooks if (empty($reshook)) { $result = $object->insertExtraFields(); - if ($result < 0) { - $error++; - } + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } else if ($reshook < 0) $error++; } @@ -150,7 +152,7 @@ if (empty($reshook)) // Action to add record if ($action == 'add') { - if (GETPOST('cancel')) + if (GETPOST('cancel','alpha')) { $urltogo=$backtopage?$backtopage:dol_buildpath('/stock/list.php',1); header("Location: ".$urltogo); @@ -198,10 +200,10 @@ if (empty($reshook)) } // Cancel - if ($action == 'update' && GETPOST('cancel')) $action='view'; + if ($action == 'update' && GETPOST('cancel','alpha')) $action='view'; // Action to update record - if ($action == 'update' && ! GETPOST('cancel')) + if ($action == 'update' && ! GETPOST('cancel','alpha')) { $error=0; @@ -284,7 +286,6 @@ if ($action == 'create') print ''."\n"; // print ''; // - print ''; print ''; print ''; print ''; diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php index 325ddd5f796..920bbac8a9b 100644 --- a/htdocs/product/stock/productlot_list.php +++ b/htdocs/product/stock/productlot_list.php @@ -45,7 +45,7 @@ $langs->load("users"); // Get parameters $id = GETPOST('id','int'); $action = GETPOST('action','alpha'); -$backtopage = GETPOST('backtopage'); +$backtopage = GETPOST('backtopage','alpha'); $myparam = GETPOST('myparam','alpha'); @@ -76,7 +76,7 @@ if (! $sortorder) $sortorder="ASC"; $socid=0; if ($user->societe_id > 0) { - $socid = $user->societe_id; + $socid = $user->societe_id; //accessforbidden(); } @@ -90,31 +90,31 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 't.ref'=>'Ref', - 't.note_public'=>'NotePublic', + 't.ref'=>'Ref', + 't.note_public'=>'NotePublic', ); // Definition of fields for list $arrayfields=array( //'t.entity'=>array('label'=>$langs->trans("Fieldentity"), 'checked'=>1), 't.batch'=>array('label'=>$langs->trans("Batch"), 'checked'=>1), - 't.fk_product'=>array('label'=>$langs->trans("Product"), 'checked'=>1), + 't.fk_product'=>array('label'=>$langs->trans("Product"), 'checked'=>1), 't.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>1), 't.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>1), //'t.import_key'=>array('label'=>$langs->trans("ImportKey"), 'checked'=>1), - //'t.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), - //'t.fk_user_creat'=>array('label'=>$langs->trans("UserCreationShort"), 'checked'=>0, 'position'=>500), + //'t.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), + //'t.fk_user_creat'=>array('label'=>$langs->trans("UserCreationShort"), 'checked'=>0, 'position'=>500), //'t.fk_user_modif'=>array('label'=>$langs->trans("UserModificationShort"), 'checked'=>0, 'position'=>500), - 't.datec'=>array('label'=>$langs->trans("DateCreationShort"), 'checked'=>0, 'position'=>500), - 't.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - //'t.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 't.datec'=>array('label'=>$langs->trans("DateCreationShort"), 'checked'=>0, 'position'=>500), + 't.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + //'t.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -122,8 +122,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab $object=new Productlot($db); if (($id > 0 || ! empty($ref)) && $action != 'add') { - $result=$object->fetch($id,$ref); - if ($result < 0) dol_print_error($db); + $result=$object->fetch($id,$ref); + if ($result < 0) dol_print_error($db); } @@ -132,8 +132,8 @@ if (($id > 0 || ! empty($ref)) && $action != 'add') * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -144,12 +144,12 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_entity=''; - $search_product=''; - $search_batch=''; - $search_fk_user_creat=''; - $search_fk_user_modif=''; - $search_import_key=''; + $search_entity=''; + $search_product=''; + $search_batch=''; + $search_fk_user_creat=''; + $search_fk_user_modif=''; + $search_import_key=''; $search_date_creation=''; $search_date_update=''; $toselect=''; @@ -159,12 +159,12 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', if (empty($reshook)) { - $objectclass='ProductLot'; - $objectlabel='LotSerial'; - $permtoread = $user->rights->stock->read; - $permtodelete = $user->rights->stock->delete; - $uploaddir = $conf->stock->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + $objectclass='ProductLot'; + $objectlabel='LotSerial'; + $permtoread = $user->rights->stock->read; + $permtodelete = $user->rights->stock->delete; + $uploaddir = $conf->stock->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -240,16 +240,16 @@ if ($sall) $sql.= natural_search(array_keys($fieldstosearchall), $sall); // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -273,325 +273,325 @@ dol_syslog($script_file, LOG_DEBUG); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); + $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected=is_array($toselect)?$toselect:array(); - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($search_entity != '') $param.= '&search_entity='.urlencode($search_entity); - if ($search_product != '') $param.= '&search_product='.urlencode($search_product); - if ($search_batch != '') $param.= '&search_batch='.urlencode($search_batch); - if ($search_fk_user_creat != '') $param.= '&search_fk_user_creat='.urlencode($search_fk_user_creat); - if ($search_fk_user_modif != '') $param.= '&search_fk_user_modif='.urlencode($search_fk_user_modif); - if ($search_import_key != '') $param.= '&search_import_key='.urlencode($search_import_key); - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($search_entity != '') $param.= '&search_entity='.urlencode($search_entity); + if ($search_product != '') $param.= '&search_product='.urlencode($search_product); + if ($search_batch != '') $param.= '&search_batch='.urlencode($search_batch); + if ($search_fk_user_creat != '') $param.= '&search_fk_user_creat='.urlencode($search_fk_user_creat); + if ($search_fk_user_modif != '') $param.= '&search_fk_user_modif='.urlencode($search_fk_user_modif); + if ($search_import_key != '') $param.= '&search_import_key='.urlencode($search_import_key); + if ($optioncss != '') $param.='&optioncss='.$optioncss; + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), - ); - //if ($user->rights->stock->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + $arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), + ); + //if ($user->rights->stock->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + if ($massaction == 'presend') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); print ''; - if ($optioncss != '') print ''; + if ($optioncss != '') print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } - /*$moreforfilter = ''; + /*$moreforfilter = ''; $moreforfilter.='
    '; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '
    ';*/ - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; - else $moreforfilter = $hookmanager->resPrint; + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; + else $moreforfilter = $hookmanager->resPrint; - if (! empty($moreforfilter)) + if (! empty($moreforfilter)) { print '
    '; print $moreforfilter; - print '
    '; + print ''; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - print '
    '; - print '
    '.$langs->trans("Label").'
    '.$langs->trans("Fieldentity").'
    '.$langs->trans("Fieldfk_product").'
    '.$langs->trans("Fieldbatch").'
    '.$langs->trans("Fieldfk_user_creat").'
    '."\n"; + print '
    '; + print '
    '."\n"; - // Fields title search - print ''; - if (! empty($arrayfields['t.entity']['checked'])) print ''; - if (! empty($arrayfields['t.batch']['checked'])) print ''; - if (! empty($arrayfields['t.fk_product']['checked'])) print ''; - if (! empty($arrayfields['t.eatby']['checked'])) print ''; - if (! empty($arrayfields['t.sellby']['checked'])) print ''; - if (! empty($arrayfields['t.fk_user_creat']['checked'])) print ''; - if (! empty($arrayfields['t.fk_user_modif']['checked'])) print ''; - if (! empty($arrayfields['t.import_key']['checked'])) print ''; - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['t.datec']['checked'])) - { - // Date creation - print ''; - } - if (! empty($arrayfields['t.tms']['checked'])) - { - // Date modification - print ''; - } - /*if (! empty($arrayfields['u.statut']['checked'])) + // Fields title search + print ''; + if (! empty($arrayfields['t.entity']['checked'])) print ''; + if (! empty($arrayfields['t.batch']['checked'])) print ''; + if (! empty($arrayfields['t.fk_product']['checked'])) print ''; + if (! empty($arrayfields['t.eatby']['checked'])) print ''; + if (! empty($arrayfields['t.sellby']['checked'])) print ''; + if (! empty($arrayfields['t.fk_user_creat']['checked'])) print ''; + if (! empty($arrayfields['t.fk_user_modif']['checked'])) print ''; + if (! empty($arrayfields['t.import_key']['checked'])) print ''; + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['t.datec']['checked'])) + { + // Date creation + print ''; + } + if (! empty($arrayfields['t.tms']['checked'])) + { + // Date modification + print ''; + } + /*if (! empty($arrayfields['u.statut']['checked'])) { // Status print ''; }*/ - // Action column - print ''; - print ''."\n"; + // Action column + print ''; + print ''."\n"; - // Fields title - print ''; - if (! empty($arrayfields['t.entity']['checked'])) print_liste_field_titre($arrayfields['t.entity']['label'],$_SERVER['PHP_SELF'],'t.entity','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.batch']['checked'])) print_liste_field_titre($arrayfields['t.batch']['label'],$_SERVER['PHP_SELF'],'t.batch','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.fk_product']['checked'])) print_liste_field_titre($arrayfields['t.fk_product']['label'],$_SERVER['PHP_SELF'],'t.fk_product','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.eatby']['checked'])) print_liste_field_titre($arrayfields['t.eatby']['label'],$_SERVER['PHP_SELF'],'t.eatby','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.sellby']['checked'])) print_liste_field_titre($arrayfields['t.sellby']['label'],$_SERVER['PHP_SELF'],'t.sellby','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.fk_user_creat']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_creat']['label'],$_SERVER['PHP_SELF'],'t.fk_user_creat','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.fk_user_modif']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_modif']['label'],$_SERVER['PHP_SELF'],'t.fk_user_modif','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.import_key']['checked'])) print_liste_field_titre($arrayfields['t.import_key']['label'],$_SERVER['PHP_SELF'],'t.import_key','',$param,'',$sortfield,$sortorder); + // Fields title + print ''; + if (! empty($arrayfields['t.entity']['checked'])) print_liste_field_titre($arrayfields['t.entity']['label'],$_SERVER['PHP_SELF'],'t.entity','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.batch']['checked'])) print_liste_field_titre($arrayfields['t.batch']['label'],$_SERVER['PHP_SELF'],'t.batch','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.fk_product']['checked'])) print_liste_field_titre($arrayfields['t.fk_product']['label'],$_SERVER['PHP_SELF'],'t.fk_product','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.eatby']['checked'])) print_liste_field_titre($arrayfields['t.eatby']['label'],$_SERVER['PHP_SELF'],'t.eatby','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.sellby']['checked'])) print_liste_field_titre($arrayfields['t.sellby']['label'],$_SERVER['PHP_SELF'],'t.sellby','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.fk_user_creat']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_creat']['label'],$_SERVER['PHP_SELF'],'t.fk_user_creat','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.fk_user_modif']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_modif']['label'],$_SERVER['PHP_SELF'],'t.fk_user_modif','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.import_key']['checked'])) print_liste_field_titre($arrayfields['t.import_key']['label'],$_SERVER['PHP_SELF'],'t.import_key','',$param,'',$sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } - // Hook fields + // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['t.datec']['checked'])) print_liste_field_titre($arrayfields['t.datec']['label'],$_SERVER["PHP_SELF"],"t.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'],$_SERVER["PHP_SELF"],"t.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); //if (! empty($arrayfields['t.status']['checked'])) print_liste_field_titre($arrayfields['t.status']['label'],$_SERVER["PHP_SELF"],"t.status","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print ''."\n"; + print ''."\n"; $productlot = new Productlot($db); $i=0; $var=true; $totalarray=array(); - while ($i < min($num, $limit)) - { - $obj = $db->fetch_object($resql); - if ($obj) - { - $var = !$var; + while ($i < min($num, $limit)) + { + $obj = $db->fetch_object($resql); + if ($obj) + { + $var = !$var; - $productlot->id = $obj->rowid; - $productlot->batch = $obj->batch; + $productlot->id = $obj->rowid; + $productlot->batch = $obj->batch; - // You can use here results - print ''; - if (! empty($arrayfields['t.entity']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.batch']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.fk_product']['checked'])) - { - $productstatic->id=$obj->fk_product; - $productstatic->type=$obj->product_type; - $productstatic->ref=$obj->product_ref; - $productstatic->label=$obj->product_label; - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.eatby']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.sellby']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.fk_user_creat']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.fk_user_modif']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.import_key']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['t.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['t.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - /* + // You can use here results + print ''; + if (! empty($arrayfields['t.entity']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.batch']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.fk_product']['checked'])) + { + $productstatic->id=$obj->fk_product; + $productstatic->type=$obj->product_type; + $productstatic->ref=$obj->product_ref; + $productstatic->label=$obj->product_label; + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.eatby']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.sellby']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.fk_user_creat']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.fk_user_modif']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['t.import_key']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['t.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['t.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + /* if (! empty($arrayfields['u.statut']['checked'])) { $userstatic->statut=$obj->statut; print ''; }*/ - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; - print ''; - } - $i++; - } + print ''; + } + $i++; + } - // Show total line - if (isset($totalarray['totalhtfield'])) - { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''; - else print ''; - } - elseif ($totalarray['totalhtfield'] == $i) print ''; - elseif ($totalarray['totalvatfield'] == $i) print ''; - elseif ($totalarray['totalttcfield'] == $i) print ''; - else print ''; - } - print ''; - } + // Show total line + if (isset($totalarray['totalhtfield'])) + { + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } + elseif ($totalarray['totalhtfield'] == $i) print ''; + elseif ($totalarray['totalvatfield'] == $i) print ''; + elseif ($totalarray['totalttcfield'] == $i) print ''; + else print ''; + } + print ''; + } - $db->free($resql); + $db->free($resql); $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 '
    '; - 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 '
    '; + 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 ''; print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); print ''; - $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); - print $searchpicto; - print '
    '; + $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + print $searchpicto; + print '
    '.$obj->entity.''.$productlot->getNomUrl(1).''.$productstatic->getNomUrl(1).''.dol_print_date($db->jdate($obj->eatby), 'day').''.dol_print_date($db->jdate($obj->sellby), 'day').''.$obj->fk_user_creat.''.$obj->fk_user_modif.''.$obj->import_key.''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print '
    '.$obj->entity.''.$productlot->getNomUrl(1).''.$productstatic->getNomUrl(1).''.dol_print_date($db->jdate($obj->eatby), 'day').''.dol_print_date($db->jdate($obj->sellby), 'day').''.$obj->fk_user_creat.''.$obj->fk_user_modif.''.$obj->import_key.''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$userstatic->getLibStatut(3).''; - 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 ''; + 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 '
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
    '."\n"; - print ''; + print ''; print '
    '."\n"; @@ -616,8 +616,8 @@ if ($resql) } else { - $error++; - dol_print_error($db); + $error++; + dol_print_error($db); } diff --git a/htdocs/product/stock/replenish.php b/htdocs/product/stock/replenish.php index 28786f0d324..b959eebeb2d 100644 --- a/htdocs/product/stock/replenish.php +++ b/htdocs/product/stock/replenish.php @@ -357,17 +357,17 @@ if ($usevirtualstock) if ($salert == 'on') // Option to see when stock is lower than alert { - $sql.= ' AND ('.$sqlalertstock.' > 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql.= ' AND ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; $sql.= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.')))'; $alertchecked = 'checked'; } } else { - $sql.= ' HAVING (('.$sqldesiredtock.' > 0 AND ('.$sqldesiredtock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; - $sql.= ' OR ('.$sqlalertstock.' > 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").'))))'; + $sql.= ' HAVING (('.$sqldesiredtock.' >= 0 AND ('.$sqldesiredtock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; + $sql.= ' OR ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").'))))'; if ($salert == 'on') // Option to see when stock is lower than alert { - $sql.= ' AND ('.$sqlalertstock.' > 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; + $sql.= ' AND ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; $alertchecked = 'checked'; } } diff --git a/htdocs/product/traduction.php b/htdocs/product/traduction.php index 791da80c05d..fd13aee1ea2 100644 --- a/htdocs/product/traduction.php +++ b/htdocs/product/traduction.php @@ -200,7 +200,7 @@ if (! empty($object->multilangs)) dol_fiche_head($head, 'translation', $titre, 0, $picto); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; $shownav = 1; if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; diff --git a/htdocs/projet/activity/perday.php b/htdocs/projet/activity/perday.php index b767c35e329..39c3be794b0 100644 --- a/htdocs/projet/activity/perday.php +++ b/htdocs/projet/activity/perday.php @@ -32,6 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; $langs->load('projects'); $langs->load('users'); @@ -81,13 +82,13 @@ else if ($year && $month && $day) $daytoparse=dol_mktime(0, 0, 0, $month, $day, if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) { - $usertoprocess=$user; + $usertoprocess=$user; $search_usertoprocessid=$usertoprocess->id; } elseif ($search_usertoprocessid > 0) { - $usertoprocess=new User($db); - $usertoprocess->fetch($search_usertoprocessid); + $usertoprocess=new User($db); + $usertoprocess->fetch($search_usertoprocessid); $search_usertoprocessid=$usertoprocess->id; } else @@ -105,17 +106,17 @@ $object=new Task($db); // Purge criteria if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $action = ''; - $search_categ=''; - $search_usertoprocessid = $user->id; - $search_task_ref = ''; - $search_task_label = ''; - $search_project_ref = ''; - $search_thirdparty = ''; + $action = ''; + $search_categ=''; + $search_usertoprocessid = $user->id; + $search_task_ref = ''; + $search_task_label = ''; + $search_project_ref = ''; + $search_thirdparty = ''; } if (GETPOST("button_search_x",'alpha') || GETPOST("button_search.x",'alpha') || GETPOST("button_search",'alpha')) { - $action = ''; + $action = ''; } if (GETPOST('submitdateselect')) @@ -128,57 +129,57 @@ if (GETPOST('submitdateselect')) if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')) { - $action = 'assigntask'; + $action = 'assigntask'; - if ($taskid > 0) - { + if ($taskid > 0) + { $result = $object->fetch($taskid, $ref); if ($result < 0) $error++; - } - else - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); - $error++; - } - if (! GETPOST('type')) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); - $error++; - } - if (! $error) - { - $idfortaskuser=$usertoprocess->id; + } + else + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); + $error++; + } + if (! GETPOST('type')) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); + $error++; + } + if (! $error) + { + $idfortaskuser=$usertoprocess->id; $result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal'); - if ($result >= 0 || $result == -2) // Contact add ok or already contact of task - { + if ($result >= 0 || $result == -2) // Contact add ok or already contact of task + { // Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project) - $sql='SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; - $sql.=' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; - $resql=$db->query($sql); - if ($resql) - { - $obj=$db->fetch_object($resql); - if (! $obj) // User is not already linked to project, so we will create link to first type - { - $project = new Project($db); - $project->fetch($object->fk_project); - // Get type - $listofprojcontact=$project->liste_type_contact('internal'); + $sql='SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; + $sql.=' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; + $resql=$db->query($sql); + if ($resql) + { + $obj=$db->fetch_object($resql); + if (! $obj) // User is not already linked to project, so we will create link to first type + { + $project = new Project($db); + $project->fetch($object->fk_project); + // Get type + $listofprojcontact=$project->liste_type_contact('internal'); - if (count($listofprojcontact)) - { - $typeforprojectcontact=reset(array_keys($listofprojcontact)); - $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); - } - } - } - else - { - dol_print_error($db); - } - } - } + if (count($listofprojcontact)) + { + $typeforprojectcontact=reset(array_keys($listofprojcontact)); + $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); + } + } + } + else + { + dol_print_error($db); + } + } + } if ($result < 0) { @@ -205,48 +206,48 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') if ($action == 'addtime' && $user->rights->projet->lire) { - $timespent_duration=array(); + $timespent_duration=array(); - if (is_array($_POST)) - { - foreach($_POST as $key => $time) - { - if (intval($time) > 0) - { - // Hours or minutes of duration - if (preg_match("/([0-9]+)duration(hour|min)/",$key,$matches)) - { - $id = $matches[1]; - if ($id > 0) - { - // We store HOURS in seconds - if($matches[2]=='hour') $timespent_duration[$id] += $time*60*60; - - // We store MINUTES in seconds - if($matches[2]=='min') $timespent_duration[$id] += $time*60; - } - } - } - } - } - - if (count($timespent_duration) > 0) - { - foreach($timespent_duration as $key => $val) - { - $object->fetch($key); - $object->progress = GETPOST($key.'progress', 'int'); - $object->timespent_duration = $val; - $object->timespent_fk_user = $user->id; - $object->timespent_note = GETPOST($key.'note'); - if (GETPOST($key."hour") != '' && GETPOST($key."hour") >= 0) // If hour was entered - { - $object->timespent_datehour = dol_mktime(GETPOST($key."hour"),GETPOST($key."min"),0,$monthofday,$dayofday,$yearofday); - $object->timespent_withhour = 1; - } - else + if (is_array($_POST)) + { + foreach($_POST as $key => $time) + { + if (intval($time) > 0) { - $object->timespent_datehour = dol_mktime(12,0,0,$monthofday,$dayofday,$yearofday); + // Hours or minutes of duration + if (preg_match("/([0-9]+)duration(hour|min)/",$key,$matches)) + { + $id = $matches[1]; + if ($id > 0) + { + // We store HOURS in seconds + if($matches[2]=='hour') $timespent_duration[$id] += $time*60*60; + + // We store MINUTES in seconds + if($matches[2]=='min') $timespent_duration[$id] += $time*60; + } + } + } + } + } + + if (count($timespent_duration) > 0) + { + foreach($timespent_duration as $key => $val) + { + $object->fetch($key); + $object->progress = GETPOST($key.'progress', 'int'); + $object->timespent_duration = $val; + $object->timespent_fk_user = $user->id; + $object->timespent_note = GETPOST($key.'note'); + if (GETPOST($key."hour") != '' && GETPOST($key."hour") >= 0) // If hour was entered + { + $object->timespent_datehour = dol_mktime(GETPOST($key."hour"),GETPOST($key."min"),0,$monthofday,$dayofday,$yearofday); + $object->timespent_withhour = 1; + } + else + { + $object->timespent_datehour = dol_mktime(12,0,0,$monthofday,$dayofday,$yearofday); } $object->timespent_date = $object->timespent_datehour; @@ -267,21 +268,21 @@ if ($action == 'addtime' && $user->rights->projet->lire) $error++; break; } - } + } - if (! $error) - { - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + if (! $error) + { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - // Redirect to avoid submit twice on back - header('Location: '.$_SERVER["PHP_SELF"].'?'.($projectid?'id='.$projectid:'').($search_usertoprocessid?'&search_usertoprocessid='.$search_usertoprocessid:'').($mode?'&mode='.$mode:'').'&year='.$yearofday.'&month='.$monthofday.'&day='.$dayofday); - exit; - } - } - else - { - setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); - } + // Redirect to avoid submit twice on back + header('Location: '.$_SERVER["PHP_SELF"].'?'.($projectid?'id='.$projectid:'').($search_usertoprocessid?'&search_usertoprocessid='.$search_usertoprocessid:'').($mode?'&mode='.$mode:'').'&year='.$yearofday.'&month='.$monthofday.'&day='.$dayofday); + exit; + } + } + else + { + setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); + } } @@ -317,15 +318,16 @@ $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess,(e if ($id) { - $project->fetch($id); - $project->fetch_thirdparty(); + $project->fetch($id); + $project->fetch_thirdparty(); } $onlyopenedproject=1; // or -1 $morewherefilter=''; -if ($search_task_ref) $morewherefilter.=natural_search("t.ref", $search_task_ref); -if ($search_task_label) $morewherefilter.=natural_search("t.label", $search_task_label); +if ($search_task_ref) $morewherefilter.=natural_search("t.ref", $search_task_ref); +if ($search_task_label) $morewherefilter.=natural_search(array("t.ref", "t.label"), $search_task_label); if ($search_thirdparty) $morewherefilter.=natural_search("s.nom", $search_thirdparty); + $tasksarray=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid?$search_usertoprocessid:0)); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. $projectsrole=$taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id?$project->id:0), 0, $onlyopenedproject); $tasksrole=$taskstatic->getUserRolesForProjectsOrTasks(0, $usertoprocess, ($project->id?$project->id:0), 0, $onlyopenedproject); @@ -333,8 +335,7 @@ $tasksrole=$taskstatic->getUserRolesForProjectsOrTasks(0, $usertoprocess, ($proj //var_dump($projectsrole); //var_dump($taskrole); - -llxHeader("",$title,""); +llxHeader("",$title,"",'','','',array('/core/js/timesheet.js')); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num, '', 'title_project'); @@ -395,8 +396,8 @@ dol_fiche_end(); print '
    '.$nav.'
    '; // We move this before the assign to components so, the default submit button is not the assign to. print '
    '; -$titleassigntask = $langs->trans("AssignTaskToMe"); -if ($usertoprocess->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", $usertoprocess->getFullName($langs)); +$titleassigntask = $langs->transnoentities("AssignTaskToMe"); +if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); print '
    '; $formproject->selectTasks($socid?$socid:-1, $taskid, 'taskid', 32, 0, 1, 1); print '
    '; @@ -444,8 +445,8 @@ print ''; print ''; -if (! empty($conf->global->PROJECT_LINES_PERDAY_SHOW_THIRDPARTY)) print ''; -print ''; +print ''; +//print ''; print ''; print ''; print ''; @@ -462,13 +463,10 @@ print ''; print "\n"; print ''; -print ''; -if (! empty($conf->global->PROJECT_LINES_PERDAY_SHOW_THIRDPARTY)) -{ - print ''; -} -print ''; -print ''; +print ''; +print ''; +//print ''; +print ''; print ''; print ''; /*print ''; @@ -478,7 +476,7 @@ print ''; print ''; print ''; -print ''; +print ''; print ''; print "\n"; @@ -486,10 +484,29 @@ print "\n"; // By default, we can edit only tasks we are assigned to $restrictviewformytask=(empty($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)?1:0); +// Get if user is available or not for each day +$holiday = new Holiday($db); +$isavailable=array(); + +$isavailablefordayanduser = $holiday->verifDateHolidayForTimestamp($usertoprocess->id, $daytoparse); // $daytoparse is a date with hours = 0 +$isavailable[$daytoparse]=$isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day + if (count($tasksarray) > 0) { $j=0; - projectLinesPerDay($j, 0, $usertoprocess, $tasksarray, $level, $projectsrole, $tasksrole, $mine, $restrictviewformytask, $daytoparse); + projectLinesPerDay($j, 0, $usertoprocess, $tasksarray, $level, $projectsrole, $tasksrole, $mine, $restrictviewformytask, $daytoparse, $isavailable); + + $colspan = 8; + + print ' + + + + + '; } else { @@ -498,17 +515,30 @@ else print "
    '.$langs->trans("ProjectRef").''.$langs->trans("ThirdParty").''.$langs->trans("RefTask").''.$langs->trans("LabelTask").''.$langs->trans("Project").''.$langs->trans("ThirdParty").''.$langs->trans("RefTask").''.$langs->trans("Task").''.$langs->trans("PlannedWorkload").''.$langs->trans("ProgressDeclared").''.$langs->trans("TimeSpent").''.$langs->trans("TimeSpent").'
    ( print '
    '.$langs->trans("TimeSpent").''.$langs->trans("HourStart").''.$langs->trans("Duration").''.$langs->trans("Note").''.$langs->trans("Note").'
    '; + print $langs->trans("Total"); + //print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; + print '
     
    "; print '
    '; +print ''."\n"; + print '
    '; print ''; print '
    '; print ''; +$modeinput='hours'; -print ''; diff --git a/htdocs/projet/activity/perweek.php b/htdocs/projet/activity/perweek.php index 438d71cbdba..b7fc2b32376 100644 --- a/htdocs/projet/activity/perweek.php +++ b/htdocs/projet/activity/perweek.php @@ -32,6 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; $langs->load('projects'); $langs->load('users'); @@ -94,13 +95,13 @@ $lastdaytoshow=dol_time_plus_duree($firstdaytoshow, 7, 'd'); if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) { - $usertoprocess=$user; + $usertoprocess=$user; $search_usertoprocessid=$usertoprocess->id; } elseif ($search_usertoprocessid > 0) { - $usertoprocess=new User($db); - $usertoprocess->fetch($search_usertoprocessid); + $usertoprocess=new User($db); + $usertoprocess->fetch($search_usertoprocessid); $search_usertoprocessid=$usertoprocess->id; } else @@ -118,17 +119,17 @@ $object=new Task($db); // Purge criteria if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $action = ''; - $search_categ=''; - $search_usertoprocessid = $user->id; - $search_task_ref = ''; - $search_task_label = ''; - $search_project_ref = ''; - $search_thirdparty = ''; + $action = ''; + $search_categ=''; + $search_usertoprocessid = $user->id; + $search_task_ref = ''; + $search_task_label = ''; + $search_project_ref = ''; + $search_thirdparty = ''; } if (GETPOST("button_search_x",'alpha') || GETPOST("button_search.x",'alpha') || GETPOST("button_search",'alpha')) { - $action = ''; + $action = ''; } if (GETPOST('submitdateselect')) @@ -140,58 +141,58 @@ if (GETPOST('submitdateselect')) if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')) { - $action = 'assigntask'; + $action = 'assigntask'; - if ($taskid > 0) - { + if ($taskid > 0) + { $result = $object->fetch($taskid, $ref); if ($result < 0) $error++; - } - else - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); - $error++; - } - if (! GETPOST('type')) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); - $error++; - } + } + else + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); + $error++; + } + if (! GETPOST('type')) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); + $error++; + } - if (! $error) - { - $idfortaskuser=$usertoprocess->id; - $result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal'); + if (! $error) + { + $idfortaskuser=$usertoprocess->id; + $result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal'); - if ($result >= 0 || $result == -2) // Contact add ok or already contact of task - { - // Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project) - $sql='SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; - $sql.=' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; - $resql=$db->query($sql); - if ($resql) - { - $obj=$db->fetch_object($resql); - if (! $obj) // User is not already linked to project, so we will create link to first type - { - $project = new Project($db); - $project->fetch($object->fk_project); - // Get type - $listofprojcontact=$project->liste_type_contact('internal'); + if ($result >= 0 || $result == -2) // Contact add ok or already contact of task + { + // Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project) + $sql='SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; + $sql.=' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; + $resql=$db->query($sql); + if ($resql) + { + $obj=$db->fetch_object($resql); + if (! $obj) // User is not already linked to project, so we will create link to first type + { + $project = new Project($db); + $project->fetch($object->fk_project); + // Get type + $listofprojcontact=$project->liste_type_contact('internal'); - if (count($listofprojcontact)) - { - $typeforprojectcontact=reset(array_keys($listofprojcontact)); - $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); - } - } - } - else - { - dol_print_error($db); - } - } - } + if (count($listofprojcontact)) + { + $typeforprojectcontact=reset(array_keys($listofprojcontact)); + $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); + } + } + } + else + { + dol_print_error($db); + } + } + } if ($result < 0) { @@ -218,35 +219,35 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') if ($action == 'addtime' && $user->rights->projet->lire) { - $timetoadd=$_POST['task']; + $timetoadd=$_POST['task']; if (empty($timetoadd)) { - setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); - } + setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); + } else { foreach($timetoadd as $taskid => $value) // Loop on each task - { - $updateoftaskdone=0; + { + $updateoftaskdone=0; foreach($value as $key => $val) // Loop on each day { $amountoadd=$timetoadd[$taskid][$key]; - if (! empty($amountoadd)) - { - $tmpduration=explode(':',$amountoadd); - $newduration=0; + if (! empty($amountoadd)) + { + $tmpduration=explode(':',$amountoadd); + $newduration=0; if (! empty($tmpduration[0])) $newduration+=($tmpduration[0] * 3600); if (! empty($tmpduration[1])) $newduration+=($tmpduration[1] * 60); if (! empty($tmpduration[2])) $newduration+=($tmpduration[2]); - if ($newduration > 0) - { - $object->fetch($taskid); - $object->progress = GETPOST($taskid . 'progress', 'int'); - $object->timespent_duration = $newduration; - $object->timespent_fk_user = $usertoprocess->id; - $object->timespent_date = dol_time_plus_duree($firstdaytoshow, $key, 'd'); - $object->timespent_datehour = $object->timespent_date; + if ($newduration > 0) + { + $object->fetch($taskid); + $object->progress = GETPOST($taskid . 'progress', 'int'); + $object->timespent_duration = $newduration; + $object->timespent_fk_user = $usertoprocess->id; + $object->timespent_date = dol_time_plus_duree($firstdaytoshow, $key, 'd'); + $object->timespent_datehour = $object->timespent_date; $result=$object->addTimeSpent($user); if ($result < 0) @@ -257,31 +258,31 @@ if ($action == 'addtime' && $user->rights->projet->lire) } $updateoftaskdone++; - } - } + } + } } if (! $updateoftaskdone) // Check to update progress if no update were done on task. { - $object->fetch($taskid); - //var_dump($object->progress);var_dump(GETPOST($taskid . 'progress', 'int')); exit; - if ($object->progress != GETPOST($taskid . 'progress', 'int')) - { - $object->progress = GETPOST($taskid . 'progress', 'int'); - $result=$object->update($user); - if ($result < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - break; - } - } + $object->fetch($taskid); + //var_dump($object->progress);var_dump(GETPOST($taskid . 'progress', 'int')); exit; + if ($object->progress != GETPOST($taskid . 'progress', 'int')) + { + $object->progress = GETPOST($taskid . 'progress', 'int'); + $result=$object->update($user); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + break; + } + } } - } + } if (! $error) { - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $param=''; $param.=($mode?'&mode='.$mode:''); @@ -321,14 +322,14 @@ $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess,(e //var_dump($projectsListId); if ($id) { - $project->fetch($id); - $project->fetch_thirdparty(); + $project->fetch($id); + $project->fetch_thirdparty(); } $onlyopenedproject=1; // or -1 $morewherefilter=''; -if ($search_task_ref) $morewherefilter.=natural_search("t.ref", $search_task_ref); -if ($search_task_label) $morewherefilter.=natural_search("t.label", $search_task_label); +if ($search_task_ref) $morewherefilter.=natural_search("t.ref", $search_task_ref); +if ($search_task_label) $morewherefilter.=natural_search(array("t.ref", "t.label"), $search_task_label); if ($search_thirdparty) $morewherefilter.=natural_search("s.nom", $search_thirdparty); $tasksarray=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid?$search_usertoprocessid:0)); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. @@ -398,8 +399,8 @@ dol_fiche_end(); print '
    '.$nav.'
    '; // We move this before the assign to components so, the default submit button is not the assign to. print '
    '; -$titleassigntask = $langs->trans("AssignTaskToMe"); -if ($usertoprocess->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", $usertoprocess->getFullName($langs)); +$titleassigntask = $langs->transnoentities("AssignTaskToMe"); +if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); print '
    '; $formproject->selectTasks($socid?$socid:-1, $taskid, 'taskid', 32, 0, 1, 1); print '
    '; @@ -448,8 +449,8 @@ print ''; print ''; -if (! empty($conf->global->PROJECT_LINES_PERWEEK_SHOW_THIRDPARTY)) print ''; -print ''; +print ''; +//print ''; print ''; print ''; print ''; @@ -457,7 +458,7 @@ print ''; print ''; for($i=0;$i<7;$i++) { - print ''; + print ''; } // Action column print ''; print "\n"; print ''; -print ''; -if (! empty($conf->global->PROJECT_LINES_PERWEEK_SHOW_THIRDPARTY)) -{ - print ''; -} -print ''; -print ''; +print ''; +print ''; +//print ''; +print ''; print ''; print ''; /*print ''; @@ -484,9 +482,25 @@ print '' $startday=dol_mktime(12, 0, 0, $startdayarray['first_month'], $startdayarray['first_day'], $startdayarray['first_year']); -for($i=0;$i<7;$i++) +// Get if user is available or not for each day +$holiday = new Holiday($db); +$isavailable=array(); + +for ($i=0;$i<7;$i++) { - print ''; + $dayinloopfromfirstdaytoshow = dol_time_plus_duree($firstdaytoshow, $i, 'd'); // $firstdaytoshow is a date with hours = 0 + $dayinloop = dol_time_plus_duree($startday, $i, 'd'); + + // Useless because $dayinloopwithouthours should be same than $dayinloopfromfirstdaytoshow + //$tmparray = dol_getdate($dayinloop); + //$dayinloopwithouthours=dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); + //print dol_print_date($dayinloop, 'dayhour').' '; + //print dol_print_date($dayinloopwithouthours, 'dayhour').' '; + //print dol_print_date($dayinloopfromfirstdaytoshow, 'dayhour').'
    '; + + $isavailablefordayanduser = $holiday->verifDateHolidayForTimestamp($usertoprocess->id, $dayinloopfromfirstdaytoshow); + $isavailable[$dayinloopfromfirstdaytoshow]=$isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day + print ''; } print ''; print "\n"; @@ -496,18 +510,20 @@ $restrictviewformytask=(empty($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED if (count($tasksarray) > 0) { - //var_dump($tasksarray); - //var_dump($tasksrole); + //var_dump($tasksarray); + //var_dump($tasksrole); $j=0; $level=0; - projectLinesPerWeek($j, $firstdaytoshow, $usertoprocess, 0, $tasksarray, $level, $projectsrole, $tasksrole, $mine, $restrictviewformytask); + projectLinesPerWeek($j, $firstdaytoshow, $usertoprocess, 0, $tasksarray, $level, $projectsrole, $tasksrole, $mine, $restrictviewformytask, $isavailable); $colspan=7; - if (! empty($conf->global->PROJECT_LINES_PERWEEK_SHOW_THIRDPARTY)) $colspan++; print ' - + @@ -520,12 +536,11 @@ if (count($tasksarray) > 0) } else { - print ''; + print ''; } print "
    '; @@ -467,13 +468,10 @@ print '
    '.$langs->trans("ProjectRef").''.$langs->trans("ThirdParty").''.$langs->trans("RefTask").''.$langs->trans("LabelTask").''.$langs->trans("Project").''.$langs->trans("ThirdParty").''.$langs->trans("RefTask").''.$langs->trans("Task").''.$langs->trans("PlannedWorkload").''.$langs->trans("ProgressDeclared").''.$langs->trans("TimeSpent").''.$langs->trans("TimeSpent").''.dol_print_date($startday + ($i * 3600 * 24), '%a').'
    '.dol_print_date($startday + ($i * 3600 * 24), 'dayreduceformat').'
    '.dol_print_date($dayinloopfromfirstdaytoshow, '%a').'
    '.dol_print_date($dayinloopfromfirstdaytoshow, 'dayreduceformat').'
    '.$langs->trans("Total").''; + print $langs->trans("Total"); + print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; + print '
     
     
     
    '.$langs->trans("NoTasks").'
    '.$langs->trans("NoTasks").'
    "; print '
    '; -print ''."\n"; print ''."\n"; print '
    '; @@ -536,16 +551,24 @@ print ''."\n\n"; $modeinput='hours'; -print ''; diff --git a/htdocs/projet/admin/project.php b/htdocs/projet/admin/project.php index 744e52e0f2f..b9778b73a42 100644 --- a/htdocs/projet/admin/project.php +++ b/htdocs/projet/admin/project.php @@ -912,12 +912,33 @@ print ''; print ''; print ''.$langs->trans("AllowToSelectProjectFromOtherCompany").''; -print ''; +print ' '; +print ''; echo ajax_constantonoff('PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY'); print ''; +print ''; + +/* Kept as hidden feature because this will be "probaly be supported by standard event feature in a future + +print ''; +print ''.$langs->trans("AllowCommentOnProject").''; + +print ''; +echo ajax_constantonoff('PROJECT_ALLOW_COMMENT_ON_PROJECT'); +print ''; print ' '; print ''; +print ''; +print ''.$langs->trans("AllowCommentOnTask").''; + +print ''; +echo ajax_constantonoff('PROJECT_ALLOW_COMMENT_ON_TASK'); +print ''; +print ' '; +print ''; +*/ + print ''; diff --git a/htdocs/projet/admin/project_extrafields.php b/htdocs/projet/admin/project_extrafields.php index 26a6286f034..eb27110e88c 100644 --- a/htdocs/projet/admin/project_extrafields.php +++ b/htdocs/projet/admin/project_extrafields.php @@ -39,7 +39,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/projet/admin/project_task_extrafields.php b/htdocs/projet/admin/project_task_extrafields.php index 58f91e863fc..9f47376d02d 100644 --- a/htdocs/projet/admin/project_task_extrafields.php +++ b/htdocs/projet/admin/project_task_extrafields.php @@ -39,7 +39,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php index 849ea5cd47d..700feba4bd8 100644 --- a/htdocs/projet/card.php +++ b/htdocs/projet/card.php @@ -61,11 +61,11 @@ $extrafields = new ExtraFields($db); //include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Can't use generic include because when creating a project, ref is defined and we dont want error if fetch fails from ref. if ($id > 0 || ! empty($ref)) { - $ret = $object->fetch($id,$ref); // If we create project, ref may be defined into POST but record does not yet exists into database - if ($ret > 0) { - $object->fetch_thirdparty(); - $id=$object->id; - } + $ret = $object->fetch($id,$ref); // If we create project, ref may be defined into POST but record does not yet exists into database + if ($ret > 0) { + $object->fetch_thirdparty(); + $id=$object->id; + } } // Security check @@ -95,22 +95,22 @@ if (empty($reshook)) { if (GETPOST("comefromclone")==1) { - $result=$object->delete($user); - if ($result > 0) - { - header("Location: index.php"); - exit; - } - else - { - dol_syslog($object->error,LOG_DEBUG); - setEventMessages($langs->trans("CantRemoveProject"), null, 'errors'); - } + $result=$object->delete($user); + if ($result > 0) + { + header("Location: index.php"); + exit; + } + else + { + dol_syslog($object->error,LOG_DEBUG); + setEventMessages($langs->trans("CantRemoveProject"), null, 'errors'); + } } if ($backtopage) { - header("Location: ".$backtopage); - exit; + header("Location: ".$backtopage); + exit; } $action = ''; @@ -118,217 +118,217 @@ if (empty($reshook)) if ($action == 'add' && $user->rights->projet->creer) { - $error=0; - if (empty($_POST["ref"])) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); - $error++; - } - if (empty($_POST["title"])) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); - $error++; - } + $error=0; + if (empty($_POST["ref"])) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); + $error++; + } + if (empty($_POST["title"])) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); + $error++; + } - if (GETPOST('opp_amount') != '' && ! (GETPOST('opp_status') > 0)) - { - $error++; - setEventMessages($langs->trans("ErrorOppStatusRequiredIfAmount"), null, 'errors'); - } + if (GETPOST('opp_amount') != '' && ! (GETPOST('opp_status') > 0)) + { + $error++; + setEventMessages($langs->trans("ErrorOppStatusRequiredIfAmount"), null, 'errors'); + } - // Create with status validated immediatly - if (! empty($conf->global->PROJECT_CREATE_NO_DRAFT)) - { - $status=Project::STATUS_VALIDATED; - } + // Create with status validated immediatly + if (! empty($conf->global->PROJECT_CREATE_NO_DRAFT)) + { + $status=Project::STATUS_VALIDATED; + } - if (! $error) - { - $error=0; + if (! $error) + { + $error=0; - $db->begin(); + $db->begin(); - $object->ref = GETPOST('ref','alpha'); - $object->title = GETPOST('title','none'); // Do not use 'alpha' here, we want field as it is - $object->socid = GETPOST('socid','int'); - $object->description = GETPOST('description','none'); // Do not use 'alpha' here, we want field as it is - $object->public = GETPOST('public','alpha'); - $object->opp_amount = price2num(GETPOST('opp_amount')); - $object->budget_amount = price2num(GETPOST('budget_amount')); - $object->datec = dol_now(); - $object->date_start = $date_start; - $object->date_end = $date_end; - $object->statut = $status; - $object->opp_status = $opp_status; - $object->opp_percent = $opp_percent; + $object->ref = GETPOST('ref','alpha'); + $object->title = GETPOST('title','none'); // Do not use 'alpha' here, we want field as it is + $object->socid = GETPOST('socid','int'); + $object->description = GETPOST('description','none'); // Do not use 'alpha' here, we want field as it is + $object->public = GETPOST('public','alpha'); + $object->opp_amount = price2num(GETPOST('opp_amount')); + $object->budget_amount = price2num(GETPOST('budget_amount')); + $object->datec = dol_now(); + $object->date_start = $date_start; + $object->date_end = $date_end; + $object->statut = $status; + $object->opp_status = $opp_status; + $object->opp_percent = $opp_percent; - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); if ($ret < 0) $error++; - $result = $object->create($user); - if (! $error && $result > 0) - { - // Add myself as project leader - $result = $object->add_contact($user->id, 'PROJECTLEADER', 'internal'); - if ($result < 0) - { - $langs->load("errors"); - setEventMessages($langs->trans($object->error), null, 'errors'); - $error++; - } - } - else - { - $langs->load("errors"); - setEventMessages($langs->trans($object->error), null, 'errors'); - $error++; - } - if (! $error && !empty($object->id) > 0) - { - // Category association - $categories = GETPOST('categories'); - $result=$object->setCategories($categories); - if ($result<0) { - $langs->load("errors"); - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } - - if (! $error) - { - $db->commit(); - - if ($backtopage) + $result = $object->create($user); + if (! $error && $result > 0) + { + // Add myself as project leader + $result = $object->add_contact($user->id, 'PROJECTLEADER', 'internal'); + if ($result < 0) { - header("Location: ".$backtopage.'&projectid='.$object->id); - exit; + $langs->load("errors"); + setEventMessages($langs->trans($object->error), null, 'errors'); + $error++; + } + } + else + { + $langs->load("errors"); + setEventMessages($langs->trans($object->error), null, 'errors'); + $error++; + } + if (! $error && !empty($object->id) > 0) + { + // Category association + $categories = GETPOST('categories', 'array'); + $result=$object->setCategories($categories); + if ($result<0) { + $langs->load("errors"); + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } + + if (! $error) + { + $db->commit(); + + if ($backtopage) + { + header("Location: ".$backtopage.'&projectid='.$object->id); + exit; } else { - header("Location:card.php?id=".$object->id); - exit; + header("Location:card.php?id=".$object->id); + exit; } - } - else - { - $db->rollback(); + } + else + { + $db->rollback(); - $action = 'create'; - } - } - else - { - $action = 'create'; - } + $action = 'create'; + } + } + else + { + $action = 'create'; + } } if ($action == 'update' && ! $_POST["cancel"] && $user->rights->projet->creer) { - $error=0; + $error=0; - if (empty($ref)) - { - $error++; - //$_GET["id"]=$_POST["id"]; // We return on the project card - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); - } - if (empty($_POST["title"])) - { - $error++; - //$_GET["id"]=$_POST["id"]; // We return on the project card - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); - } + if (empty($ref)) + { + $error++; + //$_GET["id"]=$_POST["id"]; // We return on the project card + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); + } + if (empty($_POST["title"])) + { + $error++; + //$_GET["id"]=$_POST["id"]; // We return on the project card + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); + } - $db->begin(); + $db->begin(); - if (! $error) - { + if (! $error) + { $object->oldcopy = clone $object; $old_start_date = $object->date_start; - $object->ref = GETPOST('ref','alpha'); - $object->title = GETPOST('title','none'); // Do not use 'alpha' here, we want field as it is - $object->socid = GETPOST('socid','int'); - $object->description = GETPOST('description','none'); // Do not use 'alpha' here, we want field as it is - $object->public = GETPOST('public','alpha'); - $object->date_start = empty($_POST["projectstart"])?'':$date_start; - $object->date_end = empty($_POST["projectend"])?'':$date_end; - if (isset($_POST['opp_amount'])) $object->opp_amount = price2num(GETPOST('opp_amount')); - if (isset($_POST['budget_amount'])) $object->budget_amount= price2num(GETPOST('budget_amount')); - if (isset($_POST['opp_status'])) $object->opp_status = $opp_status; - if (isset($_POST['opp_percent'])) $object->opp_percent = $opp_percent; + $object->ref = GETPOST('ref','alpha'); + $object->title = GETPOST('title','none'); // Do not use 'alpha' here, we want field as it is + $object->socid = GETPOST('socid','int'); + $object->description = GETPOST('description','none'); // Do not use 'alpha' here, we want field as it is + $object->public = GETPOST('public','alpha'); + $object->date_start = empty($_POST["projectstart"])?'':$date_start; + $object->date_end = empty($_POST["projectend"])?'':$date_end; + if (isset($_POST['opp_amount'])) $object->opp_amount = price2num(GETPOST('opp_amount')); + if (isset($_POST['budget_amount'])) $object->budget_amount= price2num(GETPOST('budget_amount')); + if (isset($_POST['opp_status'])) $object->opp_status = $opp_status; + if (isset($_POST['opp_percent'])) $object->opp_percent = $opp_percent; - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); if ($ret < 0) $error++; - } + } if ($object->opp_amount && ($object->opp_status <= 0)) - { - $error++; - setEventMessages($langs->trans("ErrorOppStatusRequiredIfAmount"), null, 'errors'); - } + { + $error++; + setEventMessages($langs->trans("ErrorOppStatusRequiredIfAmount"), null, 'errors'); + } - if (! $error) - { - $result=$object->update($user); - if ($result < 0) - { - $error++; - if ($result == -4) setEventMessages($langs->trans("ErrorRefAlreadyExists"), null, 'errors'); - else setEventMessages($object->error, $object->errors, 'errors'); - }else { - // Category association - $categories = GETPOST('categories'); - $result=$object->setCategories($categories); - if ($result < 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } - } - } + if (! $error) + { + $result=$object->update($user); + if ($result < 0) + { + $error++; + if ($result == -4) setEventMessages($langs->trans("ErrorRefAlreadyExists"), null, 'errors'); + else setEventMessages($object->error, $object->errors, 'errors'); + }else { + // Category association + $categories = GETPOST('categories', 'array'); + $result=$object->setCategories($categories); + if ($result < 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } - if (! $error) - { - if (GETPOST("reportdate") && ($object->date_start!=$old_start_date)) - { - $result=$object->shiftTaskDate($old_start_date); - if ($result < 0) - { - $error++; - setEventMessages($langs->trans("ErrorShiftTaskDate").':'.$object->error, $object->errors, 'errors'); - } - } - } + if (! $error) + { + if (GETPOST("reportdate") && ($object->date_start!=$old_start_date)) + { + $result=$object->shiftTaskDate($old_start_date); + if ($result < 0) + { + $error++; + setEventMessages($langs->trans("ErrorShiftTaskDate").':'.$object->error, $object->errors, 'errors'); + } + } + } // Check if we must change status - if (GETPOST('closeproject')) - { - $resclose = $object->setClose($user); - if ($resclose < 0) - { - $error++; - setEventMessages($langs->trans("FailedToCloseProject").':'.$object->error, $object->errors, 'errors'); - } - } - - - if ($error) - { - $db->rollback(); - $action='edit'; - } - else + if (GETPOST('closeproject')) { - $db->commit(); + $resclose = $object->setClose($user); + if ($resclose < 0) + { + $error++; + setEventMessages($langs->trans("FailedToCloseProject").':'.$object->error, $object->errors, 'errors'); + } + } + + + if ($error) + { + $db->rollback(); + $action='edit'; + } + else + { + $db->commit(); if (GETPOST('socid','int') > 0) $object->fetch_thirdparty(GETPOST('socid','int')); else unset($object->thirdparty); - } + } } @@ -338,25 +338,25 @@ if (empty($reshook)) // Save last template used to generate document if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha')); - $outputlangs = $langs; - if (GETPOST('lang_id','aZ09')) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang(GETPOST('lang_id','aZ09')); - } - $result= $object->generateDocument($object->modelpdf, $outputlangs); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $action=''; - } + $outputlangs = $langs; + if (GETPOST('lang_id','aZ09')) + { + $outputlangs = new Translate("",$conf); + $outputlangs->setDefaultLang(GETPOST('lang_id','aZ09')); + } + $result= $object->generateDocument($object->modelpdf, $outputlangs); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $action=''; + } } // Delete file in doc form if ($action == 'remove_file' && $user->rights->projet->creer) { - if ($object->id > 0) - { + if ($object->id > 0) + { require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; $langs->load("other"); @@ -368,80 +368,80 @@ if (empty($reshook)) else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); $action = ''; - } + } } if ($action == 'confirm_validate' && $confirm == 'yes') { - $result = $object->setValid($user); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->setValid($user); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'confirm_close' && $confirm == 'yes') { - $result = $object->setClose($user); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->setClose($user); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'confirm_reopen' && $confirm == 'yes') { - $result = $object->setValid($user); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->setValid($user); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'confirm_delete' && GETPOST("confirm") == "yes" && $user->rights->projet->supprimer) { - $object->fetch($id); - $result=$object->delete($user); - if ($result > 0) - { - setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); - header("Location: index.php"); - exit; - } - else - { - dol_syslog($object->error,LOG_DEBUG); - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->fetch($id); + $result=$object->delete($user); + if ($result > 0) + { + setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); + header("Location: index.php"); + exit; + } + else + { + dol_syslog($object->error,LOG_DEBUG); + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'confirm_clone' && $user->rights->projet->creer && $confirm == 'yes') { - $clone_contacts=GETPOST('clone_contacts')?1:0; - $clone_tasks=GETPOST('clone_tasks')?1:0; + $clone_contacts=GETPOST('clone_contacts')?1:0; + $clone_tasks=GETPOST('clone_tasks')?1:0; $clone_project_files = GETPOST('clone_project_files') ? 1 : 0; $clone_task_files = GETPOST('clone_task_files') ? 1 : 0; - $clone_notes=GETPOST('clone_notes')?1:0; - $move_date=GETPOST('move_date')?1:0; - $clone_thirdparty=GETPOST('socid','int')?GETPOST('socid','int'):0; + $clone_notes=GETPOST('clone_notes')?1:0; + $move_date=GETPOST('move_date')?1:0; + $clone_thirdparty=GETPOST('socid','int')?GETPOST('socid','int'):0; - $result=$object->createFromClone($object->id,$clone_contacts,$clone_tasks,$clone_project_files,$clone_task_files,$clone_notes,$move_date,0,$clone_thirdparty); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } - else - { - // Load new object - $newobject=new Project($db); - $newobject->fetch($result); - $newobject->fetch_optionals(); - $newobject->fetch_thirdparty(); // Load new object - $object=$newobject; - $action='edit'; - $comefromclone=true; - } + $result=$object->createFromClone($object->id,$clone_contacts,$clone_tasks,$clone_project_files,$clone_task_files,$clone_notes,$move_date,0,$clone_thirdparty); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } + else + { + // Load new object + $newobject=new Project($db); + $newobject->fetch($result); + $newobject->fetch_optionals(); + $newobject->fetch_thirdparty(); // Load new object + $object=$newobject; + $action='edit'; + $comefromclone=true; + } } } @@ -464,180 +464,180 @@ llxHeader("",$title,$help_url); if ($action == 'create' && $user->rights->projet->creer) { - /* + /* * Create */ $thirdparty=new Societe($db); if ($socid > 0) $thirdparty->fetch($socid); - print load_fiche_titre($langs->trans("NewProject"), '', 'title_project'); + print load_fiche_titre($langs->trans("NewProject"), '', 'title_project'); - print '
    '; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
    '; - $defaultref=''; - $modele = empty($conf->global->PROJECT_ADDON)?'mod_project_simple':$conf->global->PROJECT_ADDON; + $defaultref=''; + $modele = empty($conf->global->PROJECT_ADDON)?'mod_project_simple':$conf->global->PROJECT_ADDON; - // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) - { - $file=dol_buildpath($reldir."core/modules/project/".$modele.'.php',0); - if (file_exists($file)) - { - $filefound=1; - $classname = $modele; - break; - } - } + // Search template files + $file=''; $classname=''; $filefound=0; + $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); + foreach($dirmodels as $reldir) + { + $file=dol_buildpath($reldir."core/modules/project/".$modele.'.php',0); + if (file_exists($file)) + { + $filefound=1; + $classname = $modele; + break; + } + } - if ($filefound) - { - $result=dol_include_once($reldir."core/modules/project/".$modele.'.php'); - $modProject = new $classname; + if ($filefound) + { + $result=dol_include_once($reldir."core/modules/project/".$modele.'.php'); + $modProject = new $classname; - $defaultref = $modProject->getNextValue($thirdparty,$object); - } + $defaultref = $modProject->getNextValue($thirdparty,$object); + } - if (is_numeric($defaultref) && $defaultref <= 0) $defaultref=''; + if (is_numeric($defaultref) && $defaultref <= 0) $defaultref=''; - // Ref - $suggestedref=($_POST["ref"]?$_POST["ref"]:$defaultref); - print ''; + // Ref + $suggestedref=($_POST["ref"]?$_POST["ref"]:$defaultref); + print ''; - // Label - print ''; + // Label + print ''; - // Thirdparty - if ($conf->societe->enabled) - { - print ''; - } + // Thirdparty + if ($conf->societe->enabled) + { + print ''; + } - // Status - if ($status != '') - { - print ''; - } + // Status + if ($status != '') + { + print ''; + } - // Visibility - print ''; + // Visibility + print ''; - // Date start - print ''; + // Date start + print ''; - // Date end - print ''; + // Date end + print ''; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { - // Opportunity status - print ''; - print ''; + if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + { + // Opportunity status + print ''; + print ''; - // Opportunity probability - print ''; - print ''; - print ''; + // Opportunity probability + print ''; + print ''; + print ''; - // Opportunity amount - print ''; - print ''; - print ''; - } + // Opportunity amount + print ''; + print ''; + print ''; + } // Budget print ''; - print ''; + print ''; print ''; - // Description - print ''; - print ''; + // Description + print ''; + print ''; - if ($conf->categorie->enabled) { - // Categories - print '"; - } + if ($conf->categorie->enabled) { + // Categories + print '"; + } - // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) - { - print $object->showOptionals($extrafields,'edit'); - } + // Other options + $parameters=array(); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (empty($reshook) && ! empty($extrafields->attribute_label)) + { + print $object->showOptionals($extrafields,'edit'); + } - print '
    '.$langs->trans("Ref").''; - print ' '.$form->textwithpicto('', $langs->trans("YouCanCompleteRef", $suggestedref)); - print '
    '.$langs->trans("Ref").''; + print ' '.$form->textwithpicto('', $langs->trans("YouCanCompleteRef", $suggestedref)); + print '
    '.$langs->trans("Label").'
    '.$langs->trans("Label").'
    '; - print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED)?'':''); - print $langs->trans("ThirdParty"); - print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED)?'':''); - print ''; - $filteronlist=''; - if (! empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) $filteronlist=$conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; - $text=$form->select_thirdparty_list(GETPOST('socid','int'), 'socid', $filteronlist, 'SelectThirdParty', 1, 0, array(), '', 0, 0, 'minwidth300'); - if (empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) && empty($conf->dol_use_jmobile)) - { - $texthelp=$langs->trans("IfNeedToUseOhterObjectKeepEmpty"); - print $form->textwithtooltip($text.' '.img_help(),$texthelp,1); - } - else print $text; - print ' '.$langs->trans("AddThirdParty").''; - print '
    '; + print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED)?'':''); + print $langs->trans("ThirdParty"); + print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED)?'':''); + print ''; + $filteronlist=''; + if (! empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) $filteronlist=$conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; + $text=$form->select_company(GETPOST('socid','int'), 'socid', $filteronlist, 'SelectThirdParty', 1, 0, array(), 0, 'minwidth300'); + if (empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) && empty($conf->dol_use_jmobile)) + { + $texthelp=$langs->trans("IfNeedToUseOhterObjectKeepEmpty"); + print $form->textwithtooltip($text.' '.img_help(),$texthelp,1); + } + else print $text; + print ' '.$langs->trans("AddThirdParty").''; + print '
    '.$langs->trans("Status").''; - print ''; - print $object->LibStatut($status, 4); - print '
    '.$langs->trans("Status").''; + print ''; + print $object->LibStatut($status, 4); + print '
    '.$langs->trans("Visibility").''; - $array=array(); - if (empty($conf->global->PROJECT_DISABLE_PRIVATE_PROJECT)) $array[0] = $langs->trans("PrivateProject"); - if (empty($conf->global->PROJECT_DISABLE_PUBLIC_PROJECT)) $array[1] = $langs->trans("SharedProject"); - print $form->selectarray('public',$array,GETPOST('public')?GETPOST('public'):(isset($conf->global->PROJECT_DEFAULT_PUBLIC)?$conf->global->PROJECT_DEFAULT_PUBLIC:$object->public)); - print '
    '.$langs->trans("Visibility").''; + $array=array(); + if (empty($conf->global->PROJECT_DISABLE_PRIVATE_PROJECT)) $array[0] = $langs->trans("PrivateProject"); + if (empty($conf->global->PROJECT_DISABLE_PUBLIC_PROJECT)) $array[1] = $langs->trans("SharedProject"); + print $form->selectarray('public',$array,GETPOST('public')?GETPOST('public'):$object->public); + print '
    '.$langs->trans("DateStart").''; - print $form->select_date(($date_start?$date_start:''),'projectstart',0,0,0,'',1,0,1); - print '
    '.$langs->trans("DateStart").''; + print $form->select_date(($date_start?$date_start:''),'projectstart',0,0,0,'',1,0,1); + print '
    '.$langs->trans("DateEnd").''; - print $form->select_date(($date_end?$date_end:-1),'projectend',0,0,0,'',1,0,1); - print '
    '.$langs->trans("DateEnd").''; + print $form->select_date(($date_end?$date_end:-1),'projectend',0,0,0,'',1,0,1); + print '
    '.$langs->trans("OpportunityStatus").''; - print $formproject->selectOpportunityStatus('opp_status', GETPOST('opp_status')?GETPOST('opp_status'):$object->opp_status); - print '
    '.$langs->trans("OpportunityStatus").''; + print $formproject->selectOpportunityStatus('opp_status', GETPOST('opp_status')?GETPOST('opp_status'):$object->opp_status); + print '
    '.$langs->trans("OpportunityProbability").' %'; - print ''; - print '
    '.$langs->trans("OpportunityProbability").' %'; + print ''; + print '
    '.$langs->trans("OpportunityAmount").'
    '.$langs->trans("OpportunityAmount").'
    '.$langs->trans("Budget").'
    '.$langs->trans("Description").''; - print ''; - print '
    '.$langs->trans("Description").''; + print ''; + print '
    '.$langs->trans("Categories").''; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_PROJECT, '', 'parent', 64, 0, 1); - $arrayselected=GETPOST('categories', 'array'); - print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); - print "
    '.$langs->trans("Categories").''; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_PROJECT, '', 'parent', 64, 0, 1); + $arrayselected=GETPOST('categories', 'array'); + print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); + print "
    '; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print '
    '; - print ''; - if (! empty($backtopage)) - { - print '     '; - print ''; - } - else - { - print '     '; - print ''; - } - print '
    '; + print '
    '; + print ''; + if (! empty($backtopage)) + { + print '     '; + print ''; + } + else + { + print '     '; + print ''; + } + print '
    '; - print '
    '; + print ''; - // Change probability from status - print ''; - } + } - /* + /* * Boutons actions */ - print '
    '; - $parameters = array(); - $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook - if (empty($reshook)) - { - if ($action != "edit" ) - { + print '
    '; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been + // modified by hook + if (empty($reshook)) + { + if ($action != "edit" ) + { - // Create event - if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a - // "workflow" action so should appears somewhere else on - // page. - { - print ''; - } + // Create event + if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a + // "workflow" action so should appears somewhere else on + // page. + { + print ''; + } // Modify - if ($object->statut != 2 && $user->rights->projet->creer) - { - if ($userWrite > 0) - { - print ''; - } - else - { - print ''; - } - } + if ($object->statut != 2 && $user->rights->projet->creer) + { + if ($userWrite > 0) + { + print ''; + } + else + { + print ''; + } + } - // Validate - if ($object->statut == 0 && $user->rights->projet->creer) - { - if ($userWrite > 0) - { - print ''; - } - else - { - print ''; - } - } + // Validate + if ($object->statut == 0 && $user->rights->projet->creer) + { + if ($userWrite > 0) + { + print ''; + } + else + { + print ''; + } + } - // Close - if ($object->statut == 1 && $user->rights->projet->creer) - { - if ($userWrite > 0) - { - print ''; - } - else - { - print ''; - } - } + // Close + if ($object->statut == 1 && $user->rights->projet->creer) + { + if ($userWrite > 0) + { + print ''; + } + else + { + print ''; + } + } - // Reopen - if ($object->statut == 2 && $user->rights->projet->creer) - { - if ($userWrite > 0) - { - print ''; - } - else - { - print ''; - } - } + // Reopen + if ($object->statut == 2 && $user->rights->projet->creer) + { + if ($userWrite > 0) + { + print ''; + } + else + { + print ''; + } + } - // Add button to create objects from project - if (! empty($conf->global->PROJECT_SHOW_CREATE_OBJECT_BUTTON)) - { - if (! empty($conf->propal->enabled) && $user->rights->propal->creer) - { - $langs->load("propal"); - print ''; - } - if (! empty($conf->commande->enabled) && $user->rights->commande->creer) - { - $langs->load("orders"); - print ''; - } - if (! empty($conf->facture->enabled) && $user->rights->facture->creer) - { - $langs->load("bills"); - print ''; - } - if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->creer) - { - $langs->load("supplier_proposal"); - print ''; - } - if (! empty($conf->supplier_order->enabled) && $user->rights->fournisseur->commande->creer) - { - $langs->load("suppliers"); - print ''; - } - if (! empty($conf->supplier_invoice->enabled) && $user->rights->fournisseur->facture->creer) - { - $langs->load("suppliers"); - print ''; - } - if (! empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer) - { - $langs->load("interventions"); - print ''; - } - if (! empty($conf->contrat->enabled) && $user->rights->contrat->creer) - { - $langs->load("contracts"); - print ''; - } - if (! empty($conf->expensereport->enabled) && $user->rights->expensereport->creer) - { - $langs->load("trips"); - print ''; - } - if (! empty($conf->don->enabled) && $user->rights->don->creer) - { - $langs->load("donations"); - print ''; - } - } + // Add button to create objects from project + if (! empty($conf->global->PROJECT_SHOW_CREATE_OBJECT_BUTTON)) + { + if (! empty($conf->propal->enabled) && $user->rights->propal->creer) + { + $langs->load("propal"); + print ''; + } + if (! empty($conf->commande->enabled) && $user->rights->commande->creer) + { + $langs->load("orders"); + print ''; + } + if (! empty($conf->facture->enabled) && $user->rights->facture->creer) + { + $langs->load("bills"); + print ''; + } + if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->creer) + { + $langs->load("supplier_proposal"); + print ''; + } + if (! empty($conf->supplier_order->enabled) && $user->rights->fournisseur->commande->creer) + { + $langs->load("suppliers"); + print ''; + } + if (! empty($conf->supplier_invoice->enabled) && $user->rights->fournisseur->facture->creer) + { + $langs->load("suppliers"); + print ''; + } + if (! empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer) + { + $langs->load("interventions"); + print ''; + } + if (! empty($conf->contrat->enabled) && $user->rights->contrat->creer) + { + $langs->load("contracts"); + print ''; + } + if (! empty($conf->expensereport->enabled) && $user->rights->expensereport->creer) + { + $langs->load("trips"); + print ''; + } + if (! empty($conf->don->enabled) && $user->rights->don->creer) + { + $langs->load("donations"); + print ''; + } + } - // Clone - if ($user->rights->projet->creer) - { - if ($userWrite > 0) - { - print ''; - } - else - { - print ''; - } - } + // Clone + if ($user->rights->projet->creer) + { + if ($userWrite > 0) + { + print ''; + } + else + { + print ''; + } + } - // Delete - if ($user->rights->projet->supprimer || ($object->statut == 0 && $user->rights->projet->creer)) - { - if ($userDelete > 0 || ($object->statut == 0 && $user->rights->projet->creer)) - { - print ''; - } - else - { - print ''; - } - } - } - } + // Delete + if ($user->rights->projet->supprimer || ($object->statut == 0 && $user->rights->projet->creer)) + { + if ($userDelete > 0 || ($object->statut == 0 && $user->rights->projet->creer)) + { + print ''; + } + else + { + print ''; + } + } + } + } - print "
    "; + print "
    "; - if ($action != 'presend') - { - print '
    '; - print ''; // ancre + if ($action != 'presend') + { + print '
    '; + print ''; // ancre - /* + /* * Documents generes */ - $filename=dol_sanitizeFileName($object->ref); - $filedir=$conf->projet->dir_output . "/" . dol_sanitizeFileName($object->ref); - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=($user->rights->projet->lire && $userAccess > 0); - $delallowed=($user->rights->projet->creer && $userWrite > 0); + $filename=dol_sanitizeFileName($object->ref); + $filedir=$conf->projet->dir_output . "/" . dol_sanitizeFileName($object->ref); + $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed=($user->rights->projet->lire && $userAccess > 0); + $delallowed=($user->rights->projet->creer && $userWrite > 0); - $var=true; + print $formfile->showdocuments('project',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf); - print $formfile->showdocuments('project',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf); + print '
    '; - print '
    '; + $MAX = 10; - // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; - $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'project', $socid, 1, '', 10); + $morehtmlright = ''; + $morehtmlright.= $langs->trans("SeeAll"); + $morehtmlright.= ''; - 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, 'project', $socid, 1, '', $MAX, '', $morehtmlright); - // Hook to add more things on page - $parameters=array(); - $reshook=$hookmanager->executeHooks('mainCardTabAddMore',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print '
    '; + } + + // Hook to add more things on page + $parameters=array(); + $reshook=$hookmanager->executeHooks('mainCardTabAddMore',$parameters,$object,$action); // Note that $action and $object may have been modified by hook } else { - print $langs->trans("RecordNotFound"); + print $langs->trans("RecordNotFound"); } llxFooter(); diff --git a/htdocs/projet/class/api_projects.class.php b/htdocs/projet/class/api_projects.class.php index c63c4cfbd23..6fcdfde7ca2 100644 --- a/htdocs/projet/class/api_projects.class.php +++ b/htdocs/projet/class/api_projects.class.php @@ -342,7 +342,7 @@ class Projects extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; diff --git a/htdocs/projet/class/api_tasks.class.php b/htdocs/projet/class/api_tasks.class.php index d6303c18a16..f00a536df87 100644 --- a/htdocs/projet/class/api_tasks.class.php +++ b/htdocs/projet/class/api_tasks.class.php @@ -19,7 +19,8 @@ use Luracast\Restler\RestException; require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; - + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + /** * API class for projects * @@ -87,12 +88,12 @@ class Tasks extends DolibarrApi // TODO // Add class for timespent records and loop and fill $line->lines with records of timespent } - + return $this->_cleanObjectDatas($this->task); } - - + + /** * List tasks * @@ -109,7 +110,7 @@ class Tasks extends DolibarrApi global $db, $conf; $obj_ret = array(); - + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid $socids = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $thirdparty_ids; @@ -133,7 +134,7 @@ class Tasks extends DolibarrApi $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) + if ($sqlfilters) { if (! DolibarrApi::_checkFilters($sqlfilters)) { @@ -142,7 +143,7 @@ class Tasks extends DolibarrApi $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - + $sql.= $db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) @@ -235,7 +236,7 @@ class Tasks extends DolibarrApi } $this->project->getLinesArray(DolibarrApiAccess::$user); $result = array(); - foreach ($this->project->lines as $line) // $line is a task + foreach ($this->project->lines as $line) // $line is a task { if ($includetimespent == 1) { @@ -251,7 +252,7 @@ class Tasks extends DolibarrApi return $result; } */ - + /** * Get roles a user is assigned to a task with * @@ -264,20 +265,20 @@ class Tasks extends DolibarrApi */ function getRoles($id, $userid=0) { global $db; - + if(! DolibarrApiAccess::$user->rights->projet->lire) { throw new RestException(401); } - + $result = $this->task->fetch($id); if( ! $result ) { throw new RestException(404, 'Task not found'); } - + if( ! DolibarrApi::_checkAccessToResource('task',$this->task->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + $usert = DolibarrApiAccess::$user; if ($userid > 0) { @@ -291,8 +292,8 @@ class Tasks extends DolibarrApi } return $result; } - - + + /** * Add a task to given project * @@ -347,13 +348,13 @@ class Tasks extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; } */ - + /** * Update a task to given project * @@ -411,8 +412,8 @@ class Tasks extends DolibarrApi } return false; }*/ - - + + /** * Update task general fields (won't touch time spent of task) * @@ -483,7 +484,7 @@ class Tasks extends DolibarrApi } - + /** * Add time spent to a task of a project. * You can test this API with the following input message @@ -494,36 +495,38 @@ class Tasks extends DolibarrApi * @param int $duration Duration in seconds (3600 = 1h) * @param int $user_id User (Use 0 for connected user) * @param string $note Note - * + * * @url POST {id}/addtimespent * * @return array */ function addTimeSpent($id, $date, $duration, $user_id=0, $note='') { - if(! DolibarrApiAccess::$user->rights->projet->creer) { + + + if( ! DolibarrApiAccess::$user->rights->projet->creer) { throw new RestException(401); } $result = $this->task->fetch($id); if ($result <= 0) { throw new RestException(404, 'Task not found'); } - - if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) { + + if( ! DolibarrApi::_checkAccessToResource('project', $this->task->fk_project)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + $uid = $user_id; if (empty($uid)) $uid = DolibarrApiAccess::$user->id; - $newdate = dol_stringtotime($date, 1); + $newdate = dol_stringtotime($date, 1); $this->task->timespent_date = $newdate; $this->task->timespent_datehour = $newdate; $this->task->timespent_withhour = 1; $this->task->timespent_duration = $duration; $this->task->timespent_fk_user = $user_id; - $this->task->timespent_note = $note; - + $this->task->timespent_note = $note; + $result = $this->task->addTimeSpent(DolibarrApiAccess::$user, 0); if ($result == 0) { throw new RestException(500, 'Error nothing done. May be object is already validated'); @@ -531,7 +534,7 @@ class Tasks extends DolibarrApi if ($result < 0) { throw new RestException(500, 'Error when adding time: '.$this->task->error); } - + return array( 'success' => array( 'code' => 200, @@ -539,8 +542,8 @@ class Tasks extends DolibarrApi ) ); } - - + + /** * Clean sensible object datas * @@ -548,9 +551,9 @@ class Tasks extends DolibarrApi * @return array Array of cleaned object properties */ function _cleanObjectDatas($object) { - + $object = parent::_cleanObjectDatas($object); - + unset($object->barcode_type); unset($object->barcode_type_code); unset($object->barcode_type_label); @@ -572,21 +575,21 @@ class Tasks extends DolibarrApi unset($object->country); unset($object->country_id); unset($object->country_code); - + unset($object->weekWorkLoad); unset($object->weekWorkLoad); - + //unset($object->lines); // for task we use timespent_lines, but for project we use lines - + 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 * @@ -605,8 +608,8 @@ class Tasks extends DolibarrApi } return $object; } - - + + // TODO // getSummaryOfTimeSpent } diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php index 84050012a5a..9ef2e8d6536 100644 --- a/htdocs/projet/class/project.class.php +++ b/htdocs/projet/class/project.class.php @@ -37,7 +37,7 @@ class Project extends CommonObject public $table_element = 'projet'; //!< Name of table without prefix where object is stored public $table_element_line = 'projet_task'; public $fk_element = 'fk_projet'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto = 'projectpub'; /** @@ -296,6 +296,7 @@ class Project extends CommonObject $sql.= ", fk_user_close=" . ($this->fk_user_close > 0 ? $this->fk_user_close : "null"); $sql.= ", opp_amount = " . (strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : "null"); $sql.= ", budget_amount = " . (strcmp($this->budget_amount, '') ? price2num($this->budget_amount) : "null"); + $sql.= ", fk_user_modif = " . $user->id; $sql.= " WHERE rowid = " . $this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); @@ -390,7 +391,7 @@ class Project extends CommonObject if (empty($id) && empty($ref)) return -1; $sql = "SELECT rowid, ref, title, description, public, datec, opp_amount, budget_amount,"; - $sql.= " tms, dateo, datee, date_close, fk_soc, fk_user_creat, fk_user_close, fk_statut, fk_opp_status, opp_percent, note_private, note_public, model_pdf"; + $sql.= " tms, dateo, datee, date_close, fk_soc, fk_user_creat, fk_user_modif, fk_user_close, fk_statut, fk_opp_status, opp_percent, note_private, note_public, model_pdf"; $sql.= " FROM " . MAIN_DB_PREFIX . "projet"; if (! empty($id)) { @@ -428,6 +429,7 @@ class Project extends CommonObject $this->note_public = $obj->note_public; $this->socid = $obj->fk_soc; $this->user_author_id = $obj->fk_user_creat; + $this->user_modification_id = $obj->fk_user_modif; $this->user_close_id = $obj->fk_user_close; $this->public = $obj->public; $this->statut = $obj->fk_statut; @@ -441,6 +443,7 @@ class Project extends CommonObject // Retreive all extrafield for thirdparty $this->fetch_optionals(); + $this->fetchComments(); return 1; } @@ -971,6 +974,7 @@ class Project extends CommonObject $label .= ($label?'
    ':'').'' . $langs->trans('DateEnd') . ': ' . dol_print_date($this->datee, 'day'); // The space must be after the : to not being explode when showing the title in img_picto if ($moreinpopup) $label.='
    '.$moreinpopup; + $url=''; if ($option != 'nolink') { if (preg_match('/\.php$/',$option)) { @@ -1000,18 +1004,32 @@ class Project extends CommonObject } $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose.=' class="classfortooltip"'; + + if (! is_object($hookmanager)) { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager=new HookManager($this->db); + } + $hookmanager->initHooks(array('projectdao')); + $parameters=array('id'=>$this->id); + // Note that $action and $object may have been modified by some hooks + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); + if ($reshook > 0) + $linkclose = $hookmanager->resPrint; } $picto = 'projectpub'; - if (!$this->public) $picto = 'project'; + if (! $this->public) $picto = 'project'; $linkstart = ''; $linkend=''; - if ($withpicto) $result.=($linkstart . img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1) . $linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$linkstart . $this->ref . $linkend . (($addlabel && $this->title) ? $sep . dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)) : ''); + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), $picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; + if ($withpicto != 2) $result.=(($addlabel && $this->title) ? $sep . dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)) : ''); + return $result; } diff --git a/htdocs/projet/class/task.class.php b/htdocs/projet/class/task.class.php index 1c8b1466483..64dc35a94f2 100644 --- a/htdocs/projet/class/task.class.php +++ b/htdocs/projet/class/task.class.php @@ -31,25 +31,25 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; */ class Task extends CommonObject { - public $element='project_task'; //!< Id that identify managed objects - public $table_element='projet_task'; //!< Name of table without prefix where object is stored - public $fk_element='fk_task'; - public $picto = 'task'; - protected $childtables=array('projet_task_time'); // To test if we can delete object + public $element='project_task'; //!< Id that identify managed objects + public $table_element='projet_task'; //!< Name of table without prefix where object is stored + public $fk_element='fk_task'; + public $picto = 'task'; + protected $childtables=array('projet_task_time','projet_task_comment'); // To test if we can delete object - var $fk_task_parent; - var $label; - var $description; - var $duration_effective; // total of time spent on this task - var $planned_workload; - var $date_c; - var $date_start; - var $date_end; - var $progress; - var $fk_statut; - var $priority; - var $fk_user_creat; - var $fk_user_valid; + var $fk_task_parent; + var $label; + var $description; + var $duration_effective; // total of time spent on this task + var $planned_workload; + var $date_c; + var $date_start; + var $date_end; + var $progress; + var $fk_statut; + var $priority; + var $fk_user_creat; + var $fk_user_valid; var $rang; var $timespent_min_date; @@ -61,1290 +61,1301 @@ class Task extends CommonObject // For detail of lines of timespent record, there is the property ->lines in common // Var used to call method addTimeSpent(). Bad practice. - var $timespent_id; - var $timespent_duration; - var $timespent_old_duration; - var $timespent_date; - var $timespent_datehour; // More accurate start date (same than timespent_date but includes hours, minutes and seconds) - var $timespent_withhour; // 1 = we entered also start hours for timesheet line - var $timespent_fk_user; - var $timespent_note; + var $timespent_id; + var $timespent_duration; + var $timespent_old_duration; + var $timespent_date; + var $timespent_datehour; // More accurate start date (same than timespent_date but includes hours, minutes and seconds) + var $timespent_withhour; // 1 = we entered also start hours for timesheet line + var $timespent_fk_user; + var $timespent_note; - public $oldcopy; + var $comments = array(); + public $oldcopy; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - } - - - /** - * Create into database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - function create($user, $notrigger=0) - { - global $conf, $langs; - - $error=0; - - // Clean parameters - $this->label = trim($this->label); - $this->description = trim($this->description); - - // Check parameters - // Put here code to add control on parameters values - - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task ("; - $sql.= "fk_projet"; - $sql.= ", ref"; - $sql.= ", fk_task_parent"; - $sql.= ", label"; - $sql.= ", description"; - $sql.= ", datec"; - $sql.= ", fk_user_creat"; - $sql.= ", dateo"; - $sql.= ", datee"; - $sql.= ", planned_workload"; - $sql.= ", progress"; - $sql.= ") VALUES ("; - $sql.= $this->fk_project; - $sql.= ", ".(!empty($this->ref)?"'".$this->db->escape($this->ref)."'":'null'); - $sql.= ", ".$this->fk_task_parent; - $sql.= ", '".$this->db->escape($this->label)."'"; - $sql.= ", '".$this->db->escape($this->description)."'"; - $sql.= ", '".$this->db->idate($this->date_c)."'"; - $sql.= ", ".$user->id; - $sql.= ", ".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null'); - $sql.= ", ".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null'); - $sql.= ", ".(($this->planned_workload!='' && $this->planned_workload >= 0)?$this->planned_workload:'null'); - $sql.= ", ".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null'); - $sql.= ")"; - - $this->db->begin(); - - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task"); - - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('TASK_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } - - // Update extrafield - if (! $error) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - else - { - $this->db->commit(); - return $this->id; - } - } - - - /** - * Load object in memory from database - * - * @param int $id Id object - * @param int $ref ref object - * @return int <0 if KO, 0 if not found, >0 if OK - */ - function fetch($id,$ref='') - { - global $langs; - - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.ref,"; - $sql.= " t.fk_projet,"; - $sql.= " t.fk_task_parent,"; - $sql.= " t.label,"; - $sql.= " t.description,"; - $sql.= " t.duration_effective,"; - $sql.= " t.planned_workload,"; - $sql.= " t.datec,"; - $sql.= " t.dateo,"; - $sql.= " t.datee,"; - $sql.= " t.fk_user_creat,"; - $sql.= " t.fk_user_valid,"; - $sql.= " t.fk_statut,"; - $sql.= " t.progress,"; - $sql.= " t.priority,"; - $sql.= " t.note_private,"; - $sql.= " t.note_public,"; - $sql.= " t.rang"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as t"; - $sql.= " WHERE "; - if (!empty($ref)) { - $sql.="t.ref = '".$this->db->escape($ref)."'"; - }else { - $sql.="t.rowid = ".$id; - } - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $num_rows = $this->db->num_rows($resql); - - if ($num_rows) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->ref = $obj->ref; - $this->fk_project = $obj->fk_projet; - $this->fk_task_parent = $obj->fk_task_parent; - $this->label = $obj->label; - $this->description = $obj->description; - $this->duration_effective = $obj->duration_effective; - $this->planned_workload = $obj->planned_workload; - $this->date_c = $this->db->jdate($obj->datec); - $this->date_start = $this->db->jdate($obj->dateo); - $this->date_end = $this->db->jdate($obj->datee); - $this->fk_user_creat = $obj->fk_user_creat; - $this->fk_user_valid = $obj->fk_user_valid; - $this->fk_statut = $obj->fk_statut; - $this->progress = $obj->progress; - $this->priority = $obj->priority; - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->rang = $obj->rang; - - // Retreive all extrafield for thirdparty - $this->fetch_optionals(); - } - - $this->db->free($resql); - - if ($num_rows) return 1; - else return 0; - } - else - { - $this->error="Error ".$this->db->lasterror(); - return -1; - } - } - - - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <=0 if KO, >0 if OK - */ - function update($user=null, $notrigger=0) - { - global $conf, $langs; - $error=0; - - // Clean parameters - if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project); - if (isset($this->ref)) $this->ref=trim($this->ref); - if (isset($this->fk_task_parent)) $this->fk_task_parent=trim($this->fk_task_parent); - if (isset($this->label)) $this->label=trim($this->label); - if (isset($this->description)) $this->description=trim($this->description); - if (isset($this->duration_effective)) $this->duration_effective=trim($this->duration_effective); - if (isset($this->planned_workload)) $this->planned_workload=trim($this->planned_workload); - - // Check parameters - // Put here code to add control on parameters values - - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET"; - $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").","; - $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"'".$this->id."'").","; - $sql.= " fk_task_parent=".(isset($this->fk_task_parent)?$this->fk_task_parent:"null").","; - $sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").","; - $sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").","; - $sql.= " duration_effective=".(isset($this->duration_effective)?$this->duration_effective:"null").","; - $sql.= " planned_workload=".((isset($this->planned_workload) && $this->planned_workload != '')?$this->planned_workload:"null").","; - $sql.= " dateo=".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null').","; - $sql.= " datee=".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null').","; - $sql.= " progress=".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null').","; - $sql.= " rang=".((!empty($this->rang))?$this->rang:"0"); - $sql.= " WHERE rowid=".$this->id; - - $this->db->begin(); - - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('TASK_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } - - //Update extrafield - if (!$error) { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - - if (! $error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) - { - // We remove directory - if ($conf->projet->dir_output) - { - $project = new Project($this->db); - $project->fetch($this->fk_project); - - $olddir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->oldcopy->ref); - $newdir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref); - if (file_exists($olddir)) - { - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $res=dol_move($olddir, $newdir); - if (! $res) - { - $langs->load("errors"); - $this->error=$langs->trans('ErrorFailToRenameDir',$olddir,$newdir); - $error++; - } - } - } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - else - { - $this->db->commit(); - return 1; - } - } - - - /** - * Delete task from database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function delete($user, $notrigger=0) - { - - global $conf, $langs; - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - - $error=0; - - $this->db->begin(); - - if ($this->hasChildren() > 0) - { - dol_syslog(get_class($this)."::delete Can't delete record as it has some sub tasks", LOG_WARNING); - $this->error='ErrorRecordHasSubTasks'; - $this->db->rollback(); - return 0; - } - - $objectisused = $this->isObjectUsed($this->id); - if (! empty($objectisused)) - { - dol_syslog(get_class($this)."::delete Can't delete record as it has some child", LOG_WARNING); - $this->error='ErrorRecordHasChildren'; - $this->db->rollback(); - return 0; - } - - if (! $error) - { - // Delete linked contacts - $res = $this->delete_linked_contact(); - if ($res < 0) - { - $this->error='ErrorFailToDeleteLinkedContact'; - //$error++; - $this->db->rollback(); - return 0; - } - } - - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time"; - $sql.= " WHERE fk_task=".$this->id; - - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - } - - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_extrafields"; - $sql.= " WHERE fk_object=".$this->id; - - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - } - - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task"; - $sql.= " WHERE rowid=".$this->id; - - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - } - - if (! $error) - { - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('TASK_DELETE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - else - { - //Delete associated link file - if ($conf->projet->dir_output) - { - $projectstatic=new Project($this->db); - $projectstatic->fetch($this->fk_project); - - $dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($projectstatic->ref) . '/' . dol_sanitizeFileName($this->id); - dol_syslog(get_class($this)."::delete dir=".$dir, LOG_DEBUG); - if (file_exists($dir)) - { - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $res = @dol_delete_dir_recursive($dir); - if (!$res) - { - $this->error = 'ErrorFailToDeleteDir'; - $this->db->rollback(); - return 0; - } - } - } - - $this->db->commit(); - - return 1; - } - } - - /** - * Return nb of children - * - * @return int <0 if KO, 0 if no children, >0 if OK - */ - function hasChildren() - { - $error=0; - $ret=0; - - $sql = "SELECT COUNT(*) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet_task"; - $sql.= " WHERE fk_task_parent=".$this->id; - - dol_syslog(get_class($this)."::hasChildren", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - else - { - $obj=$this->db->fetch_object($resql); - if ($obj) $ret=$obj->nb; - $this->db->free($resql); - } - - if (! $error) - { - return $ret; - } - else - { - return -1; - } - } /** - * Return nb of time spent - * - * @return int <0 if KO, 0 if no children, >0 if OK - */ - function hasTimeSpent() - { - $error=0; - $ret=0; - - $sql = "SELECT COUNT(*) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time"; - $sql.= " WHERE fk_task=".$this->id; - - dol_syslog(get_class($this)."::hasTimeSpent", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - else - { - $obj=$this->db->fetch_object($resql); - if ($obj) $ret=$obj->nb; - $this->db->free($resql); - } - - if (! $error) - { - return $ret; - } - else - { - return -1; - } - } + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db = $db; + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param string $option 'withproject' or '' - * @param string $mode Mode 'task', 'time', 'contact', 'note', document' define page to link to. - * @param int $addlabel 0=Default, 1=Add label into string, >1=Add first chars into string - * @param string $sep Separator between ref and label if option addlabel is set - * @param int $notooltip 1=Disable tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string Chaine avec URL - */ - function getNomUrl($withpicto=0,$option='',$mode='task', $addlabel=0, $sep=' - ', $notooltip=0, $save_lastsearch_value=-1) - { - global $conf, $langs, $user; + /** + * Create into database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + function create($user, $notrigger=0) + { + global $conf, $langs; - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + $error=0; - $result=''; - $label = '' . $langs->trans("ShowTask") . ''; - if (! empty($this->ref)) - $label .= '
    ' . $langs->trans('Ref') . ': ' . $this->ref; - if (! empty($this->label)) - $label .= '
    ' . $langs->trans('LabelTask') . ': ' . $this->label; - if ($this->date_start || $this->date_end) - { - $label .= "
    ".get_date_range($this->date_start,$this->date_end,'',$langs,0); - } + // Clean parameters + $this->label = trim($this->label); + $this->description = trim($this->description); - $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option=='withproject'?'&withproject=1':''); - // Add param to save lastsearch_values or not - $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; - if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + // Check parameters + // Put here code to add control on parameters values - $linkclose = ''; - if (empty($notooltip)) - { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label=$langs->trans("ShowTask"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip"'; - } + // Insert request + $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task ("; + $sql.= "fk_projet"; + $sql.= ", ref"; + $sql.= ", fk_task_parent"; + $sql.= ", label"; + $sql.= ", description"; + $sql.= ", datec"; + $sql.= ", fk_user_creat"; + $sql.= ", dateo"; + $sql.= ", datee"; + $sql.= ", planned_workload"; + $sql.= ", progress"; + $sql.= ") VALUES ("; + $sql.= $this->fk_project; + $sql.= ", ".(!empty($this->ref)?"'".$this->db->escape($this->ref)."'":'null'); + $sql.= ", ".$this->fk_task_parent; + $sql.= ", '".$this->db->escape($this->label)."'"; + $sql.= ", '".$this->db->escape($this->description)."'"; + $sql.= ", '".$this->db->idate($this->date_c)."'"; + $sql.= ", ".$user->id; + $sql.= ", ".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null'); + $sql.= ", ".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null'); + $sql.= ", ".(($this->planned_workload!='' && $this->planned_workload >= 0)?$this->planned_workload:'null'); + $sql.= ", ".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null'); + $sql.= ")"; - $linkstart = ''; - $linkend=''; + $this->db->begin(); - $picto='projecttask'; + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$linkstart.$this->ref.$linkend . (($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); - return $result; - } + if (! $error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task"); - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - function initAsSpecimen() - { - $this->id=0; + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } - $this->fk_projet=''; + // Update extrafield + if (! $error) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id Id object + * @param int $ref ref object + * @return int <0 if KO, 0 if not found, >0 if OK + */ + function fetch($id,$ref='') + { + global $langs; + + $sql = "SELECT"; + $sql.= " t.rowid,"; + $sql.= " t.ref,"; + $sql.= " t.fk_projet,"; + $sql.= " t.fk_task_parent,"; + $sql.= " t.label,"; + $sql.= " t.description,"; + $sql.= " t.duration_effective,"; + $sql.= " t.planned_workload,"; + $sql.= " t.datec,"; + $sql.= " t.dateo,"; + $sql.= " t.datee,"; + $sql.= " t.fk_user_creat,"; + $sql.= " t.fk_user_valid,"; + $sql.= " t.fk_statut,"; + $sql.= " t.progress,"; + $sql.= " t.priority,"; + $sql.= " t.note_private,"; + $sql.= " t.note_public,"; + $sql.= " t.rang"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as t"; + $sql.= " WHERE "; + if (!empty($ref)) { + $sql.="t.ref = '".$this->db->escape($ref)."'"; + }else { + $sql.="t.rowid = ".$id; + } + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $num_rows = $this->db->num_rows($resql); + + if ($num_rows) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->ref = $obj->ref; + $this->fk_project = $obj->fk_projet; + $this->fk_task_parent = $obj->fk_task_parent; + $this->label = $obj->label; + $this->description = $obj->description; + $this->duration_effective = $obj->duration_effective; + $this->planned_workload = $obj->planned_workload; + $this->date_c = $this->db->jdate($obj->datec); + $this->date_start = $this->db->jdate($obj->dateo); + $this->date_end = $this->db->jdate($obj->datee); + $this->fk_user_creat = $obj->fk_user_creat; + $this->fk_user_valid = $obj->fk_user_valid; + $this->fk_statut = $obj->fk_statut; + $this->progress = $obj->progress; + $this->priority = $obj->priority; + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->rang = $obj->rang; + + // Retreive all extrafield for thirdparty + $this->fetch_optionals(); + } + + $this->db->free($resql); + + if ($num_rows) { + $this->fetchComments(); + return 1; + }else { + return 0; + } + } + else + { + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <=0 if KO, >0 if OK + */ + function update($user=null, $notrigger=0) + { + global $conf, $langs; + $error=0; + + // Clean parameters + if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project); + if (isset($this->ref)) $this->ref=trim($this->ref); + if (isset($this->fk_task_parent)) $this->fk_task_parent=trim($this->fk_task_parent); + if (isset($this->label)) $this->label=trim($this->label); + if (isset($this->description)) $this->description=trim($this->description); + if (isset($this->duration_effective)) $this->duration_effective=trim($this->duration_effective); + if (isset($this->planned_workload)) $this->planned_workload=trim($this->planned_workload); + + // Check parameters + // Put here code to add control on parameters values + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET"; + $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").","; + $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"'".$this->db->escape($this->id)."'").","; + $sql.= " fk_task_parent=".(isset($this->fk_task_parent)?$this->fk_task_parent:"null").","; + $sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").","; + $sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").","; + $sql.= " duration_effective=".(isset($this->duration_effective)?$this->duration_effective:"null").","; + $sql.= " planned_workload=".((isset($this->planned_workload) && $this->planned_workload != '')?$this->planned_workload:"null").","; + $sql.= " dateo=".($this->date_start!=''?"'".$this->db->idate($this->date_start)."'":'null').","; + $sql.= " datee=".($this->date_end!=''?"'".$this->db->idate($this->date_end)."'":'null').","; + $sql.= " progress=".(($this->progress!='' && $this->progress >= 0)?$this->progress:'null').","; + $sql.= " rang=".((!empty($this->rang))?$this->rang:"0"); + $sql.= " WHERE rowid=".$this->id; + + $this->db->begin(); + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + //Update extrafield + if (!$error) { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } + + if (! $error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) + { + // We remove directory + if ($conf->projet->dir_output) + { + $project = new Project($this->db); + $project->fetch($this->fk_project); + + $olddir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->oldcopy->ref); + $newdir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref); + if (file_exists($olddir)) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + $res=dol_move($olddir, $newdir); + if (! $res) + { + $langs->load("errors"); + $this->error=$langs->trans('ErrorFailToRenameDir',$olddir,$newdir); + $error++; + } + } + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return 1; + } + } + + + /** + * Delete task from database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function delete($user, $notrigger=0) + { + + global $conf, $langs; + require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + $error=0; + + $this->db->begin(); + + if ($this->hasChildren() > 0) + { + dol_syslog(get_class($this)."::delete Can't delete record as it has some sub tasks", LOG_WARNING); + $this->error='ErrorRecordHasSubTasks'; + $this->db->rollback(); + return 0; + } + + $objectisused = $this->isObjectUsed($this->id); + if (! empty($objectisused)) + { + dol_syslog(get_class($this)."::delete Can't delete record as it has some child", LOG_WARNING); + $this->error='ErrorRecordHasChildren'; + $this->db->rollback(); + return 0; + } + + if (! $error) + { + // Delete linked contacts + $res = $this->delete_linked_contact(); + if ($res < 0) + { + $this->error='ErrorFailToDeleteLinkedContact'; + //$error++; + $this->db->rollback(); + return 0; + } + } + + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time"; + $sql.= " WHERE fk_task=".$this->id; + + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + } + + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_extrafields"; + $sql.= " WHERE fk_object=".$this->id; + + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + } + + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task"; + $sql.= " WHERE rowid=".$this->id; + + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + } + + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + //Delete associated link file + if ($conf->projet->dir_output) + { + $projectstatic=new Project($this->db); + $projectstatic->fetch($this->fk_project); + + $dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($projectstatic->ref) . '/' . dol_sanitizeFileName($this->id); + dol_syslog(get_class($this)."::delete dir=".$dir, LOG_DEBUG); + if (file_exists($dir)) + { + require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + $res = @dol_delete_dir_recursive($dir); + if (!$res) + { + $this->error = 'ErrorFailToDeleteDir'; + $this->db->rollback(); + return 0; + } + } + } + + $this->db->commit(); + + return 1; + } + } + + /** + * Return nb of children + * + * @return int <0 if KO, 0 if no children, >0 if OK + */ + function hasChildren() + { + $error=0; + $ret=0; + + $sql = "SELECT COUNT(*) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet_task"; + $sql.= " WHERE fk_task_parent=".$this->id; + + dol_syslog(get_class($this)."::hasChildren", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + else + { + $obj=$this->db->fetch_object($resql); + if ($obj) $ret=$obj->nb; + $this->db->free($resql); + } + + if (! $error) + { + return $ret; + } + else + { + return -1; + } + } + + /** + * Return nb of time spent + * + * @return int <0 if KO, 0 if no children, >0 if OK + */ + function hasTimeSpent() + { + $error=0; + $ret=0; + + $sql = "SELECT COUNT(*) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time"; + $sql.= " WHERE fk_task=".$this->id; + + dol_syslog(get_class($this)."::hasTimeSpent", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + else + { + $obj=$this->db->fetch_object($resql); + if ($obj) $ret=$obj->nb; + $this->db->free($resql); + } + + if (! $error) + { + return $ret; + } + else + { + return -1; + } + } + + + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param string $option 'withproject' or '' + * @param string $mode Mode 'task', 'time', 'contact', 'note', document' define page to link to. + * @param int $addlabel 0=Default, 1=Add label into string, >1=Add first chars into string + * @param string $sep Separator between ref and label if option addlabel is set + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL + */ + function getNomUrl($withpicto=0,$option='',$mode='task', $addlabel=0, $sep=' - ', $notooltip=0, $save_lastsearch_value=-1) + { + global $conf, $langs, $user; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + + $result=''; + $label = '' . $langs->trans("ShowTask") . ''; + if (! empty($this->ref)) + $label .= '
    ' . $langs->trans('Ref') . ': ' . $this->ref; + if (! empty($this->label)) + $label .= '
    ' . $langs->trans('LabelTask') . ': ' . $this->label; + if ($this->date_start || $this->date_end) + { + $label .= "
    ".get_date_range($this->date_start,$this->date_end,'',$langs,0); + } + + $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option=='withproject'?'&withproject=1':''); + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + + $linkclose = ''; + if (empty($notooltip)) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowTask"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; + } + + $linkstart = ''; + $linkend=''; + + $picto='projecttask'; + + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), $picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; + if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + + return $result; + } + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + $this->id=0; + + $this->fk_projet=''; $this->ref='TK01'; - $this->fk_task_parent=''; - $this->label='Specimen task TK01'; - $this->duration_effective=''; - $this->fk_user_creat=''; - $this->progress='25'; - $this->fk_statut=''; - $this->note='This is a specimen task not'; - } + $this->fk_task_parent=''; + $this->label='Specimen task TK01'; + $this->duration_effective=''; + $this->fk_user_creat=''; + $this->progress='25'; + $this->fk_statut=''; + $this->note='This is a specimen task not'; + } - /** - * Return list of tasks for all projects or for one particular project - * Sort order is on project, then on position of task, and last on start date of first level task - * - * @param User $usert Object user to limit tasks affected to a particular user - * @param User $userp Object user to limit projects of a particular user and public projects - * @param int $projectid Project id - * @param int $socid Third party id - * @param int $mode 0=Return list of tasks and their projects, 1=Return projects and tasks if exists - * @param string $filteronprojref Filter on project ref - * @param string $filteronprojstatus Filter on project status - * @param string $morewherefilter Add more filter into where SQL request (must start with ' AND ...') - * @param string $filteronprojuser Filter on user that is a contact of project - * @param string $filterontaskuser Filter on user assigned to task - * @return array Array of tasks - */ - function getTasksArray($usert=0, $userp=0, $projectid=0, $socid=0, $mode=0, $filteronprojref='', $filteronprojstatus=-1, $morewherefilter='',$filteronprojuser=0,$filterontaskuser=0) - { - global $conf; + /** + * Return list of tasks for all projects or for one particular project + * Sort order is on project, then on position of task, and last on start date of first level task + * + * @param User $usert Object user to limit tasks affected to a particular user + * @param User $userp Object user to limit projects of a particular user and public projects + * @param int $projectid Project id + * @param int $socid Third party id + * @param int $mode 0=Return list of tasks and their projects, 1=Return projects and tasks if exists + * @param string $filteronproj Filter on project ref or label + * @param string $filteronprojstatus Filter on project status + * @param string $morewherefilter Add more filter into where SQL request (must start with ' AND ...') + * @param string $filteronprojuser Filter on user that is a contact of project + * @param string $filterontaskuser Filter on user assigned to task + * @return array Array of tasks + */ + function getTasksArray($usert=null, $userp=null, $projectid=0, $socid=0, $mode=0, $filteronproj='', $filteronprojstatus=-1, $morewherefilter='',$filteronprojuser=0,$filterontaskuser=0) + { + global $conf; - $tasks = array(); + $tasks = array(); - //print $usert.'-'.$userp.'-'.$projectid.'-'.$socid.'-'.$mode.'
    '; + //print $usert.'-'.$userp.'-'.$projectid.'-'.$socid.'-'.$mode.'
    '; - // List of tasks (does not care about permissions. Filtering will be done later) - $sql = "SELECT "; - if ($filteronprojuser > 0 || $filterontaskuser > 0) $sql.= " DISTINCT"; // We may get several time the same record if user has several roles on same project/task - $sql.= " p.rowid as projectid, p.ref, p.title as plabel, p.public, p.fk_statut as projectstatus,"; - $sql.= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,"; - $sql.= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang,"; - $sql.= " s.rowid as thirdparty_id, s.nom as thirdparty_name"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; - if ($mode == 0) - { - if ($filteronprojuser > 0) - { - $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; - } - $sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; - if ($filterontaskuser > 0) - { - $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2"; - $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2"; - } - $sql.= " WHERE p.entity IN (".getEntity('project').")"; - $sql.= " AND t.fk_projet = p.rowid"; - } - elseif ($mode == 1) - { - if ($filteronprojuser > 0) - { - $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; - } - if ($filterontaskuser > 0) - { - $sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; - $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2"; - $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2"; - } - else - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid"; - } - $sql.= " WHERE p.entity IN (".getEntity('project').")"; - } - else return 'BadValueForParameterMode'; + // List of tasks (does not care about permissions. Filtering will be done later) + $sql = "SELECT "; + if ($filteronprojuser > 0 || $filterontaskuser > 0) $sql.= " DISTINCT"; // We may get several time the same record if user has several roles on same project/task + $sql.= " p.rowid as projectid, p.ref, p.title as plabel, p.public, p.fk_statut as projectstatus,"; + $sql.= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,"; + $sql.= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang,"; + $sql.= " s.rowid as thirdparty_id, s.nom as thirdparty_name, s.email as thirdparty_email"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; + if ($mode == 0) + { + if ($filteronprojuser > 0) + { + $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; + } + $sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; + if ($filterontaskuser > 0) + { + $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2"; + $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2"; + } + $sql.= " WHERE p.entity IN (".getEntity('project').")"; + $sql.= " AND t.fk_projet = p.rowid"; + } + elseif ($mode == 1) + { + if ($filteronprojuser > 0) + { + $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; + } + if ($filterontaskuser > 0) + { + $sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; + $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec2"; + $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2"; + } + else + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid"; + } + $sql.= " WHERE p.entity IN (".getEntity('project').")"; + } + else return 'BadValueForParameterMode'; - if ($filteronprojuser > 0) - { - $sql.= " AND p.rowid = ec.element_id"; - $sql.= " AND ctc.rowid = ec.fk_c_type_contact"; - $sql.= " AND ctc.element = 'project'"; - $sql.= " AND ec.fk_socpeople = ".$filteronprojuser; - $sql.= " AND ec.statut = 4"; - $sql.= " AND ctc.source = 'internal'"; - } - if ($filterontaskuser > 0) - { - $sql.= " AND t.fk_projet = p.rowid"; - $sql.= " AND p.rowid = ec2.element_id"; - $sql.= " AND ctc2.rowid = ec2.fk_c_type_contact"; - $sql.= " AND ctc2.element = 'project_task'"; - $sql.= " AND ec2.fk_socpeople = ".$filterontaskuser; - $sql.= " AND ec2.statut = 4"; - $sql.= " AND ctc2.source = 'internal'"; - } - if ($socid) $sql.= " AND p.fk_soc = ".$socid; - if ($projectid) $sql.= " AND p.rowid in (".$projectid.")"; - if ($filteronprojref) $sql.= " AND p.ref LIKE '%".$this->db->escape($filteronprojref)."%'"; - if ($filteronprojstatus > -1) $sql.= " AND p.fk_statut = ".$filteronprojstatus; - if ($morewherefilter) $sql.=$morewherefilter; - $sql.= " ORDER BY p.ref, t.rang, t.dateo"; + if ($filteronprojuser > 0) + { + $sql.= " AND p.rowid = ec.element_id"; + $sql.= " AND ctc.rowid = ec.fk_c_type_contact"; + $sql.= " AND ctc.element = 'project'"; + $sql.= " AND ec.fk_socpeople = ".$filteronprojuser; + $sql.= " AND ec.statut = 4"; + $sql.= " AND ctc.source = 'internal'"; + } + if ($filterontaskuser > 0) + { + $sql.= " AND t.fk_projet = p.rowid"; + $sql.= " AND p.rowid = ec2.element_id"; + $sql.= " AND ctc2.rowid = ec2.fk_c_type_contact"; + $sql.= " AND ctc2.element = 'project_task'"; + $sql.= " AND ec2.fk_socpeople = ".$filterontaskuser; + $sql.= " AND ec2.statut = 4"; + $sql.= " AND ctc2.source = 'internal'"; + } + if ($socid) $sql.= " AND p.fk_soc = ".$socid; + if ($projectid) $sql.= " AND p.rowid in (".$projectid.")"; + if ($filteronproj) $sql.= " AND (p.ref LIKE '%".$this->db->escape($filteronproj)."%' OR p.title LIKE '%".$this->db->escape($filteronproj)."%')"; + if ($filteronprojstatus > -1) $sql.= " AND p.fk_statut = ".$filteronprojstatus; + if ($morewherefilter) $sql.=$morewherefilter; + $sql.= " ORDER BY p.ref, t.rang, t.dateo"; - //print $sql;exit; - dol_syslog(get_class($this)."::getTasksArray", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - // Loop on each record found, so each couple (project id, task id) - while ($i < $num) - { - $error=0; + //print $sql;exit; + dol_syslog(get_class($this)."::getTasksArray", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + // Loop on each record found, so each couple (project id, task id) + while ($i < $num) + { + $error=0; - $obj = $this->db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); - if ((! $obj->public) && (is_object($userp))) // If not public project and we ask a filter on project owned by a user - { - if (! $this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0)) - { - $error++; - } - } - if (is_object($usert)) // If we ask a filter on a user affected to a task - { - if (! $this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid)) - { - $error++; - } - } + if ((! $obj->public) && (is_object($userp))) // If not public project and we ask a filter on project owned by a user + { + if (! $this->getUserRolesForProjectsOrTasks($userp, 0, $obj->projectid, 0)) + { + $error++; + } + } + if (is_object($usert)) // If we ask a filter on a user affected to a task + { + if (! $this->getUserRolesForProjectsOrTasks(0, $usert, $obj->projectid, $obj->taskid)) + { + $error++; + } + } - if (! $error) - { + if (! $error) + { $tasks[$i] = new Task($this->db); - $tasks[$i]->id = $obj->taskid; + $tasks[$i]->id = $obj->taskid; $tasks[$i]->ref = $obj->taskref; - $tasks[$i]->fk_project = $obj->projectid; - $tasks[$i]->projectref = $obj->ref; - $tasks[$i]->projectlabel = $obj->plabel; - $tasks[$i]->projectstatus = $obj->projectstatus; - $tasks[$i]->label = $obj->label; - $tasks[$i]->description = $obj->description; - $tasks[$i]->fk_parent = $obj->fk_task_parent; // deprecated - $tasks[$i]->fk_task_parent = $obj->fk_task_parent; - $tasks[$i]->duration = $obj->duration_effective; - $tasks[$i]->planned_workload= $obj->planned_workload; - $tasks[$i]->progress = $obj->progress; - $tasks[$i]->fk_statut = $obj->status; - $tasks[$i]->public = $obj->public; - $tasks[$i]->date_start = $this->db->jdate($obj->date_start); - $tasks[$i]->date_end = $this->db->jdate($obj->date_end); - $tasks[$i]->rang = $obj->rang; + $tasks[$i]->fk_project = $obj->projectid; + $tasks[$i]->projectref = $obj->ref; + $tasks[$i]->projectlabel = $obj->plabel; + $tasks[$i]->projectstatus = $obj->projectstatus; + $tasks[$i]->label = $obj->label; + $tasks[$i]->description = $obj->description; + $tasks[$i]->fk_parent = $obj->fk_task_parent; // deprecated + $tasks[$i]->fk_task_parent = $obj->fk_task_parent; + $tasks[$i]->duration = $obj->duration_effective; + $tasks[$i]->planned_workload= $obj->planned_workload; + $tasks[$i]->progress = $obj->progress; + $tasks[$i]->fk_statut = $obj->status; + $tasks[$i]->public = $obj->public; + $tasks[$i]->date_start = $this->db->jdate($obj->date_start); + $tasks[$i]->date_end = $this->db->jdate($obj->date_end); + $tasks[$i]->rang = $obj->rang; - $tasks[$i]->thirdparty_id = $obj->thirdparty_id; - $tasks[$i]->thirdparty_name = $obj->thirdparty_name; - } + $tasks[$i]->socid = $obj->thirdparty_id; // For backward compatibility + $tasks[$i]->thirdparty_id = $obj->thirdparty_id; + $tasks[$i]->thirdparty_name = $obj->thirdparty_name; + $tasks[$i]->thirdparty_email= $obj->thirdparty_email; + } - $i++; - } - $this->db->free($resql); - } - else - { - dol_print_error($this->db); - } + $i++; + } + $this->db->free($resql); + } + else + { + dol_print_error($this->db); + } - return $tasks; - } + return $tasks; + } - /** - * Return list of roles for a user for each projects or each tasks (or a particular project or a particular task). - * - * @param User $userp Return roles on project for this internal user. If set, usert and taskid must not be defined. - * @param User $usert Return roles on task for this internal user. If set userp must NOT be defined. -1 means no filter. - * @param int $projectid Project id list separated with , to filter on project - * @param int $taskid Task id to filter on a task - * @param integer $filteronprojstatus Filter on project status if userp is set. Not used if userp not defined. - * @return array Array (projectid => 'list of roles for project' or taskid => 'list of roles for task') - */ - function getUserRolesForProjectsOrTasks($userp, $usert, $projectid='', $taskid=0, $filteronprojstatus=-1) - { - $arrayroles = array(); + /** + * Return list of roles for a user for each projects or each tasks (or a particular project or a particular task). + * + * @param User $userp Return roles on project for this internal user. If set, usert and taskid must not be defined. + * @param User $usert Return roles on task for this internal user. If set userp must NOT be defined. -1 means no filter. + * @param int $projectid Project id list separated with , to filter on project + * @param int $taskid Task id to filter on a task + * @param integer $filteronprojstatus Filter on project status if userp is set. Not used if userp not defined. + * @return array Array (projectid => 'list of roles for project' or taskid => 'list of roles for task') + */ + function getUserRolesForProjectsOrTasks($userp, $usert, $projectid='', $taskid=0, $filteronprojstatus=-1) + { + $arrayroles = array(); - dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks userp=".is_object($userp)." usert=".is_object($usert)." projectid=".$projectid." taskid=".$taskid); + dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks userp=".is_object($userp)." usert=".is_object($usert)." projectid=".$projectid." taskid=".$taskid); - // We want role of user for a projet or role of user for a task. Both are not possible. - if (empty($userp) && empty($usert)) - { - $this->error="CallWithWrongParameters"; - return -1; - } - if (! empty($userp) && ! empty($usert)) - { - $this->error="CallWithWrongParameters"; - return -1; - } + // We want role of user for a projet or role of user for a task. Both are not possible. + if (empty($userp) && empty($usert)) + { + $this->error="CallWithWrongParameters"; + return -1; + } + if (! empty($userp) && ! empty($usert)) + { + $this->error="CallWithWrongParameters"; + return -1; + } - /* Liste des taches et role sur les projets ou taches */ - $sql = "SELECT pt.rowid as pid, ec.element_id, ctc.code, ctc.source"; - if ($userp) $sql.= " FROM ".MAIN_DB_PREFIX."projet as pt"; - if ($usert && $filteronprojstatus > -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt"; - if ($usert && $filteronprojstatus <= -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as pt"; - $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; - $sql.= " WHERE pt.rowid = ec.element_id"; - if ($userp && $filteronprojstatus > -1) $sql.= " AND pt.fk_statut = ".$filteronprojstatus; - if ($usert && $filteronprojstatus > -1) $sql.= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus; - if ($userp) $sql.= " AND ctc.element = 'project'"; - if ($usert) $sql.= " AND ctc.element = 'project_task'"; - $sql.= " AND ctc.rowid = ec.fk_c_type_contact"; - if ($userp) $sql.= " AND ec.fk_socpeople = ".$userp->id; - if ($usert) $sql.= " AND ec.fk_socpeople = ".$usert->id; - $sql.= " AND ec.statut = 4"; - $sql.= " AND ctc.source = 'internal'"; - if ($projectid) - { - if ($userp) $sql.= " AND pt.rowid in (".$projectid.")"; - if ($usert) $sql.= " AND pt.fk_projet in (".$projectid.")"; - } - if ($taskid) - { - if ($userp) $sql.= " ERROR SHOULD NOT HAPPENS"; - if ($usert) $sql.= " AND pt.rowid = ".$taskid; - } - //print $sql; + /* Liste des taches et role sur les projets ou taches */ + $sql = "SELECT pt.rowid as pid, ec.element_id, ctc.code, ctc.source"; + if ($userp) $sql.= " FROM ".MAIN_DB_PREFIX."projet as pt"; + if ($usert && $filteronprojstatus > -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt"; + if ($usert && $filteronprojstatus <= -1) $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as pt"; + $sql.= ", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; + $sql.= " WHERE pt.rowid = ec.element_id"; + if ($userp && $filteronprojstatus > -1) $sql.= " AND pt.fk_statut = ".$filteronprojstatus; + if ($usert && $filteronprojstatus > -1) $sql.= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".$filteronprojstatus; + if ($userp) $sql.= " AND ctc.element = 'project'"; + if ($usert) $sql.= " AND ctc.element = 'project_task'"; + $sql.= " AND ctc.rowid = ec.fk_c_type_contact"; + if ($userp) $sql.= " AND ec.fk_socpeople = ".$userp->id; + if ($usert) $sql.= " AND ec.fk_socpeople = ".$usert->id; + $sql.= " AND ec.statut = 4"; + $sql.= " AND ctc.source = 'internal'"; + if ($projectid) + { + if ($userp) $sql.= " AND pt.rowid in (".$projectid.")"; + if ($usert) $sql.= " AND pt.fk_projet in (".$projectid.")"; + } + if ($taskid) + { + if ($userp) $sql.= " ERROR SHOULD NOT HAPPENS"; + if ($usert) $sql.= " AND pt.rowid = ".$taskid; + } + //print $sql; - dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks execute request", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - if (empty($arrayroles[$obj->pid])) $arrayroles[$obj->pid] = $obj->code; - else $arrayroles[$obj->pid].=','.$obj->code; - $i++; - } - $this->db->free($resql); - } - else - { - dol_print_error($this->db); - } + dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks execute request", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + if (empty($arrayroles[$obj->pid])) $arrayroles[$obj->pid] = $obj->code; + else $arrayroles[$obj->pid].=','.$obj->code; + $i++; + } + $this->db->free($resql); + } + else + { + dol_print_error($this->db); + } - return $arrayroles; - } + return $arrayroles; + } - /** - * Return list of id of contacts of task - * - * @param string $source Source - * @return array Array of id of contacts - */ - function getListContactId($source='internal') - { - $contactAlreadySelected = array(); - $tab = $this->liste_contact(-1,$source); - //var_dump($tab); - $num=count($tab); - $i = 0; - while ($i < $num) - { - if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; - else $contactAlreadySelected[$i] = $tab[$i]['id']; - $i++; - } - return $contactAlreadySelected; - } + /** + * Return list of id of contacts of task + * + * @param string $source Source + * @return array Array of id of contacts + */ + function getListContactId($source='internal') + { + $contactAlreadySelected = array(); + $tab = $this->liste_contact(-1,$source); + //var_dump($tab); + $num=count($tab); + $i = 0; + while ($i < $num) + { + if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; + else $contactAlreadySelected[$i] = $tab[$i]['id']; + $i++; + } + return $contactAlreadySelected; + } - /** - * Add time spent - * - * @param User $user User object - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <=0 if KO, >0 if OK - */ - function addTimeSpent($user, $notrigger=0) - { - global $conf,$langs; + /** + * Add time spent + * + * @param User $user User object + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <=0 if KO, >0 if OK + */ + function addTimeSpent($user, $notrigger=0) + { + global $conf,$langs; - dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG); + dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG); - $ret = 0; + $ret = 0; - // Check parameters - if (! is_object($user)) - { - dol_print_error('',"Method addTimeSpent was called with wrong parameter user"); - return -1; - } + // Check parameters + if (! is_object($user)) + { + dol_print_error('',"Method addTimeSpent was called with wrong parameter user"); + return -1; + } - // Clean parameters - if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note); + // Clean parameters + if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note); if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date; - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task_time ("; - $sql.= "fk_task"; - $sql.= ", task_date"; - $sql.= ", task_datehour"; - $sql.= ", task_date_withhour"; - $sql.= ", task_duration"; - $sql.= ", fk_user"; - $sql.= ", note"; - $sql.= ") VALUES ("; - $sql.= $this->id; - $sql.= ", '".$this->db->idate($this->timespent_date)."'"; - $sql.= ", '".$this->db->idate($this->timespent_datehour)."'"; - $sql.= ", ".(empty($this->timespent_withhour)?0:1); - $sql.= ", ".$this->timespent_duration; - $sql.= ", ".$this->timespent_fk_user; - $sql.= ", ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null"); - $sql.= ")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task_time ("; + $sql.= "fk_task"; + $sql.= ", task_date"; + $sql.= ", task_datehour"; + $sql.= ", task_date_withhour"; + $sql.= ", task_duration"; + $sql.= ", fk_user"; + $sql.= ", note"; + $sql.= ") VALUES ("; + $sql.= $this->id; + $sql.= ", '".$this->db->idate($this->timespent_date)."'"; + $sql.= ", '".$this->db->idate($this->timespent_datehour)."'"; + $sql.= ", ".(empty($this->timespent_withhour)?0:1); + $sql.= ", ".$this->timespent_duration; + $sql.= ", ".$this->timespent_fk_user; + $sql.= ", ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null"); + $sql.= ")"; - $resql=$this->db->query($sql); - if ($resql) - { - $tasktime_id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_time"); - $ret = $tasktime_id; + $resql=$this->db->query($sql); + if ($resql) + { + $tasktime_id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_time"); + $ret = $tasktime_id; $this->timespent_id = $ret; - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('TASK_TIMESPENT_CREATE',$user); - if ($result < 0) { $ret=-1; } - // End call triggers - } - } - else + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_TIMESPENT_CREATE',$user); + if ($result < 0) { $ret=-1; } + // End call triggers + } + } + else { - $this->error=$this->db->lasterror(); - $ret = -1; - } + $this->error=$this->db->lasterror(); + $ret = -1; + } - if ($ret > 0) - { - // Recalculate amount of time spent for task and update denormalized field - $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task"; - $sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")"; + if ($ret > 0) + { + // Recalculate amount of time spent for task and update denormalized field + $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task"; + $sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")"; if (isset($this->progress)) $sql.= ", progress = " . $this->progress; // Do not overwrite value if not provided - $sql.= " WHERE rowid = ".$this->id; + $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG); - if (! $this->db->query($sql) ) - { - $this->error=$this->db->lasterror(); - $ret = -2; - } + dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG); + if (! $this->db->query($sql) ) + { + $this->error=$this->db->lasterror(); + $ret = -2; + } - $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time"; - $sql.= " SET thm = (SELECT thm FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->timespent_fk_user.")"; // set average hour rate of user - $sql.= " WHERE rowid = ".$tasktime_id; + $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time"; + $sql.= " SET thm = (SELECT thm FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->timespent_fk_user.")"; // set average hour rate of user + $sql.= " WHERE rowid = ".$tasktime_id; - dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG); - if (! $this->db->query($sql) ) - { - $this->error=$this->db->lasterror(); - $ret = -2; - } - } + dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG); + if (! $this->db->query($sql) ) + { + $this->error=$this->db->lasterror(); + $ret = -2; + } + } - if ($ret >0) - { - $this->db->commit(); - } - else + if ($ret >0) { - $this->db->rollback(); - } - return $ret; - } + $this->db->commit(); + } + else + { + $this->db->rollback(); + } + return $ret; + } - /** - * Calculate total of time spent for task - * - * @param int $userid Filter on user id. 0=No filter - * @return array Array of info for task array('min_date', 'max_date', 'total_duration', 'total_amount', 'nblines', 'nblinesnull') - */ - function getSummaryOfTimeSpent($userid=0) - { - global $langs; + /** + * Calculate total of time spent for task + * + * @param int $userid Filter on user id. 0=No filter + * @return array Array of info for task array('min_date', 'max_date', 'total_duration', 'total_amount', 'nblines', 'nblinesnull') + */ + function getSummaryOfTimeSpent($userid=0) + { + global $langs; - $id=$this->id; - if (empty($id)) - { - dol_syslog("getSummaryOfTimeSpent called on a not loaded task", LOG_ERR); - return -1; - } + $id=$this->id; + if (empty($id)) + { + dol_syslog("getSummaryOfTimeSpent called on a not loaded task", LOG_ERR); + return -1; + } - $result=array(); + $result=array(); - $sql = "SELECT"; - $sql.= " MIN(t.task_datehour) as min_date,"; - $sql.= " MAX(t.task_datehour) as max_date,"; - $sql.= " SUM(t.task_duration) as total_duration,"; - $sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as total_amount,"; - $sql.= " COUNT(t.rowid) as nblines,"; - $sql.= " SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; - $sql.= " WHERE t.fk_task = ".$id; - if ($userid > 0) $sql.=" AND t.fk_user = ".$userid; + $sql = "SELECT"; + $sql.= " MIN(t.task_datehour) as min_date,"; + $sql.= " MAX(t.task_datehour) as max_date,"; + $sql.= " SUM(t.task_duration) as total_duration,"; + $sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as total_amount,"; + $sql.= " COUNT(t.rowid) as nblines,"; + $sql.= " SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; + $sql.= " WHERE t.fk_task = ".$id; + if ($userid > 0) $sql.=" AND t.fk_user = ".$userid; - dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); - $result['min_date'] = $obj->min_date; // deprecated. use the ->timespent_xxx instead - $result['max_date'] = $obj->max_date; // deprecated. use the ->timespent_xxx instead - $result['total_duration'] = $obj->total_duration; // deprecated. use the ->timespent_xxx instead + $result['min_date'] = $obj->min_date; // deprecated. use the ->timespent_xxx instead + $result['max_date'] = $obj->max_date; // deprecated. use the ->timespent_xxx instead + $result['total_duration'] = $obj->total_duration; // deprecated. use the ->timespent_xxx instead - $this->timespent_min_date=$this->db->jdate($obj->min_date); - $this->timespent_max_date=$this->db->jdate($obj->max_date); - $this->timespent_total_duration=$obj->total_duration; - $this->timespent_total_amount=$obj->total_amount; - $this->timespent_nblinesnull=($obj->nblinesnull?$obj->nblinesnull:0); - $this->timespent_nblines=($obj->nblines?$obj->nblines:0); + $this->timespent_min_date=$this->db->jdate($obj->min_date); + $this->timespent_max_date=$this->db->jdate($obj->max_date); + $this->timespent_total_duration=$obj->total_duration; + $this->timespent_total_amount=$obj->total_amount; + $this->timespent_nblinesnull=($obj->nblinesnull?$obj->nblinesnull:0); + $this->timespent_nblines=($obj->nblines?$obj->nblines:0); - $this->db->free($resql); - } - else - { - dol_print_error($this->db); - } - return $result; - } + $this->db->free($resql); + } + else + { + dol_print_error($this->db); + } + return $result; + } - /** - * Calculate quantity and value of time consumed using the thm (hourly amount value of work for user entering time) - * - * @param User $fuser Filter on a dedicated user - * @param string $dates Start date (ex 00:00:00) - * @param string $datee End date (ex 23:59:59) - * @return array Array of info for task array('amount','nbseconds','nblinesnull') - */ - function getSumOfAmount($fuser='', $dates='', $datee='') - { - global $langs; + /** + * Calculate quantity and value of time consumed using the thm (hourly amount value of work for user entering time) + * + * @param User $fuser Filter on a dedicated user + * @param string $dates Start date (ex 00:00:00) + * @param string $datee End date (ex 23:59:59) + * @return array Array of info for task array('amount','nbseconds','nblinesnull') + */ + function getSumOfAmount($fuser='', $dates='', $datee='') + { + global $langs; - if (empty($id)) $id=$this->id; + if (empty($id)) $id=$this->id; - $result=array(); + $result=array(); - $sql = "SELECT"; - $sql.= " SUM(t.task_duration) as nbseconds,"; - $sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as amount, SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; - $sql.= " WHERE t.fk_task = ".$id; - if (is_object($fuser) && $fuser->id > 0) - { - $sql.=" AND fk_user = ".$fuser->id; - } - if ($dates > 0) + $sql = "SELECT"; + $sql.= " SUM(t.task_duration) as nbseconds,"; + $sql.= " SUM(t.task_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", 0, "t.thm").") as amount, SUM(".$this->db->ifsql("t.thm IS NULL", 1, 0).") as nblinesnull"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; + $sql.= " WHERE t.fk_task = ".$id; + if (is_object($fuser) && $fuser->id > 0) + { + $sql.=" AND fk_user = ".$fuser->id; + } + if ($dates > 0) { $datefieldname="task_datehour"; $sql.=" AND (".$datefieldname." >= '".$this->db->idate($dates)."' OR ".$datefieldname." IS NULL)"; } - if ($datee > 0) + if ($datee > 0) { $datefieldname="task_datehour"; $sql.=" AND (".$datefieldname." <= '".$this->db->idate($datee)."' OR ".$datefieldname." IS NULL)"; } //print $sql; - dol_syslog(get_class($this)."::getSumOfAmount", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - - $result['amount'] = $obj->amount; - $result['nbseconds'] = $obj->nbseconds; - $result['nblinesnull'] = $obj->nblinesnull; - - $this->db->free($resql); - return $result; - } - else + dol_syslog(get_class($this)."::getSumOfAmount", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) { - dol_print_error($this->db); - return $result; - } - } + $obj = $this->db->fetch_object($resql); - /** - * Load one record of time spent - * - * @param int $id Id object - * @return int <0 if KO, >0 if OK - */ - function fetchTimeSpent($id) - { - global $langs; + $result['amount'] = $obj->amount; + $result['nbseconds'] = $obj->nbseconds; + $result['nblinesnull'] = $obj->nblinesnull; - $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_task,"; - $sql.= " t.task_date,"; - $sql.= " t.task_datehour,"; - $sql.= " t.task_date_withhour,"; - $sql.= " t.task_duration,"; - $sql.= " t.fk_user,"; - $sql.= " t.note"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; - $sql.= " WHERE t.rowid = ".$id; + $this->db->free($resql); + return $result; + } + else + { + dol_print_error($this->db); + return $result; + } + } - dol_syslog(get_class($this)."::fetchTimeSpent", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->timespent_id = $obj->rowid; - $this->id = $obj->fk_task; - $this->timespent_date = $this->db->jdate($obj->task_date); - $this->timespent_datehour = $this->db->jdate($obj->task_datehour); - $this->timespent_withhour = $obj->task_date_withhour; - $this->timespent_duration = $obj->task_duration; - $this->timespent_fk_user = $obj->fk_user; - $this->timespent_note = $obj->note; - } - - $this->db->free($resql); - - return 1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - return -1; - } - } - - /** - * Update time spent - * - * @param User $user User id - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function updateTimeSpent($user, $notrigger=0) - { - global $conf,$langs; - - $ret = 0; - - // Clean parameters - if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date; - if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note); - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time SET"; - $sql.= " task_date = '".$this->db->idate($this->timespent_date)."',"; - $sql.= " task_datehour = '".$this->db->idate($this->timespent_datehour)."',"; - $sql.= " task_date_withhour = ".(empty($this->timespent_withhour)?0:1).","; - $sql.= " task_duration = ".$this->timespent_duration.","; - $sql.= " fk_user = ".$this->timespent_fk_user.","; - $sql.= " note = ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null"); - $sql.= " WHERE rowid = ".$this->timespent_id; - - dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG); - if ($this->db->query($sql) ) - { - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('TASK_TIMESPENT_MODIFY',$user); - if ($result < 0) - { - $this->db->rollback(); - $ret = -1; - } - else $ret = 1; - // End call triggers - } - else $ret = 1; - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - $ret = -1; - } - - if ($ret == 1 && ($this->timespent_old_duration != $this->timespent_duration)) - { - $newDuration = $this->timespent_duration - $this->timespent_old_duration; - - $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task"; - $sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->id.")"; - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG); - if (! $this->db->query($sql) ) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - $ret = -2; - } - } - - if ($ret >= 0) $this->db->commit(); - return $ret; - } - - /** - * Delete time spent - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function delTimeSpent($user, $notrigger=0) - { - global $conf, $langs; - - $error=0; - - $this->db->begin(); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time"; - $sql.= " WHERE rowid = ".$this->timespent_id; - - dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - - if (! $error) - { - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('TASK_TIMESPENT_DELETE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } - - if (! $error) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task"; - $sql.= " SET duration_effective = duration_effective - '".$this->timespent_duration."'"; - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG); - if ($this->db->query($sql) ) - { - $result = 0; - } - else - { - $this->error=$this->db->lasterror(); - $result = -2; - } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delTimeSpent ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - else - { - $this->db->commit(); - return 1; - } - } - - /** Load an object from its id and create a new one in database + /** + * Load one record of time spent * - * @param int $fromid Id of object to clone - * @param int $project_id Id of project to attach clone task - * @param int $parent_task_id Id of task to attach clone task - * @param bool $clone_change_dt recalculate date of task regarding new project start date - * @param bool $clone_affectation clone affectation of project - * @param bool $clone_time clone time of project - * @param bool $clone_file clone file of project - * @param bool $clone_note clone note of project - * @param bool $clone_prog clone progress of project - * @return int New id of clone + * @param int $id Id object + * @return int <0 if KO, >0 if OK */ + function fetchTimeSpent($id) + { + global $langs; + + $sql = "SELECT"; + $sql.= " t.rowid,"; + $sql.= " t.fk_task,"; + $sql.= " t.task_date,"; + $sql.= " t.task_datehour,"; + $sql.= " t.task_date_withhour,"; + $sql.= " t.task_duration,"; + $sql.= " t.fk_user,"; + $sql.= " t.note"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; + $sql.= " WHERE t.rowid = ".$id; + + dol_syslog(get_class($this)."::fetchTimeSpent", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->timespent_id = $obj->rowid; + $this->id = $obj->fk_task; + $this->timespent_date = $this->db->jdate($obj->task_date); + $this->timespent_datehour = $this->db->jdate($obj->task_datehour); + $this->timespent_withhour = $obj->task_date_withhour; + $this->timespent_duration = $obj->task_duration; + $this->timespent_fk_user = $obj->fk_user; + $this->timespent_note = $obj->note; + } + + $this->db->free($resql); + + return 1; + } + else + { + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } + + /** + * Update time spent + * + * @param User $user User id + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function updateTimeSpent($user, $notrigger=0) + { + global $conf,$langs; + + $ret = 0; + + // Clean parameters + if (empty($this->timespent_datehour)) $this->timespent_datehour = $this->timespent_date; + if (isset($this->timespent_note)) $this->timespent_note = trim($this->timespent_note); + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_time SET"; + $sql.= " task_date = '".$this->db->idate($this->timespent_date)."',"; + $sql.= " task_datehour = '".$this->db->idate($this->timespent_datehour)."',"; + $sql.= " task_date_withhour = ".(empty($this->timespent_withhour)?0:1).","; + $sql.= " task_duration = ".$this->timespent_duration.","; + $sql.= " fk_user = ".$this->timespent_fk_user.","; + $sql.= " note = ".(isset($this->timespent_note)?"'".$this->db->escape($this->timespent_note)."'":"null"); + $sql.= " WHERE rowid = ".$this->timespent_id; + + dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG); + if ($this->db->query($sql) ) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_TIMESPENT_MODIFY',$user); + if ($result < 0) + { + $this->db->rollback(); + $ret = -1; + } + else $ret = 1; + // End call triggers + } + else $ret = 1; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + $ret = -1; + } + + if ($ret == 1 && ($this->timespent_old_duration != $this->timespent_duration)) + { + $newDuration = $this->timespent_duration - $this->timespent_old_duration; + + $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task"; + $sql.= " SET duration_effective = (SELECT SUM(task_duration) FROM ".MAIN_DB_PREFIX."projet_task_time as ptt where ptt.fk_task = ".$this->db->escape($this->id).")"; + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG); + if (! $this->db->query($sql) ) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + $ret = -2; + } + } + + if ($ret >= 0) $this->db->commit(); + return $ret; + } + + /** + * Delete time spent + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function delTimeSpent($user, $notrigger=0) + { + global $conf, $langs; + + $error=0; + + $this->db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time"; + $sql.= " WHERE rowid = ".$this->timespent_id; + + dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_TIMESPENT_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + if (! $error) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task"; + $sql.= " SET duration_effective = duration_effective - ".$this->db->escape($this->timespent_duration?$this->timespent_duration:0); + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG); + if ($this->db->query($sql) ) + { + $result = 0; + } + else + { + $this->error=$this->db->lasterror(); + $result = -2; + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::delTimeSpent ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return 1; + } + } + + /** Load an object from its id and create a new one in database + * + * @param int $fromid Id of object to clone + * @param int $project_id Id of project to attach clone task + * @param int $parent_task_id Id of task to attach clone task + * @param bool $clone_change_dt recalculate date of task regarding new project start date + * @param bool $clone_affectation clone affectation of project + * @param bool $clone_time clone time of project + * @param bool $clone_file clone file of project + * @param bool $clone_note clone note of project + * @param bool $clone_prog clone progress of project + * @return int New id of clone + */ function createFromClone($fromid,$project_id,$parent_task_id,$clone_change_dt=false,$clone_affectation=false,$clone_time=false,$clone_file=false,$clone_note=false,$clone_prog=false) { global $user,$langs,$conf; @@ -1383,39 +1394,39 @@ class Task extends CommonObject $clone_task->id = 0; $clone_task->ref = $defaultref; - $clone_task->fk_project = $project_id; - $clone_task->fk_task_parent = $parent_task_id; - $clone_task->date_c = $datec; - $clone_task->planned_workload = $origin_task->planned_workload; + $clone_task->fk_project = $project_id; + $clone_task->fk_task_parent = $parent_task_id; + $clone_task->date_c = $datec; + $clone_task->planned_workload = $origin_task->planned_workload; $clone_task->rang = $origin_task->rang; - //Manage Task Date - if ($clone_change_dt) - { - $projectstatic=new Project($this->db); - $projectstatic->fetch($ori_project_id); + //Manage Task Date + if ($clone_change_dt) + { + $projectstatic=new Project($this->db); + $projectstatic->fetch($ori_project_id); - //Origin project strat date - $orign_project_dt_start = $projectstatic->date_start; + //Origin project strat date + $orign_project_dt_start = $projectstatic->date_start; - //Calcultate new task start date with difference between origin proj start date and origin task start date - if (!empty($clone_task->date_start)) - { + //Calcultate new task start date with difference between origin proj start date and origin task start date + if (!empty($clone_task->date_start)) + { $clone_task->date_start = $now + $clone_task->date_start - $orign_project_dt_start; - } + } - //Calcultate new task end date with difference between origin proj end date and origin task end date - if (!empty($clone_task->date_end)) - { + //Calcultate new task end date with difference between origin proj end date and origin task end date + if (!empty($clone_task->date_end)) + { $clone_task->date_end = $now + $clone_task->date_end - $orign_project_dt_start; - } + } - } + } if (!$clone_prog) - { - $clone_task->progress=0; - } + { + $clone_task->progress=0; + } // Create clone $result=$clone_task->create($user); @@ -1433,15 +1444,15 @@ class Task extends CommonObject $clone_task_id=$clone_task->id; $clone_task_ref = $clone_task->ref; - //Note Update + //Note Update if (!$clone_note) - { - $clone_task->note_private=''; - $clone_task->note_public=''; - } - else - { - $this->db->begin(); + { + $clone_task->note_private=''; + $clone_task->note_public=''; + } + else + { + $this->db->begin(); $res=$clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES),'_public'); if ($res < 0) { @@ -1466,7 +1477,7 @@ class Task extends CommonObject { $this->db->commit(); } - } + } //Duplicate file if ($clone_file) @@ -1475,18 +1486,18 @@ class Task extends CommonObject //retreive project origin ref to know folder to copy $projectstatic=new Project($this->db); - $projectstatic->fetch($ori_project_id); - $ori_project_ref=$projectstatic->ref; + $projectstatic->fetch($ori_project_id); + $ori_project_ref=$projectstatic->ref; - if ($ori_project_id!=$project_id) - { - $projectstatic->fetch($project_id); - $clone_project_ref=$projectstatic->ref; - } - else - { - $clone_project_ref=$ori_project_ref; - } + if ($ori_project_id!=$project_id) + { + $projectstatic->fetch($project_id); + $clone_project_ref=$projectstatic->ref; + } + else + { + $clone_project_ref=$ori_project_ref; + } $clone_task_dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($clone_project_ref). "/" . dol_sanitizeFileName($clone_task_ref); $ori_task_dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($ori_project_ref). "/" . dol_sanitizeFileName($fromid); @@ -1653,8 +1664,8 @@ class Task extends CommonObject if ($statut==3) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4'); if ($statut==4) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6'); if ($statut==5) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut5');*/ - //return $this->progress.' %'; - return ' '; + //return $this->progress.' %'; + return ' '; } } @@ -1699,65 +1710,114 @@ class Task extends CommonObject */ function load_board($user) { - global $conf, $langs; + global $conf, $langs; - $mine=0; $socid=$user->societe_id; + $mine=0; $socid=$user->societe_id; - $projectstatic = new Project($this->db); - $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,$mine,1,$socid); + $projectstatic = new Project($this->db); + $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,$mine,1,$socid); - // List of tasks (does not care about permissions. Filtering will be done later) - $sql = "SELECT p.rowid as projectid, p.fk_statut as projectstatus,"; - $sql.= " t.rowid as taskid, t.progress as progress, t.fk_statut as status,"; - $sql.= " t.dateo as date_start, t.datee as datee"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; - if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; - $sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; - $sql.= " WHERE p.entity IN (".getEntity('project', 0).')'; - $sql.= " AND p.fk_statut = 1"; - $sql.= " AND t.fk_projet = p.rowid"; - $sql.= " AND t.progress < 100"; // tasks to do - if ($mine || ! $user->rights->projet->all->lire) $sql.= " AND p.rowid IN (".$projectsListId.")"; - // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser - //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; - if ($socid) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))"; - //print $sql; - $resql=$this->db->query($sql); - if ($resql) - { - $task_static = new Task($this->db); + // List of tasks (does not care about permissions. Filtering will be done later) + $sql = "SELECT p.rowid as projectid, p.fk_statut as projectstatus,"; + $sql.= " t.rowid as taskid, t.progress as progress, t.fk_statut as status,"; + $sql.= " t.dateo as date_start, t.datee as datee"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; + if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; + $sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; + $sql.= " WHERE p.entity IN (".getEntity('project', 0).')'; + $sql.= " AND p.fk_statut = 1"; + $sql.= " AND t.fk_projet = p.rowid"; + $sql.= " AND t.progress < 100"; // tasks to do + if ($mine || ! $user->rights->projet->all->lire) $sql.= " AND p.rowid IN (".$projectsListId.")"; + // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser + //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + if ($socid) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))"; + //print $sql; + $resql=$this->db->query($sql); + if ($resql) + { + $task_static = new Task($this->db); - $response = new WorkboardResponse(); - $response->warning_delay = $conf->projet->task->warning_delay/60/60/24; - $response->label = $langs->trans("OpenedTasks"); - if ($user->rights->projet->all->lire) $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project'; - else $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&mainmenu=project'; - $response->img = img_object('',"task"); + $response = new WorkboardResponse(); + $response->warning_delay = $conf->projet->task->warning_delay/60/60/24; + $response->label = $langs->trans("OpenedTasks"); + if ($user->rights->projet->all->lire) $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project'; + else $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&mainmenu=project'; + $response->img = img_object('',"task"); - // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) - { - $response->nbtodo++; + // This assignment in condition is not a bug. It allows walking the results. + while ($obj=$this->db->fetch_object($resql)) + { + $response->nbtodo++; - $task_static->projectstatus = $obj->projectstatus; - $task_static->progress = $obj->progress; - $task_static->fk_statut = $obj->status; - $task_static->date_end = $this->db->jdate($obj->datee); + $task_static->projectstatus = $obj->projectstatus; + $task_static->progress = $obj->progress; + $task_static->fk_statut = $obj->status; + $task_static->date_end = $this->db->jdate($obj->datee); - if ($task_static->hasDelay()) { - $response->nbtodolate++; - } - } + if ($task_static->hasDelay()) { + $response->nbtodolate++; + } + } - return $response; - } - else - { - $this->error=$this->db->error(); - return -1; - } + return $response; + } + else + { + $this->error=$this->db->error(); + return -1; + } + } + + + /** + * Charge indicateurs this->nb de tableau de bord + * + * @return int <0 if ko, >0 if ok + */ + function load_state_board() + { + global $user; + + $mine=0; $socid=$user->societe_id; + + $projectstatic = new Project($this->db); + $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,$mine,1,$socid); + + // List of tasks (does not care about permissions. Filtering will be done later) + $sql = "SELECT count(p.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; + if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; + $sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; + $sql.= " WHERE p.entity IN (".getEntity('project', 0).')'; + $sql.= " AND t.fk_projet = p.rowid"; // tasks to do + if ($mine || ! $user->rights->projet->all->lire) $sql.= " AND p.rowid IN (".$projectsListId.")"; + // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser + //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + if ($socid) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id.") OR (s.rowid IS NULL))"; + + $resql=$this->db->query($sql); + if ($resql) + { + + // This assignment in condition is not a bug. It allows walking the results. + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["tasks"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } } /** @@ -1767,16 +1827,16 @@ class Task extends CommonObject */ public function hasDelay() { - global $conf; + global $conf; - if (! ($this->progress >= 0 && $this->progress < 100)) { - return false; - } + if (! ($this->progress >= 0 && $this->progress < 100)) { + return false; + } - $now = dol_now(); + $now = dol_now(); - $datetouse = ($this->date_end > 0) ? $this->date_end : ($this->datee > 0 ? $this->datee : 0); + $datetouse = ($this->date_end > 0) ? $this->date_end : ($this->datee > 0 ? $this->datee : 0); - return ($datetouse > 0 && ($datetouse < ($now - $conf->projet->task->warning_delay))); + return ($datetouse > 0 && ($datetouse < ($now - $conf->projet->task->warning_delay))); } -} +} \ No newline at end of file diff --git a/htdocs/projet/comment.php b/htdocs/projet/comment.php new file mode 100644 index 00000000000..4e3d52a2f37 --- /dev/null +++ b/htdocs/projet/comment.php @@ -0,0 +1,189 @@ + + * Copyright (C) 2006-2017 Laurent Destailleur + * Copyright (C) 2010-2012 Regis Houssin + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/projet/tasks/task.php + * \ingroup project + * \brief Page of a project task + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + +$langs->load("projects"); +$langs->load("companies"); + +$id=GETPOST('id','int'); +$idcomment=GETPOST('idcomment','int'); +$ref=GETPOST("ref",'alpha',1); // task ref +$objectref=GETPOST("taskref",'alpha'); // task ref +$action=GETPOST('action','alpha'); +$confirm=GETPOST('confirm','alpha'); +$withproject=GETPOST('withproject','int'); +$project_ref=GETPOST('project_ref','alpha'); +$planned_workload=((GETPOST('planned_workloadhour','int')!='' || GETPOST('planned_workloadmin','int')!='') ? (GETPOST('planned_workloadhour','int')>0?GETPOST('planned_workloadhour','int')*3600:0) + (GETPOST('planned_workloadmin','int')>0?GETPOST('planned_workloadmin','int')*60:0) : ''); + +// Security check +$socid=0; +//if ($user->societe_id > 0) $socid = $user->societe_id; // For external user, no check is done on company because readability is managed by public status of project and assignement. +if (! $user->rights->projet->lire) accessforbidden(); + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('projectcard','globalcard')); + +$object = new Project($db); +$extrafields = new ExtraFields($db); +$object = new Project($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +if ($id > 0 || ! empty($ref)) +{ + $ret = $object->fetch($id,$ref); // If we create project, ref may be defined into POST but record does not yet exists into database + if ($ret > 0) { + $object->fetch_thirdparty(); + $id=$object->id; + } +} + +// include comment actions +include DOL_DOCUMENT_ROOT . '/core/actions_comments.inc.php'; + +/* + * View +*/ + + +llxHeader('', $langs->trans("CommentPage")); + +$form = new Form($db); +$formother = new FormOther($db); +$formfile = new FormFile($db); + +// Tabs for project +$tab = 'project_comment'; +$head = project_prepare_head($object); +dol_fiche_head($head, $tab, $langs->trans("Project"), - 1, ($object->public ? 'projectpub' : 'project')); + +$param = ($mode == 'mine' ? '&mode=mine' : ''); + +// Project card + +$linkback = '' . $langs->trans("BackToList") . ''; + +$morehtmlref = '
    '; +// Title +$morehtmlref .= $object->title; +// Thirdparty +if ($object->thirdparty->id > 0) { + $morehtmlref .= '
    ' . $langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); +} +$morehtmlref .= '
    '; + +// Define a complementary filter for search of next/prev ref. +if (! $user->rights->projet->all->lire) { + $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); + $object->next_prev_filter = " rowid in (" . (count($objectsListId) ? join(',', array_keys($objectsListId)) : '0') . ")"; +} + +dol_banner_tab($object, 'project_ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + +print '
    '; +print '
    '; +print '
    '; + +print ''; + +// Visibility +print ''; + +// Date start - end +print ''; + +// Budget +print ''; + +// Other attributes +$cols = 2; +// include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + +print '
    ' . $langs->trans("Visibility") . ''; +if ($object->public) print $langs->trans('SharedProject'); +else + print $langs->trans('PrivateProject'); +print '
    ' . $langs->trans("DateStart") . ' - ' . $langs->trans("DateEnd") . ''; +print dol_print_date($object->date_start, 'day'); +$end = dol_print_date($object->date_end, 'day'); +if ($end) print ' - ' . $end; +print '
    ' . $langs->trans("Budget") . ''; +if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency); +print '
    '; + +print '
    '; +print '
    '; +print '
    '; +print '
    '; + +print ''; + +// Description +print ''; + +// Categories +if ($conf->categorie->enabled) { + print '"; +} + +// Nb comments +print ''; + +print '
    ' . $langs->trans("Description") . ''; +print nl2br($object->description); +print '
    ' . $langs->trans("Categories") . ''; + print $form->showCategories($object->id, 'project', 1); + print "
    '.$langs->trans("NbComments").''; +print $object->getNbComments(); +print '
    '; + +print '
    '; +print '
    '; +print '
    '; + +print '
    '; + +dol_fiche_end(); + +print '
    '; + +// Include comment tpl view +include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_comment.tpl.php'; + + +llxFooter(); +$db->close(); diff --git a/htdocs/projet/document.php b/htdocs/projet/document.php index 8777d83e419..fbf9574bd75 100644 --- a/htdocs/projet/document.php +++ b/htdocs/projet/document.php @@ -20,7 +20,7 @@ /** * \file htdocs/projet/document.php * \ingroup project - * \brief Page de gestion des documents attachees a un projet + * \brief Page to managed related documents linked to a project */ require '../main.inc.php'; @@ -106,11 +106,11 @@ if ($object->id > 0) $totalsize+=$file['size']; } - + // Project card - + $linkback = ''.$langs->trans("BackToList").''; - + $morehtmlref='
    '; // Title $morehtmlref.=$object->title; @@ -120,19 +120,19 @@ if ($object->id > 0) $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); } $morehtmlref.='
    '; - + // Define a complementary filter for search of next/prev ref. if (! $user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; } - + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - - + + print '
    '; - print '
    '; + print '
    '; print ''; @@ -141,10 +141,10 @@ if ($object->id > 0) print ''; print "
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    \n"; - + print '
    '; - + dol_fiche_end(); $modulepart = 'project'; diff --git a/htdocs/projet/element.php b/htdocs/projet/element.php index ae9872b70a0..710ccb37500 100644 --- a/htdocs/projet/element.php +++ b/htdocs/projet/element.php @@ -51,6 +51,7 @@ if (! empty($conf->don->enabled)) require_once DOL_DOCUMENT_ROOT.'/don/class/d if (! empty($conf->loan->enabled)) require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; if (! empty($conf->stock->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; if (! empty($conf->tax->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; +if (! empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; $langs->load("projects"); $langs->load("companies"); @@ -439,6 +440,19 @@ $listofreferent=array( 'datefieldname'=>'datem', 'disableamount'=>0, 'test'=>($conf->stock->enabled && $user->rights->stock->mouvement->lire && ! empty($conf->global->STOCK_MOVEMENT_INTO_PROJECT_OVERVIEW))), +'variouspayment'=>array( + 'name'=>"VariousPayments", + 'title'=>"ListVariousPaymentsAssociatedProject", + 'class'=>'PaymentVarious', + 'table'=>'payment_various', + 'datefieldname'=>'datev', + 'margin'=>'minus', + 'disableamount'=>0, + 'urlnew'=>DOL_URL_ROOT.'/compta/bank/various_payment/card.php?action=create&projectid='.$id.'&socid='.$socid, + 'lang'=>'banks', + 'buttonnew'=>'AddVariousPayment', + 'testnew'=>$user->rights->banque->modifier, + 'test'=>$conf->banque->enabled && $user->rights->banque->lire), /* No need for this, available on dedicated tab "Agenda/Events" 'agenda'=>array( 'name'=>"Agenda", @@ -637,32 +651,6 @@ foreach ($listofreferent as $key => $value) } } - /*switch ($classname) { - case 'FactureFournisseur': - $newclassname = 'SupplierInvoice'; - break; - case 'Facture': - $newclassname = 'Bill'; - break; - case 'Propal': - $newclassname = 'CommercialProposal'; - break; - case 'Commande': - $newclassname = 'Order'; - break; - case 'Expedition': - $newclassname = 'Sending'; - break; - case 'Contrat': - $newclassname = 'Contract'; - break; - case 'MouvementStock': - $newclassname = 'StockMovement'; - break; - default: - $newclassname = $classname; - }*/ - print ''; // Module print ''.$name.''; @@ -692,7 +680,6 @@ print ''; print ""; - print '

    '; print '
    '; @@ -730,7 +717,7 @@ foreach ($listofreferent as $key => $value) if (! empty($conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS)) $idtofilterthirdparty.=','.$conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS; } - if (empty($conf->global->PROJECT_LINK_ON_OVERWIEW_DISABLED) && $idtofilterthirdparty) + if (empty($conf->global->PROJECT_LINK_ON_OVERWIEW_DISABLED) && $idtofilterthirdparty && !in_array($tablename, array('payment_various'))) { $selectList=$formproject->select_element($tablename, $idtofilterthirdparty, 'minwidth300'); if (! $selectList || ($selectList<0)) @@ -770,7 +757,7 @@ foreach ($listofreferent as $key => $value) print ''; print ''; - // Remove link + // Remove link column print ''; // Ref print ''.$langs->trans("Ref").''; @@ -782,6 +769,7 @@ foreach ($listofreferent as $key => $value) // Thirdparty or user print ''; @@ -860,11 +848,15 @@ foreach ($listofreferent as $key => $value) } print ''; + // Remove link print '\n"; @@ -911,7 +903,8 @@ foreach ($listofreferent as $key => $value) $date=''; $total_time_by_line = null; if ($tablename == 'expensereport_det') $date = $element->date; // No draft status on lines elseif ($tablename == 'stock_mouvement') $date = $element->datem; - if ($tablename == 'chargesociales') $date = $element->date_ech; + elseif ($tablename == 'payment_various') $date = $element->datev; + elseif ($tablename == 'chargesociales') $date = $element->date_ech; elseif (! empty($element->status) || ! empty($element->statut) || ! empty($element->fk_status)) { if ($tablename == 'don') $date = $element->datedon; @@ -922,7 +915,7 @@ foreach ($listofreferent as $key => $value) elseif ($tablename == 'supplier_proposal') $date=$element->date_validation; // There is no other date for this elseif ($tablename == 'fichinter') $date=$element->datev; // There is no other date for this elseif ($tablename == 'projet_task') $date=''; // We show no date. Showing date of beginning of task make user think it is date of time consumed - else + else { $date=$element->date; // invoice, ... if (empty($date)) $date=$element->date_contrat; @@ -976,7 +969,7 @@ foreach ($listofreferent as $key => $value) { $total_ht_by_line=null; $othermessage=''; - if ($tablename == 'don' || $tablename == 'chargesociales') $total_ht_by_line=$element->amount; + if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various') $total_ht_by_line=$element->amount; else if($tablename == 'fichinter') $total_ht_by_line=$element->getAmount(); elseif ($tablename == 'stock_mouvement') $total_ht_by_line=$element->price*abs($element->qty); elseif (in_array($tablename, array('projet_task'))) @@ -1017,7 +1010,7 @@ foreach ($listofreferent as $key => $value) if (empty($value['disableamount'])) { $total_ttc_by_line=null; - if ($tablename == 'don' || $tablename == 'chargesociales') $total_ttc_by_line=$element->amount; + if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various') $total_ttc_by_line=$element->amount; else if($tablename == 'fichinter') $total_ttc_by_line=$element->getAmount(); elseif ($tablename == 'stock_mouvement') $total_ttc_by_line=$element->price*abs($element->qty); elseif ($tablename == 'projet_task') @@ -1154,13 +1147,11 @@ foreach ($listofreferent as $key => $value) } // Enhance with select2 -$nodatarole=''; if ($conf->use_javascript_ajax) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; $comboenhancement = ajax_combobox('.elementselect'); $out.=$comboenhancement; - $nodatarole=($comboenhancement?' data-role="none"':''); print $comboenhancement; } diff --git a/htdocs/projet/ganttchart.inc.php b/htdocs/projet/ganttchart.inc.php index 47ad04d1dc7..58d212db7bd 100644 --- a/htdocs/projet/ganttchart.inc.php +++ b/htdocs/projet/ganttchart.inc.php @@ -99,18 +99,39 @@ if (g.getDivId() != null) g.setShowComp(1); // Show/Hide % Complete(0/1) g.setShowStartDate(1); // Show/Hide % Complete(0/1) g.setShowEndDate(1); // Show/Hide % Complete(0/1) - g.setFormatArr("day","week","month","quarter") // Set format options (up to 4 : "minute","hour","day","week","month","quarter") + g.setShowTaskInfoLink(1); + g.setFormatArr("day","week","month") // Set format options (up to 4 : "minute","hour","day","week","month","quarter") g.setCaptionType('Caption'); // Set to Show Caption (None,Caption,Resource,Duration,Complete) + g.setUseFade(0); + g.setDayColWidth(20); /* g.setShowTaskInfoLink(1) */ + g.addLang('getDefaultLang(1);?>', vLangs['getDefaultLang(1);?>']); + g.setLang('getDefaultLang(1);?>'); fetch($t['task_project_id']); + $tmpt = array( + 'task_id'=> '-'.$t['task_project_id'], 'task_name'=>$projecttmp->ref.' '.$projecttmp->title, 'task_resources'=>'', 'task_start_date'=>'', 'task_end_date'=>'', + 'task_is_group'=>1, 'task_css'=>'ggroupblack', 'task_milestone'=> 0, 'task_parent'=>0, 'task_notes'=>''); + constructGanttLine($tasks, $tmpt, array(), 0, $t['task_project_id']); + $old_project_id = $t['task_project_id']; + } + + if ($t["task_parent"] <= 0) + { + constructGanttLine($tasks, $t, $task_dependencies, $level, $t['task_project_id']); + findChildGanttLine($tasks, $t["task_id"], $task_dependencies, $level+1); } } ?> @@ -133,12 +154,12 @@ else * * @param array $tarr Array of all tasks * @param array $task Array with properties of one task - * @param Project $project_dependencies Project object + * @param array $task_dependencies Task dependencies (array(array(0=>idtask,1=>idtasktofinishfisrt)) * @param int $level Level * @param int $project_id Id of project * @return void */ -function constructGanttLine($tarr,$task,$project_dependencies,$level=0,$project_id=null) +function constructGanttLine($tarr, $task, $task_dependencies, $level=0, $project_id=null) { global $dateformatinput2; @@ -152,26 +173,40 @@ function constructGanttLine($tarr,$task,$project_dependencies,$level=0,$project_ // Define depend (ex: "", "4,13", ...) $depend = ''; $count = 0; - foreach ($project_dependencies as $value) { + foreach ($task_dependencies as $value) { // Not yet used project_dependencies = array(array(0=>idtask,1=>idtasktofinishfisrt)) if ($value[0] == $task['task_id']) { $depend.=($count>0?",":"").$value[1]; $count ++; } } - // $depend .= "\""; + // $depend .= "\""; // Define parent if ($project_id && $level < 0) - $parent = 'p'.$project_id; + { + $parent = '-'.$project_id; + } else - $parent = $task["task_parent"]; + { + $parent = $task["task_parent"]; + } // Define percent $percent = $task['task_percent_complete']?$task['task_percent_complete']:0; // Link (more information) - $link=DOL_URL_ROOT.'/projet/tasks/contact.php?withproject=1&id='.$task["task_id"]; + if ($task["task_id"] < 0) + { + //$link=DOL_URL_ROOT.'/projet/tasks.php?withproject=1&id='.abs($task["task_id"]); + $link=''; + } + else + { + $link=DOL_URL_ROOT.'/projet/tasks/contact.php?withproject=1&id='.$task["task_id"]; + } // Name + //$name=''.$task['task_name'].''; $name=$task['task_name']; + /*for($i=0; $i < $level; $i++) { $name=' - '.$name; }*/ @@ -195,7 +230,7 @@ function constructGanttLine($tarr,$task,$project_dependencies,$level=0,$project_
    pGroup
    (optional) indicates whether this is a group task (parent) - Numeric; 0 = normal task, 1 = standard group task, 2 = combined group task*
    pParent
    (required) identifies a parent pID, this causes this task to be a child of identified task. Numeric, top level tasks should have pParent set to 0
    pOpen
    (required) indicates whether a standard group task is open when chart is first drawn. Value must be set for all items but is only used by standard group tasks. Numeric, 1 = open, 0 = closed
    -
    pDepend
    (optional) comma separated list of id's this task is dependent on. A line will be drawn from each listed task to this item
    Each id can optionally be followed by a dependency type suffix. Valid values are:
    'FS' - Finish to Start (default if suffix is omitted)
    'SF' - Start to Finish
    'SS' - Start to Start
    'FF' - Finish to Finish
    If present the suffix must be added directly to the id e.g. '123SS'
    +
    pDepend
    (optional) comma separated list of id's this task is dependent on. A line will be drawn from each listed task to this item
    Each id can optionally be followed by a dependency type suffix. Valid values are:
    'FS' - Finish to Start (default if suffix is omitted)
    'SF' - Start to Finish
    'SS' - Start to Start
    'FF' - Finish to Finish
    If present the suffix must be added directly to the id e.g. '123SS'
    pCaption
    (optional) caption that will be added after task bar if CaptionType set to "Caption"
    pNotes
    (optional) Detailed task information that will be displayed in tool tip for this task
    pGantt
    (required) javascript JSGantt.GanttChart object from which to take settings. Defaults to "g" for backwards compatibility
    @@ -204,9 +239,19 @@ function constructGanttLine($tarr,$task,$project_dependencies,$level=0,$project_ //$note=""; $s = "\n// Add taks id=".$task["task_id"]." level = ".$level."\n"; - // $s.= "g.AddTaskItem(new JSGantt.TaskItem(".$task['task_id'].",'".dol_escape_js($name)."','".$start_date."', '".$end_date."', '".$task['task_color']."', '".$link."', ".$task['task_milestone'].", '".$resources."', ".($percent >= 0 ? $percent : 0).", ".($task["task_is_group"]>0?1:0).", '".$parent."', 1, '".($depend?$depend:"")."', '".$note."'));"; + + //$task["task_is_group"]=1; // When task_is_group is 1, content will be autocalculated from sum of all low tasks + // For JSGanttImproved - $s.= "g.AddTaskItem(new JSGantt.TaskItem(".$task['task_id'].",'".dol_escape_js(trim($name))."','".$start_date."', '".$end_date."', '".$task['task_css']."', '".$link."', ".$task['task_milestone'].", '".dol_escape_js($resources)."', ".($percent >= 0 ? $percent : 0).", ".($task["task_is_group"]).", '".$parent."', 1, '".($depend?$depend:$parent."SS")."', '".($percent >= 0 ? $percent.'%' : '0%')."','".dol_escape_js($task['note'])."'));"; + $css = $task['task_css']; + $line_is_auto_group = $task["task_is_group"]; + //$line_is_auto_group=0; + //if ($line_is_auto_group) $css = 'ggroupblack'; + //$dependency = ($depend?$depend:$parent."SS"); + $dependency = ''; + //$name = str_repeat("..", $level).$name; + + $s.= "g.AddTaskItem(new JSGantt.TaskItem('".$task['task_id']."', '".dol_escape_js(trim($name))."', '".$start_date."', '".$end_date."', '".$css."', '".$link."', ".$task['task_milestone'].", '".dol_escape_js($resources)."', ".($percent >= 0 ? $percent : 0).", ".$line_is_auto_group.", '".$parent."', 1, '".$dependency."', '".(empty($task["task_is_group"]) ? (($percent >= 0 && $percent != '') ? $percent.'%' : '') : '')."', '".dol_escape_js($task['note'])."', g));"; echo $s; @@ -217,19 +262,34 @@ function constructGanttLine($tarr,$task,$project_dependencies,$level=0,$project_ * * @param array $tarr tarr * @param int $parent Parent - * @param Project $project_dependencies Project object + * @param array $task_dependencies Task dependencies * @param int $level Level * @return void */ -function findChildGanttLine($tarr,$parent,$project_dependencies,$level) +function findChildGanttLine($tarr, $parent, $task_dependencies, $level) { $n=count($tarr); + + echo "\n"; + echo "/* g.AddTaskItem(new JSGantt.TaskItem(task_id, 'label', 'start_date', 'end_date', 'css', 'link', milestone, 'Resources', Compl%, Group, Parent, 1, 'Dependency', 'label','note', g)); */\n"; + + $old_parent_id = 0; for ($x=0; $x < $n; $x++) { if($tarr[$x]["task_parent"] == $parent && $tarr[$x]["task_parent"] != $tarr[$x]["task_id"]) { - constructGanttLine($tarr,$tarr[$x],$project_dependencies,$level,null); - findChildGanttLine($tarr,$tarr[$x]["task_id"],$project_dependencies,$level+1); + // Create a grouping parent task for the new level + /*if (empty($old_parent_id) || $old_parent_id != $tarr[$x]['task_project_id']) + { + $tmpt = array( + 'task_id'=> -98, 'task_name'=>'Level '.$level, 'task_resources'=>'', 'task_start_date'=>'', 'task_end_date'=>'', + 'task_is_group'=>1, 'task_css'=>'ggroupblack', 'task_milestone'=> 0, 'task_parent'=>$tarr[$x]["task_parent"], 'task_notes'=>''); + constructGanttLine($tasks, $tmpt, array(), 0, $tarr[$x]['task_project_id']); + $old_parent_id = $tarr[$x]['task_project_id']; + }*/ + + constructGanttLine($tarr, $tarr[$x], $task_dependencies, $level, null); + findChildGanttLine($tarr, $tarr[$x]["task_id"], $task_dependencies, $level+1); } } } diff --git a/htdocs/projet/ganttview.php b/htdocs/projet/ganttview.php index eb24c58a211..d63f2d2bb62 100644 --- a/htdocs/projet/ganttview.php +++ b/htdocs/projet/ganttview.php @@ -195,28 +195,36 @@ if ($id > 0 || ! empty($ref)) * Buttons actions */ -print '
    '; - -if ($user->rights->projet->all->creer || $user->rights->projet->creer) +if ($id > 0) { - if ($object->public || $userWrite > 0) - { - print ''.$langs->trans('AddTask').''; - } - else - { - print ''.$langs->trans('AddTask').''; - } + + print '
    '; + + if ($user->rights->projet->all->creer || $user->rights->projet->creer) + { + if ($object->public || $userWrite > 0) + { + print ''.$langs->trans('AddTask').''; + } + else + { + print ''.$langs->trans('AddTask').''; + } + } + else + { + print ''.$langs->trans('AddTask').''; + } + + print '
    '; + + print '
    '; } else { - print ''.$langs->trans('AddTask').''; + print_fiche_titre($langs->trans("GanttView")); } -print '
    '; - -print '
    '; - // Get list of tasks in tasksarray and taskarrayfiltered // We need all tasks (even not limited to a user because a task to user @@ -237,24 +245,28 @@ if (count($tasksarray)>0) $datehourformat=$langs->trans("FormatDateShortJQuery").' '.$langs->trans("FormatHourShortJQuery"); // Used by include ganttchart.inc.php later $array_contacts=array(); $tasks=array(); - $project_dependencies=array(); + $task_dependencies=array(); $taskcursor=0; foreach($tasksarray as $key => $val) { $task->fetch($val->id); $tasks[$taskcursor]['task_id']=$val->id; - $tasks[$taskcursor]['task_parent']=$val->fk_parent; + $tasks[$taskcursor]['task_project_id']=$val->fk_project; + $tasks[$taskcursor]['task_parent']=($val->fk_parent ? $val->fk_parent : '-'.$val->fk_project); $tasks[$taskcursor]['task_is_group'] = 0; $tasks[$taskcursor]['task_css'] = 'gtaskblue'; - if($val->fk_parent > 0 && $task->hasChildren()> 0){ + if ($val->fk_parent != 0 && $task->hasChildren()> 0){ $tasks[$taskcursor]['task_is_group']=1; - $tasks[$taskcursor]['task_css'] = 'gtaskred'; + $tasks[$taskcursor]['task_css']='ggroupblack'; + //$tasks[$taskcursor]['task_css'] = 'gtaskblue'; } - elseif($task->hasChildren()> 0) { + elseif ($task->hasChildren()> 0) { $tasks[$taskcursor]['task_is_group'] = 1; - $tasks[$taskcursor]['task_css'] = 'gtaskgreen'; + //$tasks[$taskcursor]['task_is_group'] = 0; + $tasks[$taskcursor]['task_css'] = 'ggroupblack'; + //$tasks[$taskcursor]['task_css'] = 'gtaskblue'; } $tasks[$taskcursor]['task_milestone']='0'; $tasks[$taskcursor]['task_percent_complete']=$val->progress; @@ -315,14 +327,17 @@ if (count($tasksarray)>0) if (! empty($conf->use_javascript_ajax)) { //var_dump($_SESSION); - $dateformatinput='mm/dd/yyyy'; // How the date for data are formated - $dateformatinput2="%m/%d/%Y"; // How the date for data are formated - //var_dump($dateformatinput); + + // How the date for data are formated (format used bu jsgantt) + $dateformatinput='yyyy-mm-dd'; + // How the date for data are formated (format used by dol_print_date) + $dateformatinput2='standard'; + //var_dump($dateformatinput); //var_dump($dateformatinput2); print '
    '; - print '
    '."\n"; + print '
    '."\n"; include_once DOL_DOCUMENT_ROOT.'/projet/ganttchart.inc.php'; print '
    '."\n"; diff --git a/htdocs/projet/graph_opportunities.inc.php b/htdocs/projet/graph_opportunities.inc.php index 10bec155ded..60b0ffa0809 100644 --- a/htdocs/projet/graph_opportunities.inc.php +++ b/htdocs/projet/graph_opportunities.inc.php @@ -1,4 +1,4 @@ -global->PROJECT_USE_OPPORTUNITIES)) { $sql = "SELECT p.fk_opp_status as opp_status, cls.code, COUNT(p.rowid) as nb, SUM(p.opp_amount) as opp_amount, SUM(p.opp_amount * p.opp_percent) as ponderated_opp_amount"; @@ -48,7 +48,8 @@ if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $db->free($resql); $ponderated_opp_amount = $ponderated_opp_amount / 100; - + + print '
    '; print '
    '; if (in_array($tablename, array('projet_task')) && $key == 'project_task') print ''; // if $key == 'project_task', we don't want details per user + elseif (in_array($tablename, array('payment_various'))) print ''; // if $key == 'payment_various', we don't have any thirdparty elseif (in_array($tablename, array('expensereport_det','don','projet_task','stock_mouvement'))) print $langs->trans("User"); else print $langs->trans("ThirdParty"); print '
    '; if ($tablename != 'projet_task' && $tablename != 'stock_mouvement') { - print '' . img_picto($langs->trans('Unlink'), 'editdelete') . ''; + if (empty($conf->global->PROJECT_DISABLE_UNLINK_FROM_OVERVIEW) || $user->admin) // PROJECT_DISABLE_UNLINK_FROM_OVERVIEW is empty by defaut, so this test true + { + print '' . img_picto($langs->trans('Unlink'), 'editdelete') . ''; + } } print "
    '; print ''."\n"; $var=true; @@ -67,7 +68,7 @@ if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $dataseries[]=array('label'=>$labelstatus,'data'=>(isset($valsamount[$status])?(float) $valsamount[$status]:0)); if (! $conf->use_javascript_ajax) { - + print ''; print ''; print ''; @@ -88,7 +89,10 @@ if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) //print $langs->trans("OpportunityPonderatedAmount").' ('.$langs->trans("WonLostExcluded").')'; print $form->textwithpicto($langs->trans("OpportunityPonderatedAmount").' ('.$langs->trans("WonLostExcluded").')', $langs->trans("OpportunityPonderatedAmountDesc"), 1); print ''; - print "
    '.$langs->trans("Statistics").' - '.$langs->trans("OpportunitiesStatusForOpenedProjects").'
    '.$labelstatus.''.price((isset($valsamount[$status])?(float) $valsamount[$status]:0), 0, '', 1, -1, -1, $conf->currency).''.price(price2num($ponderated_opp_amount,'MT'), 0, '', 1, -1, -1, $conf->currency).'

    "; + print ""; + print "
    "; + + print "
    "; } else { diff --git a/htdocs/projet/index.php b/htdocs/projet/index.php index 2188d4bd6a4..a1c68756181 100644 --- a/htdocs/projet/index.php +++ b/htdocs/projet/index.php @@ -94,6 +94,7 @@ else $listofoppstatus=array(); $listofopplabel=array(); $listofoppcode=array(); $sql = "SELECT cls.rowid, cls.code, cls.percent, cls.label"; $sql.= " FROM ".MAIN_DB_PREFIX."c_lead_status as cls"; +$sql.= " WHERE active=1"; $resql = $db->query($sql); if ( $resql ) { @@ -159,6 +160,7 @@ print_projecttasks_array($db, $form, $socid, $projectsListId, 0, 0, $listofoppst print '
    '; +print '
    '; print ''; print ''; print_liste_field_titre("OpenedProjectsByThirdparties",$_SERVER["PHP_SELF"],"s.nom","","",'',$sortfield,$sortorder); @@ -213,6 +215,7 @@ else dol_print_error($db); } print "
    "; +print '
    '; if (! empty($conf->global->PROJECT_SHOW_PROJECT_LIST_ON_PROJECT_AREA)) { diff --git a/htdocs/projet/info.php b/htdocs/projet/info.php index 8e506b5d454..124371e299b 100644 --- a/htdocs/projet/info.php +++ b/htdocs/projet/info.php @@ -156,42 +156,32 @@ if ($permok) } -print '
    '; - +//print '
    '; +$morehtmlcenter=''; if (! empty($conf->agenda->enabled)) { if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) { - print ''.$langs->trans("AddAction").''; + $morehtmlcenter.=''.$langs->trans("AddAction").''; } else { - print ''.$langs->trans("AddAction").''; + $morehtmlcenter.=''.$langs->trans("AddAction").''; } } -print '
    '; - +//print '
    '; if (!empty($object->id)) { - $param='&id='.$object->id; + print '
    '; + + $param='&id='.$object->id; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - print load_fiche_titre($langs->trans("ActionsOnProject"),'',''); - - // List of actions on element - /*include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown=$formactions->showactions($object,'project',0);*/ - - // List of todo actions - //show_actions_todo($conf,$langs,$db,$object,null,0,$actioncode); - - // List of done actions - //show_actions_done($conf,$langs,$db,$object,null,0,$actioncode); - + print_barre_liste($langs->trans("ActionsOnProject"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $morehtmlcenter, 0, -1, '', '', '', '', 0, 1, 1); + // List of all actions $filters=array(); $filters['search_agenda_label']=$search_agenda_label; diff --git a/htdocs/projet/jsgantt_language.js.php b/htdocs/projet/jsgantt_language.js.php index 7aafd97fb45..a702432998e 100644 --- a/htdocs/projet/jsgantt_language.js.php +++ b/htdocs/projet/jsgantt_language.js.php @@ -38,6 +38,7 @@ require_once __DIR__.'/../main.inc.php'; top_httphead('text/javascript'); global $langs; +$langs->load("projects"); ?> var vLangs={'getDefaultLang(1);?>': @@ -46,8 +47,8 @@ var vLangs={'getDefaultLang(1);?>': 'week':'transnoentities('Week'); ?>','month':'transnoentities('Month'); ?>','quarter':'transnoentities('Quadri'); ?>', 'hours':'transnoentities('Hours'); ?>','days':'transnoentities('Days'); ?>','weeks':'transnoentities('Weeks');?>', 'months':'transnoentities('Months'); ?>','quarters':'transnoentities('Quadri'); ?>','hr':'Hr','dy':'transnoentities('Day'); ?>','wk':'transnoentities('Week'); ?>','mth':'transnoentities('Month'); ?>','qtr':'transnoentities('Quadri'); ?>','hrs':'transnoentities('Hours'); ?>', - 'dys':'transnoentities('Days'); ?>','wks':'transnoentities('Weeks'); ?>','mths':'transnoentities('Months'); ?>','qtrs':'transnoentities('Quadri'); ?>','resource':'transnoentities('Resources')); ?>','duration':'transnoentities('Duration')); ?>','comp':'% transnoentities('Total')); ?>', - 'completion':'transnoentities('Total'); ?>','startdate':'transnoentities('DateStart'); ?>','enddate':'transnoentities('DateEnd'); ?>','moreinfo':'transnoentities('MoreInformation')); ?>', + 'dys':'transnoentities('Days'); ?>','wks':'transnoentities('Weeks'); ?>','mths':'transnoentities('Months'); ?>','qtrs':'transnoentities('Quadri'); ?>','resource':'transnoentities('Resource')); ?>','duration':'transnoentities('Duration')); ?>','comp':'%', + 'completion':'transnoentities('Total'); ?>','startdate':'transnoentities('DateStart'); ?>','enddate':'transnoentities('DateEnd'); ?>','moreinfo':'transnoentities('ShowTask')); ?>', 'notes':'transnoentities('NotePublic'); ?>', 'january':'transnoentities('January'); ?>','february':'transnoentities('February'); ?>','march':'transnoentities('March'); ?>','april':'transnoentities('April'); ?>','maylong':'transnoentities('May'); ?>','june':'transnoentities('June'); ?>','july':'transnoentities('July'); ?>', 'august':'transnoentities('August'); ?>','september':'transnoentities('September'); ?>','october':'transnoentities('October'); ?>','november':'transnoentities('November'); ?>','december':'transnoentities('December'); ?>', diff --git a/htdocs/projet/list.php b/htdocs/projet/list.php index 6eaf231a5cb..08c22f30a37 100644 --- a/htdocs/projet/list.php +++ b/htdocs/projet/list.php @@ -112,32 +112,32 @@ $fieldstosearchall = array( 'p.ref'=>"Ref", 'p.title'=>"Label", 's.nom'=>"ThirdPartyName", - "p.note_public"=>"NotePublic" + "p.note_public"=>"NotePublic" ); if (empty($user->socid)) $fieldstosearchall["p.note_private"]="NotePrivate"; $arrayfields=array( - 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'p.title'=>array('label'=>$langs->trans("Label"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'enabled'=>$conf->societe->enabled), - 'commercial'=>array('label'=>$langs->trans("SaleRepresentativesOfThirdParty"), 'checked'=>1), + 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'p.title'=>array('label'=>$langs->trans("Label"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'enabled'=>$conf->societe->enabled), + 'commercial'=>array('label'=>$langs->trans("SaleRepresentativesOfThirdParty"), 'checked'=>0), 'p.dateo'=>array('label'=>$langs->trans("DateStart"), 'checked'=>1, 'position'=>100), - 'p.datee'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1, 'position'=>101), - 'p.public'=>array('label'=>$langs->trans("Visibility"), 'checked'=>1, 'position'=>102), - 'p.opp_amount'=>array('label'=>$langs->trans("OpportunityAmountShort"), 'checked'=>1, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>103), - 'p.fk_opp_status'=>array('label'=>$langs->trans("OpportunityStatusShort"), 'checked'=>1, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>104), - 'p.opp_percent'=>array('label'=>$langs->trans("OpportunityProbabilityShort"), 'checked'=>1, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>105), - 'p.budget_amount'=>array('label'=>$langs->trans("Budget"), 'checked'=>0, 'position'=>110), - 'p.datec'=>array('label'=>$langs->trans("DateCreationShort"), 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'p.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'p.datee'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1, 'position'=>101), + 'p.public'=>array('label'=>$langs->trans("Visibility"), 'checked'=>1, 'position'=>102), + 'p.opp_amount'=>array('label'=>$langs->trans("OpportunityAmountShort"), 'checked'=>1, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>103), + 'p.fk_opp_status'=>array('label'=>$langs->trans("OpportunityStatusShort"), 'checked'=>1, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>104), + 'p.opp_percent'=>array('label'=>$langs->trans("OpportunityProbabilityShort"), 'checked'=>1, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>105), + 'p.budget_amount'=>array('label'=>$langs->trans("Budget"), 'checked'=>0, 'position'=>110), + 'p.datec'=>array('label'=>$langs->trans("DateCreationShort"), 'checked'=>0, 'position'=>500), + 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'p.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -148,8 +148,8 @@ $object = new Project($db); * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -157,44 +157,44 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search_all=''; - $search_categ=''; - $search_ref=""; - $search_label=""; - $search_societe=""; - $search_year=""; - $search_status=-1; - $search_opp_status=-1; - $search_opp_amount=''; - $search_opp_percent=''; - $search_budget_amount=''; - $search_public=""; - $search_sale=""; - $search_project_user=''; - $search_sday=""; - $search_smonth=""; - $search_syear=""; - $search_eday=""; - $search_emonth=""; - $search_eyear=""; - $toselect=''; - $search_array_options=array(); - } + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_all=''; + $search_categ=''; + $search_ref=""; + $search_label=""; + $search_societe=""; + $search_year=""; + $search_status=-1; + $search_opp_status=-1; + $search_opp_amount=''; + $search_opp_percent=''; + $search_budget_amount=''; + $search_public=""; + $search_sale=""; + $search_project_user=''; + $search_sday=""; + $search_smonth=""; + $search_syear=""; + $search_eday=""; + $search_emonth=""; + $search_eyear=""; + $toselect=''; + $search_array_options=array(); + } - // Mass actions - $objectclass='Project'; - $objectlabel='Project'; - $permtoread = $user->rights->projet->lire; - $permtodelete = $user->rights->projet->supprimer; - $uploaddir = $conf->projet->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Mass actions + $objectclass='Project'; + $objectlabel='Project'; + $permtoread = $user->rights->projet->lire; + $permtodelete = $user->rights->projet->supprimer; + $uploaddir = $conf->projet->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -223,10 +223,10 @@ $sql.= " AND ctc.source = 'internal'"; $resql = $db->query($sql); if ($resql) { - while($obj = $db->fetch_object($resql)) - { - $listofprojectcontacttype[$obj->rowid]=$obj->code; - } + while($obj = $db->fetch_object($resql)) + { + $listofprojectcontacttype[$obj->rowid]=$obj->code; + } } else dol_print_error($db); if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0]='0'; // To avoid sql syntax error if not found @@ -272,42 +272,42 @@ if ($search_opp_amount) $sql .= natural_search('p.opp_amount', $search_opp_amoun if ($search_opp_percent) $sql .= natural_search('p.opp_percent', $search_opp_percent, 1); if ($search_smonth > 0) { - if ($search_syear > 0 && empty($search_sday)) - $sql.= " AND p.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,$search_smonth,false))."' AND '".$db->idate(dol_get_last_day($search_syear,$search_smonth,false))."'"; - else if ($search_syear > 0 && ! empty($search_sday)) - $sql.= " AND p.dateo BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_smonth, $search_sday, $search_syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_smonth, $search_sday, $search_syear))."'"; - else - $sql.= " AND date_format(p.dateo, '%m') = '".$search_smonth."'"; + if ($search_syear > 0 && empty($search_sday)) + $sql.= " AND p.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,$search_smonth,false))."' AND '".$db->idate(dol_get_last_day($search_syear,$search_smonth,false))."'"; + else if ($search_syear > 0 && ! empty($search_sday)) + $sql.= " AND p.dateo BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_smonth, $search_sday, $search_syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_smonth, $search_sday, $search_syear))."'"; + else + $sql.= " AND date_format(p.dateo, '%m') = '".$search_smonth."'"; } else if ($search_syear > 0) { - $sql.= " AND p.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,1,false))."' AND '".$db->idate(dol_get_last_day($search_syear,12,false))."'"; + $sql.= " AND p.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,1,false))."' AND '".$db->idate(dol_get_last_day($search_syear,12,false))."'"; } if ($search_emonth > 0) { - if ($search_eyear > 0 && empty($search_eday)) - $sql.= " AND p.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,$search_emonth,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,$search_emonth,false))."'"; - else if ($search_eyear > 0 && ! empty($search_eday)) - $sql.= " AND p.datee BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_emonth, $search_eday, $search_eyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_emonth, $search_eday, $search_eyear))."'"; - else - $sql.= " AND date_format(p.datee, '%m') = '".$search_emonth."'"; + if ($search_eyear > 0 && empty($search_eday)) + $sql.= " AND p.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,$search_emonth,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,$search_emonth,false))."'"; + else if ($search_eyear > 0 && ! empty($search_eday)) + $sql.= " AND p.datee BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_emonth, $search_eday, $search_eyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_emonth, $search_eday, $search_eyear))."'"; + else + $sql.= " AND date_format(p.datee, '%m') = '".$search_emonth."'"; } else if ($search_eyear > 0) { - $sql.= " AND p.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,12,false))."'"; + $sql.= " AND p.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,12,false))."'"; } if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); if ($search_status >= 0) { - if ($search_status == 99) $sql .= " AND p.fk_statut <> 2"; - else $sql .= " AND p.fk_statut = ".$db->escape($search_status); + if ($search_status == 99) $sql .= " AND p.fk_statut <> 2"; + else $sql .= " AND p.fk_statut = ".$db->escape($search_status); } if ($search_opp_status) { - if (is_numeric($search_opp_status) && $search_opp_status > 0) $sql .= " AND p.fk_opp_status = ".$db->escape($search_opp_status); - if ($search_opp_status == 'all') $sql .= " AND p.fk_opp_status IS NOT NULL"; - if ($search_opp_status == 'openedopp') $sql .= " AND p.fk_opp_status IS NOT NULL AND p.fk_opp_status NOT IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code IN ('WON','LOST'))"; - if ($search_opp_status == 'none') $sql .= " AND p.fk_opp_status IS NULL"; + if (is_numeric($search_opp_status) && $search_opp_status > 0) $sql .= " AND p.fk_opp_status = ".$db->escape($search_opp_status); + if ($search_opp_status == 'all') $sql .= " AND p.fk_opp_status IS NOT NULL"; + if ($search_opp_status == 'openedopp') $sql .= " AND p.fk_opp_status IS NOT NULL AND p.fk_opp_status NOT IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code IN ('WON','LOST'))"; + if ($search_opp_status == 'none') $sql .= " AND p.fk_opp_status IS NULL"; } if ($search_public!='') $sql .= " AND p.public = ".$db->escape($search_public); if ($search_sale > 0) $sql.= " AND sc.fk_user = " .$search_sale; @@ -319,16 +319,16 @@ if ($search_budget_amount != '') $sql .= natural_search('p.budget_amount', $sear // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -339,8 +339,8 @@ $sql.= $db->order($sortfield,$sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit + 1,$offset); @@ -351,8 +351,8 @@ dol_syslog("list allowed project", LOG_DEBUG); $resql = $db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -361,9 +361,9 @@ $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); - header("Location: ".DOL_URL_ROOT.'/projet/card.php?id='.$obj->id); - exit; + $obj = $db->fetch_object($resql); + header("Location: ".DOL_URL_ROOT.'/projet/card.php?id='.$obj->id); + exit; } $help_url="EN:Module_Projects|FR:Module_Projets|ES:Módulo_Proyectos"; @@ -395,9 +395,9 @@ if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available @@ -433,8 +433,8 @@ else if ($search_all) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); } $moreforfilter=''; @@ -442,11 +442,11 @@ $moreforfilter=''; // Filter on categories if (! empty($conf->categorie->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('ProjectCategories'). ': '; - $moreforfilter.=$formother->select_categories('project', $search_categ, 'search_categ', 1, 1, 'maxwidth300'); - $moreforfilter.='
    '; + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('ProjectCategories'). ': '; + $moreforfilter.=$formother->select_categories('project', $search_categ, 'search_categ', 1, 1, 'maxwidth300'); + $moreforfilter.='
    '; } // If the user can view user other than himself @@ -536,14 +536,14 @@ if (! empty($arrayfields['p.public']['checked'])) { print ''; $array=array(''=>'',0 => $langs->trans("PrivateProject"),1 => $langs->trans("SharedProject")); - print $form->selectarray('search_public',$array,$search_public); - print ''; + print $form->selectarray('search_public',$array,$search_public); + print ''; } if (! empty($arrayfields['p.fk_opp_status']['checked'])) { print ''; print $formproject->selectOpportunityStatus('search_opp_status', $search_opp_status, 1, 1, 1, 0, 'maxwidth100'); - print ''; + print ''; } if (! empty($arrayfields['p.opp_amount']['checked'])) { @@ -561,30 +561,30 @@ if (! empty($arrayfields['p.budget_amount']['checked'])) { print ''; print ''; - print ''; + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { - $crit=$val; + $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 ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -592,24 +592,25 @@ $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // N print $hookmanager->resPrint; if (! empty($arrayfields['p.datec']['checked'])) { - // Date creation - print ''; - print ''; + // Date creation + print ''; + print ''; } if (! empty($arrayfields['p.tms']['checked'])) { - // Date modification - print ''; - print ''; + // Date modification + print ''; + print ''; } if (! empty($arrayfields['p.fk_statut']['checked'])) { print ''; - $arrayofstatus = array(); - 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 ''; + $arrayofstatus = array(); + 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 selectarrowonleft'); + print ajax_combobox('search_status'); + print ''; } // Action column print ''; @@ -634,16 +635,16 @@ if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -668,6 +669,7 @@ while ($i < min($num,$limit)) $object->datee = $db->jdate($obj->date_end); $object->statut = $obj->fk_statut; $object->opp_status = $obj->fk_opp_status; + $object->title = $obj->title; $userAccess = $object->restrictedProjectArea($user); // why this ? if ($userAccess >= 0) @@ -675,168 +677,168 @@ while ($i < min($num,$limit)) print ''; // Project url - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - print $object->getNomUrl(1); - if ($object->hasDelay()) print img_warning($langs->trans('Late')); - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.ref']['checked'])) + { + print ''; + print $object->getNomUrl(1); + if ($object->hasDelay()) print img_warning($langs->trans('Late')); + print ''; + if (! $i) $totalarray['nbfield']++; + } // Title - if (! empty($arrayfields['p.title']['checked'])) - { - print ''; - print dol_trunc($obj->title,80); - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.title']['checked'])) + { + print ''; + print dol_trunc($obj->title,80); + print ''; + if (! $i) $totalarray['nbfield']++; + } // Company - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - if ($obj->socid) - { - $socstatic->id=$obj->socid; - $socstatic->name=$obj->name; - print $socstatic->getNomUrl(1); - } - else - { - print ' '; - } - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + if ($obj->socid) + { + $socstatic->id=$obj->socid; + $socstatic->name=$obj->name; + print $socstatic->getNomUrl(1); + } + else + { + print ' '; + } + print ''; + if (! $i) $totalarray['nbfield']++; + } // Sales Representatives - if (! empty($arrayfields['commercial']['checked'])) - { - print ''; - if ($obj->socid) - { - $socstatic->id=$obj->socid; - $socstatic->name=$obj->name; - $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); - $nbofsalesrepresentative=count($listsalesrepresentatives); - if ($nbofsalesrepresentative > 3) // We print only number - { - print ''; - print $nbofsalesrepresentative; - print ''; - } - else if ($nbofsalesrepresentative > 0) - { - $userstatic=new User($db); - $j=0; - foreach($listsalesrepresentatives as $val) - { - $userstatic->id=$val['id']; - $userstatic->lastname=$val['lastname']; - $userstatic->firstname=$val['firstname']; - $userstatic->email=$val['email']; - $userstatic->statut=$val['statut']; - $userstatic->entity=$val['entity']; - $userstatic->photo=$val['photo']; - //print $userstatic->getNomUrl(1, '', 0, 0, 12); - print $userstatic->getNomUrl(-2); - $j++; - if ($j < $nbofsalesrepresentative) print ' '; - } - } - //else print $langs->trans("NoSalesRepresentativeAffected"); - } - else - { - print ' '; - } - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['commercial']['checked'])) + { + print ''; + if ($obj->socid) + { + $socstatic->id=$obj->socid; + $socstatic->name=$obj->name; + $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); + $nbofsalesrepresentative=count($listsalesrepresentatives); + if ($nbofsalesrepresentative > 3) // We print only number + { + print ''; + print $nbofsalesrepresentative; + print ''; + } + else if ($nbofsalesrepresentative > 0) + { + $userstatic=new User($db); + $j=0; + foreach($listsalesrepresentatives as $val) + { + $userstatic->id=$val['id']; + $userstatic->lastname=$val['lastname']; + $userstatic->firstname=$val['firstname']; + $userstatic->email=$val['email']; + $userstatic->statut=$val['statut']; + $userstatic->entity=$val['entity']; + $userstatic->photo=$val['photo']; + //print $userstatic->getNomUrl(1, '', 0, 0, 12); + print $userstatic->getNomUrl(-2); + $j++; + if ($j < $nbofsalesrepresentative) print ' '; + } + } + //else print $langs->trans("NoSalesRepresentativeAffected"); + } + else + { + print ' '; + } + print ''; + if (! $i) $totalarray['nbfield']++; + } // Date start - if (! empty($arrayfields['p.dateo']['checked'])) - { + if (! empty($arrayfields['p.dateo']['checked'])) + { print ''; - print dol_print_date($db->jdate($obj->date_start),'day'); - print ''; - if (! $i) $totalarray['nbfield']++; - } + print dol_print_date($db->jdate($obj->date_start),'day'); + print ''; + if (! $i) $totalarray['nbfield']++; + } // Date end - if (! empty($arrayfields['p.datee']['checked'])) - { + if (! empty($arrayfields['p.datee']['checked'])) + { print ''; - print dol_print_date($db->jdate($obj->date_end),'day'); - print ''; - if (! $i) $totalarray['nbfield']++; - } + print dol_print_date($db->jdate($obj->date_end),'day'); + print ''; + if (! $i) $totalarray['nbfield']++; + } // Visibility - if (! empty($arrayfields['p.public']['checked'])) - { - print ''; - if ($obj->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Opp Status - if (! empty($arrayfields['p.fk_opp_status']['checked'])) - { - print ''; + if (! empty($arrayfields['p.public']['checked'])) + { + print ''; + if ($obj->public) print $langs->trans('SharedProject'); + else print $langs->trans('PrivateProject'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Opp Status + if (! empty($arrayfields['p.fk_opp_status']['checked'])) + { + print ''; if ($obj->opp_status_code) print $langs->trans("OppStatusShort".$obj->opp_status_code); print ''; - if (! $i) $totalarray['nbfield']++; - } - // Opp Amount - if (! empty($arrayfields['p.opp_amount']['checked'])) - { + if (! $i) $totalarray['nbfield']++; + } + // Opp Amount + if (! empty($arrayfields['p.opp_amount']['checked'])) + { print ''; //if ($obj->opp_status_code) if (strcmp($obj->opp_amount,'')) { - print price($obj->opp_amount, 1, $langs, 1, -1, -1, ''); - $totalarray['totalopp'] += $obj->opp_amount; + print price($obj->opp_amount, 1, $langs, 1, -1, -1, ''); + $totalarray['totalopp'] += $obj->opp_amount; } print ''; if (! $i) $totalarray['nbfield']++; if (! $i) $totalarray['totaloppfield']=$totalarray['nbfield']; - } - // Opp percent - if (! empty($arrayfields['p.opp_percent']['checked'])) - { + } + // Opp percent + if (! empty($arrayfields['p.opp_percent']['checked'])) + { print ''; if ($obj->opp_percent) print price($obj->opp_percent, 1, $langs, 1, 0).'%'; print ''; - if (! $i) $totalarray['nbfield']++; - } - // Budget - if (! empty($arrayfields['p.budget_amount']['checked'])) - { + if (! $i) $totalarray['nbfield']++; + } + // Budget + if (! empty($arrayfields['p.budget_amount']['checked'])) + { print ''; if ($obj->budget_amount != '') { - print price($obj->budget_amount, 1, $langs, 1, -1, -1); - $totalarray['totalbudget'] += $obj->budget_amount; + print price($obj->budget_amount, 1, $langs, 1, -1, -1); + $totalarray['totalbudget'] += $obj->budget_amount; } print ''; if (! $i) $totalarray['nbfield']++; if (! $i) $totalarray['totalbudgetfield']=$totalarray['nbfield']; - } + } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); @@ -845,34 +847,34 @@ while ($i < min($num,$limit)) // Date creation if (! empty($arrayfields['p.datec']['checked'])) { - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print ''; + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['p.tms']['checked'])) { - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print ''; + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; if (! $i) $totalarray['nbfield']++; } // Status if (! empty($arrayfields['p.fk_statut']['checked'])) { - print ''.$object->getLibStatut(5).''; + print ''.$object->getLibStatut(5).''; if (! $i) $totalarray['nbfield']++; } - // Action column - 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->id, $arrayofselected)) $selected=1; - print ''; - } - print ''; + // Action column + 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->id, $arrayofselected)) $selected=1; + print ''; + } + print ''; if (! $i) $totalarray['nbfield']++; print "\n"; @@ -885,21 +887,21 @@ while ($i < min($num,$limit)) // Show total line if (isset($totalarray['totaloppfield']) || isset($totalarray['totalbudgetfield'])) { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; - else print ''.$langs->trans("Totalforthispage").''; - } - elseif ($totalarray['totaloppfield'] == $i) print ''.price($totalarray['totalopp'], 1, $langs, 1, -1, -1).''; - elseif ($totalarray['totalbudgetfield'] == $i) print ''.price($totalarray['totalbudget'], 1, $langs, 1, -1, -1).''; - else print ''; - } - print ''; + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; + else print ''.$langs->trans("Totalforthispage").''; + } + elseif ($totalarray['totaloppfield'] == $i) print ''.price($totalarray['totalopp'], 1, $langs, 1, -1, -1).''; + elseif ($totalarray['totalbudgetfield'] == $i) print ''.price($totalarray['totalbudget'], 1, $langs, 1, -1, -1).''; + else print ''; + } + print ''; } $db->free($resql); diff --git a/htdocs/projet/tasks.php b/htdocs/projet/tasks.php index c00e93e239f..385b63142d4 100644 --- a/htdocs/projet/tasks.php +++ b/htdocs/projet/tasks.php @@ -39,7 +39,7 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $taskref = GETPOST('taskref', 'alpha'); $backtopage=GETPOST('backtopage','alpha'); -$cancel=GETPOST('cancel'); +$cancel=GETPOST('cancel','alpha'); $search_user_id = GETPOST('search_user_id', 'int'); @@ -366,7 +366,7 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third print ''; print ''.$langs->trans("Label").''; - print ''; + print ''; print ''; // List of projects @@ -393,7 +393,7 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third // Date end print ''.$langs->trans("DateEnd").''; - print $form->select_date(($date_end?$date_end:-1),'datee',1,1,0,'',1,1,1); + print $form->select_date(($date_end?$date_end:-1),'datee',-1,1,0,'',1,1,1); print ''; // Planned workload diff --git a/htdocs/projet/tasks/comment.php b/htdocs/projet/tasks/comment.php new file mode 100644 index 00000000000..e4250bad062 --- /dev/null +++ b/htdocs/projet/tasks/comment.php @@ -0,0 +1,275 @@ + + * Copyright (C) 2006-2017 Laurent Destailleur + * Copyright (C) 2010-2012 Regis Houssin + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/projet/tasks/task.php + * \ingroup project + * \brief Page of a project task + */ + +require ("../../main.inc.php"); +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php'; + +$langs->load("projects"); +$langs->load("companies"); + +$id=GETPOST('id','int'); +$idcomment=GETPOST('idcomment','int'); +$ref=GETPOST("ref",'alpha',1); // task ref +$objectref=GETPOST("taskref",'alpha'); // task ref +$action=GETPOST('action','alpha'); +$confirm=GETPOST('confirm','alpha'); +$withproject=GETPOST('withproject','int'); +$project_ref=GETPOST('project_ref','alpha'); +$planned_workload=((GETPOST('planned_workloadhour','int')!='' || GETPOST('planned_workloadmin','int')!='') ? (GETPOST('planned_workloadhour','int')>0?GETPOST('planned_workloadhour','int')*3600:0) + (GETPOST('planned_workloadmin','int')>0?GETPOST('planned_workloadmin','int')*60:0) : ''); + +// Security check +$socid=0; +//if ($user->societe_id > 0) $socid = $user->societe_id; // For external user, no check is done on company because readability is managed by public status of project and assignement. +if (! $user->rights->projet->lire) accessforbidden(); + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('projecttaskcard','globalcard')); + +$object = new Task($db); +$extrafields = new ExtraFields($db); +$projectstatic = new Project($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + +// include comment actions +include DOL_DOCUMENT_ROOT . '/core/actions_comments.inc.php'; + +// Retreive First Task ID of Project if withprojet is on to allow project prev next to work +if (! empty($project_ref) && ! empty($withproject)) +{ + if ($projectstatic->fetch('',$project_ref) > 0) + { + $objectsarray=$object->getTasksArray(0, 0, $projectstatic->id, $socid, 0); + if (count($objectsarray) > 0) + { + $id=$objectsarray[0]->id; + } + else + { + header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.(empty($mode)?'':'&mode='.$mode)); + } + } +} + +/* + * View +*/ + + +llxHeader('', $langs->trans("CommentPage")); + +$form = new Form($db); +$formother = new FormOther($db); +$formfile = new FormFile($db); + +if ($id > 0 || ! empty($ref)) +{ + if ($object->fetch($id,$ref) > 0) + { + $res=$object->fetch_optionals($object->id,$extralabels); + + $result=$projectstatic->fetch($object->fk_project); + if (! empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + + $object->project = clone $projectstatic; + + $userWrite = $projectstatic->restrictedProjectArea($user,'write'); + + if (! empty($withproject)) + { + // Tabs for project + $tab='tasks'; + $head=project_prepare_head($projectstatic); + dol_fiche_head($head, $tab, $langs->trans("Project"), -1, ($projectstatic->public?'projectpub':'project')); + + $param=($mode=='mine'?'&mode=mine':''); + + // Project card + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$projectstatic->title; + // Thirdparty + if ($projectstatic->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $projectstatic->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + + // Define a complementary filter for search of next/prev ref. + if (! $user->rights->projet->all->lire) + { + $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,0); + $projectstatic->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; + } + + dol_banner_tab($projectstatic, 'project_ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Visibility + print ''; + + // Date start - end + print ''; + + // Budget + print ''; + + // Other attributes + $cols = 2; + //include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '.$langs->trans("Visibility").''; + if ($projectstatic->public) print $langs->trans('SharedProject'); + else print $langs->trans('PrivateProject'); + print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + print dol_print_date($projectstatic->date_start,'day'); + $end=dol_print_date($projectstatic->date_end,'day'); + if ($end) print ' - '.$end; + print '
    '.$langs->trans("Budget").''; + if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount,'',$langs,1,0,0,$conf->currency); + print '
    '; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($projectstatic->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($projectstatic->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; + + dol_fiche_end(); + + print '
    '; + } + + $head=task_prepare_head($object); + + /* + * Fiche tache en mode visu + */ + $param=($withproject?'&withproject=1':''); + $linkback=$withproject?''.$langs->trans("BackToList").'':''; + + dol_fiche_head($head, 'task_comment', $langs->trans("Task"), -1, 'projecttask'); + + if ($action == 'delete') + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$_GET["id"].'&withproject='.$withproject,$langs->trans("DeleteATask"),$langs->trans("ConfirmDeleteATask"),"confirm_delete"); + } + + if (! GETPOST('withproject') || empty($projectstatic->id)) + { + $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1); + $object->next_prev_filter=" fk_projet in (".$projectsListId.")"; + } + else $object->next_prev_filter=" fk_projet = ".$projectstatic->id; + + $morehtmlref=''; + + // Project + if (empty($withproject)) + { + $morehtmlref.='
    '; + $morehtmlref.=$langs->trans("Project").': '; + $morehtmlref.=$projectstatic->getNomUrl(1); + $morehtmlref.='
    '; + + // Third party + $morehtmlref.=$langs->trans("ThirdParty").': '; + if (!empty($projectstatic->thirdparty)) { + $morehtmlref.=$projectstatic->thirdparty->getNomUrl(1); + } + $morehtmlref.='
    '; + } + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, $param); + + print '
    '; + + print '
    '; + print ''; + + // Nb comments + print ''; + + // Other attributes + $cols = 3; + $parameyers=array('socid'=>$socid); + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '.$langs->trans("NbComments").''; + print $object->getNbComments(); + print '
    '; + + print '
    '; + + dol_fiche_end(); + + + // Include comment tpl view + include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_comment.tpl.php'; + + } +} + + +llxFooter(); +$db->close(); diff --git a/htdocs/projet/tasks/contact.php b/htdocs/projet/tasks/contact.php index 6cdbc204749..d3baba4d5fb 100644 --- a/htdocs/projet/tasks/contact.php +++ b/htdocs/projet/tasks/contact.php @@ -339,7 +339,7 @@ if ($id > 0 || ! empty($ref)) print ''; print ''.$langs->trans("Source").''; print ''.$langs->trans("ThirdParty").''; - print ''.$langs->trans("ProjectContact").''; + print ''.$langs->trans("TaskContact").''; print ''.$langs->trans("ContactType").''; print ' '; print "\n"; @@ -421,7 +421,7 @@ if ($id > 0 || ! empty($ref)) print ''; print ''.$langs->trans("Source").''; print ''.$langs->trans("ThirdParty").''; - print ''.$langs->trans("ProjectContact").''; + print ''.$langs->trans("TaskContact").''; print ''.$langs->trans("ContactType").''; print ''.$langs->trans("Status").''; print ' '; diff --git a/htdocs/projet/tasks/list.php b/htdocs/projet/tasks/list.php index 3d239921c60..d44dc3ec4b8 100644 --- a/htdocs/projet/tasks/list.php +++ b/htdocs/projet/tasks/list.php @@ -45,8 +45,8 @@ $search_categ=GETPOST("search_categ",'alpha'); $search_project=GETPOST('search_project'); if (! isset($_GET['search_projectstatus']) && ! isset($_POST['search_projectstatus'])) { - if ($search_all != '') $search_projectstatus=-1; - else $search_projectstatus=1; + if ($search_all != '') $search_projectstatus=-1; + else $search_projectstatus=1; } else $search_projectstatus=GETPOST('search_projectstatus'); $search_project_ref=GETPOST('search_project_ref'); @@ -99,36 +99,36 @@ if (! $sortorder) $sortorder='DESC'; // List of fields to search into when doing a "search in all" $fieldstosearchall = array( 't.ref'=>"Ref", - 't.label'=>"Label", - 't.description'=>"Description", - 't.note_public'=>"NotePublic", + 't.label'=>"Label", + 't.description'=>"Description", + 't.note_public'=>"NotePublic", ); if (empty($user->socid)) $fieldstosearchall['t.note_private']="NotePrivate"; $arrayfields=array( - 't.ref'=>array('label'=>$langs->trans("RefTask"), 'checked'=>1, 'position'=>80), - 't.label'=>array('label'=>$langs->trans("LabelTask"), 'checked'=>1, 'position'=>80), - 't.dateo'=>array('label'=>$langs->trans("DateStart"), 'checked'=>1, 'position'=>100), - 't.datee'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1, 'position'=>101), - 'p.ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>1), - 'p.title'=>array('label'=>$langs->trans("ProjectLabel"), 'checked'=>0), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>0), - 'p.fk_statut'=>array('label'=>$langs->trans("ProjectStatus"), 'checked'=>1), - 't.planned_workload'=>array('label'=>$langs->trans("PlannedWorkload"), 'checked'=>1, 'position'=>102), - 't.duration_effective'=>array('label'=>$langs->trans("TimeSpent"), 'checked'=>1, 'position'=>103), - 't.progress_calculated'=>array('label'=>$langs->trans("ProgressCalculated"), 'checked'=>1, 'position'=>104), - 't.progress'=>array('label'=>$langs->trans("ProgressDeclared"), 'checked'=>1, 'position'=>105), - 't.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 't.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - //'t.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 't.ref'=>array('label'=>$langs->trans("RefTask"), 'checked'=>1, 'position'=>80), + 't.label'=>array('label'=>$langs->trans("LabelTask"), 'checked'=>1, 'position'=>80), + 't.dateo'=>array('label'=>$langs->trans("DateStart"), 'checked'=>1, 'position'=>100), + 't.datee'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1, 'position'=>101), + 'p.ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>1), + 'p.title'=>array('label'=>$langs->trans("ProjectLabel"), 'checked'=>0), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>0), + 'p.fk_statut'=>array('label'=>$langs->trans("ProjectStatus"), 'checked'=>1), + 't.planned_workload'=>array('label'=>$langs->trans("PlannedWorkload"), 'checked'=>1, 'position'=>102), + 't.duration_effective'=>array('label'=>$langs->trans("TimeSpent"), 'checked'=>1, 'position'=>103), + 't.progress_calculated'=>array('label'=>$langs->trans("ProgressCalculated"), 'checked'=>1, 'position'=>104), + 't.progress'=>array('label'=>$langs->trans("ProgressDeclared"), 'checked'=>1, 'position'=>105), + 't.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 't.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + //'t.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } } $object = new Task($db); @@ -138,8 +138,8 @@ $object = new Task($db); * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -147,40 +147,40 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search_all=""; - $search_categ=""; - $search_project=""; - $search_projectstatus=-1; - $search_project_ref=""; - $search_project_title=""; - $search_task_ref=""; - $search_task_label=""; - $search_task_description=""; - $search_task_user=-1; - $search_project_user=-1; - $search_sday=''; - $search_smonth=''; - $search_syear=''; - $search_eday=''; - $search_emonth=''; - $search_eyear=''; - $toselect=''; - $search_array_options=array(); - } + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_all=""; + $search_categ=""; + $search_project=""; + $search_projectstatus=-1; + $search_project_ref=""; + $search_project_title=""; + $search_task_ref=""; + $search_task_label=""; + $search_task_description=""; + $search_task_user=-1; + $search_project_user=-1; + $search_sday=''; + $search_smonth=''; + $search_syear=''; + $search_eday=''; + $search_emonth=''; + $search_eyear=''; + $toselect=''; + $search_array_options=array(); + } - // Mass actions - $objectclass='Task'; - $objectlabel='Tasks'; - $permtoread = $user->rights->projet->lire; - $permtodelete = $user->rights->projet->supprimer; - $uploaddir = $conf->projet->dir_output.'/tasks'; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Mass actions + $objectclass='Task'; + $objectlabel='Tasks'; + $permtoread = $user->rights->projet->lire; + $permtodelete = $user->rights->projet->supprimer; + $uploaddir = $conf->projet->dir_output.'/tasks'; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } if (empty($search_projectstatus) && $search_projectstatus == '') $search_projectstatus=1; @@ -223,10 +223,10 @@ $sql.= " AND ctc.source = 'internal'"; $resql = $db->query($sql); if ($resql) { - while($obj = $db->fetch_object($resql)) - { - $listofprojectcontacttype[$obj->rowid]=$obj->code; - } + while($obj = $db->fetch_object($resql)) + { + $listofprojectcontacttype[$obj->rowid]=$obj->code; + } } else dol_print_error($db); if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0]='0'; // To avoid sql syntax error if not found @@ -238,10 +238,10 @@ $sql.= " AND ctc.source = 'internal'"; $resql = $db->query($sql); if ($resql) { - while($obj = $db->fetch_object($resql)) - { - $listoftaskcontacttype[$obj->rowid]=$obj->code; - } + while($obj = $db->fetch_object($resql)) + { + $listoftaskcontacttype[$obj->rowid]=$obj->code; + } } else dol_print_error($db); if (count($listoftaskcontacttype) == 0) $listoftaskcontacttype[0]='0'; // To avoid sql syntax error if not found @@ -281,35 +281,35 @@ if ($search_task_label) $sql .= natural_search('t.label', $search_task_label) if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_smonth > 0) { - if ($search_syear > 0 && empty($search_sday)) - $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,$search_smonth,false))."' AND '".$db->idate(dol_get_last_day($search_syear,$search_smonth,false))."'"; - else if ($search_syear > 0 && ! empty($search_sday)) - $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_smonth, $search_sday, $search_syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_smonth, $search_sday, $search_syear))."'"; - else - $sql.= " AND date_format(t.dateo, '%m') = '".$search_smonth."'"; + if ($search_syear > 0 && empty($search_sday)) + $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,$search_smonth,false))."' AND '".$db->idate(dol_get_last_day($search_syear,$search_smonth,false))."'"; + else if ($search_syear > 0 && ! empty($search_sday)) + $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_smonth, $search_sday, $search_syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_smonth, $search_sday, $search_syear))."'"; + else + $sql.= " AND date_format(t.dateo, '%m') = '".$search_smonth."'"; } else if ($search_syear > 0) { - $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,1,false))."' AND '".$db->idate(dol_get_last_day($search_syear,12,false))."'"; + $sql.= " AND t.dateo BETWEEN '".$db->idate(dol_get_first_day($search_syear,1,false))."' AND '".$db->idate(dol_get_last_day($search_syear,12,false))."'"; } if ($search_emonth > 0) { - if ($search_eyear > 0 && empty($search_eday)) - $sql.= " AND t.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,$search_emonth,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,$search_emonth,false))."'"; - else if ($search_eyear > 0 && ! empty($search_eday)) - $sql.= " AND t.datee BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_emonth, $search_eday, $search_eyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_emonth, $search_eday, $search_eyear))."'"; - else - $sql.= " AND date_format(t.datee, '%m') = '".$search_emonth."'"; + if ($search_eyear > 0 && empty($search_eday)) + $sql.= " AND t.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,$search_emonth,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,$search_emonth,false))."'"; + else if ($search_eyear > 0 && ! empty($search_eday)) + $sql.= " AND t.datee BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_emonth, $search_eday, $search_eyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_emonth, $search_eday, $search_eyear))."'"; + else + $sql.= " AND date_format(t.datee, '%m') = '".$search_emonth."'"; } else if ($search_eyear > 0) { - $sql.= " AND t.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,12,false))."'"; + $sql.= " AND t.datee BETWEEN '".$db->idate(dol_get_first_day($search_eyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_eyear,12,false))."'"; } if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); if ($search_projectstatus >= 0) { - if ($search_projectstatus == 99) $sql .= " AND p.fk_statut <> 2"; - else $sql .= " AND p.fk_statut = ".$db->escape($search_projectstatus); + if ($search_projectstatus == 99) $sql .= " AND p.fk_statut <> 2"; + else $sql .= " AND p.fk_statut = ".$db->escape($search_projectstatus); } if ($search_public!='') $sql .= " AND p.public = ".$db->escape($search_public); if ($search_project_user > 0) $sql.= " AND ecp.fk_c_type_contact IN (".join(',',array_keys($listofprojectcontacttype)).") AND ecp.element_id = p.rowid AND ecp.fk_socpeople = ".$search_project_user; @@ -317,16 +317,16 @@ if ($search_task_user > 0) $sql.= " AND ect.fk_c_type_contact IN (".join(',',arr // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -337,8 +337,8 @@ $sql.= $db->order($sortfield,$sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit + 1,$offset); @@ -349,8 +349,8 @@ dol_syslog("list allowed project", LOG_DEBUG); $resql = $db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -359,10 +359,10 @@ $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->id; - header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->id; + header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); + exit; } $help_url="EN:Module_Projects|FR:Module_Projets|ES:Módulo_Proyectos"; @@ -393,9 +393,9 @@ if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available @@ -425,14 +425,14 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorde if ($search_task_user == $user->id) print $langs->trans("MyTasksDesc").'

    '; else { - if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("TasksOnProjectsDesc").'

    '; - else print $langs->trans("TasksOnProjectsPublicDesc").'

    '; + if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("TasksOnProjectsDesc").'

    '; + else print $langs->trans("TasksOnProjectsPublicDesc").'

    '; } if ($search_all) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); } $morehtmlfilter = ''; @@ -440,11 +440,11 @@ $morehtmlfilter = ''; // Filter on categories if (! empty($conf->categorie->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('ProjectCategories'). ': '; - $moreforfilter.=$formother->select_categories('project', $search_categ, 'search_categ', 1, 'maxwidth300'); - $moreforfilter.='
    '; + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('ProjectCategories'). ': '; + $moreforfilter.=$formother->select_categories('project', $search_categ, 'search_categ', 1, 'maxwidth300'); + $moreforfilter.='
    '; } // If the user can view users @@ -483,60 +483,60 @@ print ''; if (! empty($arrayfields['t.ref']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['t.label']['checked'])) { - print ''; + print ''; } // Start date if (! empty($arrayfields['t.dateo']['checked'])) { - print ''; + print ''; } // End date if (! empty($arrayfields['t.datee']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.ref']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.title']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['s.nom']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.fk_statut']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['t.planned_workload']['checked'])) print ''; if (! empty($arrayfields['t.duration_effective']['checked'])) print ''; @@ -545,25 +545,25 @@ if (! empty($arrayfields['t.progress']['checked'])) print ''; - } - } + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -571,15 +571,15 @@ $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // N print $hookmanager->resPrint; if (! empty($arrayfields['t.datec']['checked'])) { - // Date creation - print ''; + // Date creation + print ''; } if (! empty($arrayfields['t.tms']['checked'])) { - // Date modification - print ''; + // Date modification + print ''; } // Action column print ''; - // Ref - if (! empty($arrayfields['t.ref']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Label - if (! empty($arrayfields['t.label']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date start - if (! empty($arrayfields['t.dateo']['checked'])) - { + // Ref + if (! empty($arrayfields['t.ref']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Label + if (! empty($arrayfields['t.label']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date start + if (! empty($arrayfields['t.dateo']['checked'])) + { print ''; - if (! $i) $totalarray['nbfield']++; - } + print dol_print_date($db->jdate($obj->date_start),'day'); + print ''; + if (! $i) $totalarray['nbfield']++; + } // Date end - if (! empty($arrayfields['t.datee']['checked'])) - { + if (! empty($arrayfields['t.datee']['checked'])) + { print ''; - if (! $i) $totalarray['nbfield']++; - } - // Project ref - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Project title - if (! empty($arrayfields['p.title']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Project status - if (! empty($arrayfields['p.fk_statut']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + print dol_print_date($db->jdate($obj->date_end),'day'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Project ref + if (! empty($arrayfields['p.ref']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Project title + if (! empty($arrayfields['p.title']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Third party + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Project status + if (! empty($arrayfields['p.fk_statut']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Planned workload - if (! empty($arrayfields['t.planned_workload']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalplannedworkloadfield']=$totalarray['nbfield']; - $totalarray['totalplannedworkload'] += $obj->planned_workload; - } - // Time spent - if (! empty($arrayfields['t.duration_effective']['checked'])) - { - $showlineingray=0;$showproject=1; - print ''; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalplannedworkloadfield']=$totalarray['nbfield']; + $totalarray['totalplannedworkload'] += $obj->planned_workload; + } + // Time spent + if (! empty($arrayfields['t.duration_effective']['checked'])) + { + $showlineingray=0;$showproject=1; + print ''; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totaldurationeffectivefield']=$totalarray['nbfield']; - $totalarray['totaldurationeffective'] += $obj->duration_effective; - } - // Calculated progress - if (! empty($arrayfields['t.progress_calculated']['checked'])) - { + print ''; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totaldurationeffectivefield']=$totalarray['nbfield']; + $totalarray['totaldurationeffective'] += $obj->duration_effective; + } + // Calculated progress + if (! empty($arrayfields['t.progress_calculated']['checked'])) + { print ''; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalprogress_calculated']=$totalarray['nbfield']; - } - // Declared progress - if (! empty($arrayfields['t.progress']['checked'])) - { + print ''; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalprogress_calculated']=$totalarray['nbfield']; + } + // Declared progress + if (! empty($arrayfields['t.progress']['checked'])) + { print ''; - if (! $i) $totalarray['nbfield']++; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); @@ -815,18 +815,18 @@ while ($i < min($num,$limit)) // Date creation if (! empty($arrayfields['t.datec']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['t.tms']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Status /*if (! empty($arrayfields['p.fk_statut']['checked'])) @@ -834,16 +834,16 @@ while ($i < min($num,$limit)) $projectstatic->statut = $obj->fk_statut; print ''; }*/ - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; @@ -856,22 +856,22 @@ while ($i < min($num,$limit)) // Show total line if (isset($totalarray['totaldurationeffectivefield']) || isset($totalarray['totalplannedworkloadfield'])) { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''; - else print ''; - } - elseif ($totalarray['totalplannedworkloadfield'] == $i) print ''; - elseif ($totalarray['totaldurationeffectivefield'] == $i) print ''; - elseif ($totalarray['totalprogress_calculated'] == $i) print ''; - else print ''; - } - print ''; + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } + elseif ($totalarray['totalplannedworkloadfield'] == $i) print ''; + elseif ($totalarray['totaldurationeffectivefield'] == $i) print ''; + elseif ($totalarray['totalprogress_calculated'] == $i) print ''; + else print ''; + } + print ''; } $db->free($resql); diff --git a/htdocs/projet/tasks/time.php b/htdocs/projet/tasks/time.php index 9a513a4bce6..215a7ace2d0 100644 --- a/htdocs/projet/tasks/time.php +++ b/htdocs/projet/tasks/time.php @@ -622,7 +622,7 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -962,7 +962,7 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) } // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$task_time); $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; diff --git a/htdocs/public/demo/index.php b/htdocs/public/demo/index.php index 60559eb7aed..64e1b045279 100644 --- a/htdocs/public/demo/index.php +++ b/htdocs/public/demo/index.php @@ -22,7 +22,6 @@ * \file htdocs/public/demo/index.php * \ingroup core * \brief Entry page to access demo - * \author Laurent Destailleur */ define("NOLOGIN",1); // This means this output page does not require to be logged. @@ -71,29 +70,29 @@ if (empty($reshook)) { $demoprofiles=array( array('default'=>'1', 'key'=>'profdemoservonly','label'=>'DemoCompanyServiceOnly', - 'disablemodules'=>'adherent,barcode,cashdesk,don,expedition,externalsite,incoterm,mailmanspip,margin,prelevement,product,productbatch,stock', + 'disablemodules'=>'adherent,barcode,cashdesk,don,expedition,externalsite,ftp,incoterm,mailmanspip,margin,prelevement,product,productbatch,stock', //'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot8.png', 'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-service.jpg', 'url'=>$url ), array('default'=>'-1','key'=>'profdemoshopwithdesk','label'=>'DemoCompanyShopWithCashDesk', - 'disablemodules'=>'adherent,don,externalsite,ficheinter,incoterm,mailmanspip,prelevement,product,productbatch,stock', + 'disablemodules'=>'adherent,don,externalsite,ficheinter,ftp,incoterm,mailmanspip,prelevement,product,productbatch,stock', 'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot2.png', 'url'=>$url ), array('default'=>'0', 'key'=>'profdemoprodstock','label'=>'DemoCompanyProductAndStocks', - 'disablemodules'=>'adherent,contrat,don,externalsite,ficheinter,mailmanspip,prelevement,service', + 'disablemodules'=>'adherent,contrat,don,externalsite,ficheinter,ftp,mailmanspip,prelevement,service', //'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot2.png', 'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-product.jpg', 'url'=>$url ), array('default'=>'-1', 'key'=>'profdemofun','label'=>'DemoFundation', - 'disablemodules'=>'banque,barcode,cashdesk,commande,commercial,compta,comptabilite,contrat,expedition,externalsite,ficheinter,incoterm,mailmanspip,margin,prelevement,product,productbatch,projet,propal,propale,service,societe,stock,tax', + 'disablemodules'=>'banque,barcode,cashdesk,commande,commercial,compta,comptabilite,contrat,expedition,externalsite,ficheinter,ftp,incoterm,mailmanspip,margin,prelevement,product,productbatch,projet,propal,propale,service,societe,stock,tax', 'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot6.png', 'url'=>$url ), array('default'=>'0', 'key'=>'profdemofun2','label'=>'DemoFundation2', - 'disablemodules'=>'barcode,cashdesk,commande,commercial,compta,comptabilite,contrat,expedition,externalsite,ficheinter,incoterm,mailmanspip,margin,prelevement,product,productbatch,projet,propal,propale,service,societe,stock,tax', + 'disablemodules'=>'barcode,cashdesk,commande,commercial,compta,comptabilite,contrat,expedition,externalsite,ficheinter,ftp,incoterm,mailmanspip,margin,prelevement,product,productbatch,projet,propal,propale,service,societe,stock,tax', //'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot6.png', 'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-foundation.jpg', 'url'=>$url diff --git a/htdocs/public/members/new.php b/htdocs/public/members/new.php index b935eb12687..6a5fcbdfc62 100644 --- a/htdocs/public/members/new.php +++ b/htdocs/public/members/new.php @@ -299,11 +299,39 @@ if ($action == 'add') if (! empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) { - if ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paybox') + if ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'all') + { + $urlback=DOL_MAIN_URL_ROOT.'/public/payment/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref); + if (price2num(GETPOST('amount'))) $urlback.='&amount='.price2num(GETPOST('amount')); + if (GETPOST('email')) $urlback.='&email='.urlencode(GETPOST('email')); + if (! empty($conf->global->PAYMENT_SECURITY_TOKEN)) + { + if (! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) + { + $urlback.='&securekey='.urlencode(dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'membersubscription' . $adh->ref, 2)); + } + else + { + $urlback.='&securekey='.urlencode($conf->global->PAYMENT_SECURITY_TOKEN); + } + } + } + else if ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paybox') { $urlback=DOL_MAIN_URL_ROOT.'/public/paybox/newpayment.php?from=membernewform&source=membersubscription&ref='.urlencode($adh->ref); if (price2num(GETPOST('amount'))) $urlback.='&amount='.price2num(GETPOST('amount')); if (GETPOST('email')) $urlback.='&email='.urlencode(GETPOST('email')); + if (! empty($conf->global->PAYBOX_SECURITY_TOKEN)) + { + if (! empty($conf->global->PAYBOX_SECURITY_TOKEN_UNIQUE)) + { + $urlback.='&securekey='.urlencode(dol_hash($conf->global->PAYBOX_SECURITY_TOKEN . 'membersubscription' . $adh->ref, 2)); + } + else + { + $urlback.='&securekey='.urlencode($conf->global->PAYBOX_SECURITY_TOKEN); + } + } } else if ($conf->global->MEMBER_NEWFORM_PAYONLINE == 'paypal') { @@ -544,7 +572,7 @@ foreach($extrafields->attribute_label as $key=>$value) // Comments print ''; print ''; -print ''; +print ''; print ''."\n"; // Add specific fields used by Dolibarr foundation for example diff --git a/htdocs/public/onlinesign/newonlinesign.php b/htdocs/public/onlinesign/newonlinesign.php index 73d9f41eab0..6c9b4b154bf 100644 --- a/htdocs/public/onlinesign/newonlinesign.php +++ b/htdocs/public/onlinesign/newonlinesign.php @@ -62,14 +62,16 @@ $action=GETPOST('action','alpha'); // currency (iso code) $suffix=GETPOST("suffix",'alpha'); -$SOURCE=GETPOST("source",'alpha'); +$source=GETPOST("source",'alpha'); $ref=$REF=GETPOST("ref",'alpha'); +if (empty($source)) $source='proposal'; + if (! $action) { if ($source && ! $ref) { - dol_print_error('',$langs->trans('ErrorBadParameters')." - ref"); + print $langs->trans('ErrorBadParameters')." - ref missing"; exit; } } @@ -90,10 +92,10 @@ $urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than cur // Complete urls for post treatment $SECUREKEY=GETPOST("securekey"); // Secure key -if (! empty($SOURCE)) +if (! empty($source)) { - $urlok.='source='.urlencode($SOURCE).'&'; - $urlko.='source='.urlencode($SOURCE).'&'; + $urlok.='source='.urlencode($source).'&'; + $urlko.='source='.urlencode($source).'&'; } if (! empty($REF)) { @@ -113,7 +115,7 @@ if (! empty($entity)) $urlok=preg_replace('/&$/','',$urlok); // Remove last & $urlko=preg_replace('/&$/','',$urlko); // Remove last & - +$creditor = $mysoc->name; /* @@ -141,10 +143,10 @@ $conf->dol_hide_leftmenu=1; llxHeader($head, $langs->trans("OnlineSignature"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); // Check link validity -if (! empty($SOURCE) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) +if (! empty($source) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) { $langs->load("errors"); - dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $SOURCE, $ref)); + dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref)); llxFooter(); $db->close(); exit; @@ -164,7 +166,7 @@ print ''."\n"; print '
    '; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_syear?$search_syear:-1,'search_syear',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_syear?$search_syear:-1,'search_syear',1, 20, 5); + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_eyear?$search_eyear:-1,'search_eyear',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_eyear?$search_eyear:-1,'search_eyear',1, 20, 5); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - $arrayofstatus = array(); - foreach($projectstatic->statuts_short as $key => $val) $arrayofstatus[$key]=$langs->trans($val); - $arrayofstatus['99']=$langs->trans("NotClosed").' ('.$langs->trans('Draft').'+'.$langs->trans('Opened').')'; + print ''; + $arrayofstatus = array(); + foreach($projectstatic->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_projectstatus', $arrayofstatus, $search_projectstatus, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100'); - print 'getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { - $crit=$val; + $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 ''; - print ''; + print ''; @@ -604,16 +604,16 @@ if (! empty($arrayfields['t.progress']['checked'])) print_liste_field_titre // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -656,157 +656,157 @@ while ($i < min($num,$limit)) { print '
    '; - print $object->getNomUrl(1,'withproject'); - if ($object->hasDelay()) print img_warning("Late"); - print ''; - print $object->label; - print ''; + print $object->getNomUrl(1,'withproject'); + if ($object->hasDelay()) print img_warning("Late"); + print ''; + print $object->label; + print ''; - print dol_print_date($db->jdate($obj->date_start),'day'); - print ''; - print dol_print_date($db->jdate($obj->date_end),'day'); - print ''; - print $projectstatic->getNomUrl(1, 'task'); - if ($projectstatic->hasDelay()) print img_warning("Late"); - print ''; - print dol_trunc($obj->projecttitle,80); - print ''; - if ($obj->socid) - { - $socstatic->id=$obj->socid; - $socstatic->name=$obj->name; - print $socstatic->getNomUrl(1); - } - else - { - print ' '; - } - print ''; - print $projectstatic->getLibStatut(1); - print ''; + print $projectstatic->getNomUrl(1, 'task'); + if ($projectstatic->hasDelay()) print img_warning("Late"); + print ''; + print dol_trunc($obj->projecttitle,80); + print ''; + if ($obj->socid) + { + $socstatic->id=$obj->socid; + $socstatic->name=$obj->name; + print $socstatic->getNomUrl(1); + } + else + { + print ' '; + } + print ''; + print $projectstatic->getLibStatut(1); + print ''; - $fullhour=convertSecondToTime($obj->planned_workload,$plannedworkloadoutputformat); - $workingdelay=convertSecondToTime($obj->planned_workload,'all',86400,7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks - if ($obj->planned_workload != '') - { - print $fullhour; - // TODO Add delay taking account of working hours per day and working day per week - //if ($workingdelay != $fullhour) print '
    ('.$workingdelay.')'; - } - //else print '--:--'; - print '
    '; + // Planned workload + if (! empty($arrayfields['t.planned_workload']['checked'])) + { + print ''; + $fullhour=convertSecondToTime($obj->planned_workload,$plannedworkloadoutputformat); + $workingdelay=convertSecondToTime($obj->planned_workload,'all',86400,7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks + if ($obj->planned_workload != '') + { + print $fullhour; + // TODO Add delay taking account of working hours per day and working day per week + //if ($workingdelay != $fullhour) print '
    ('.$workingdelay.')'; + } + //else print '--:--'; + print '
    '; if ($showlineingray) print ''; else print ''; if ($obj->duration_effective) print convertSecondToTime($obj->duration_effective,$timespentoutputformat); else print '--:--'; if ($showlineingray) print ''; else print ''; - print ''; - if ($obj->planned_workload || $obj->duration_effective) + if ($obj->planned_workload || $obj->duration_effective) { if ($obj->planned_workload) print round(100 * $obj->duration_effective / $obj->planned_workload,2).' %'; else print $form->textwithpicto('',$langs->trans('WorkloadNotDefined'), 1, 'help'); } - print ''; - if ($obj->progress != '') + if ($obj->progress != '') { print $obj->progress.' %'; } - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$projectstatic->getLibStatut(5).''; - 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->id, $arrayofselected)) $selected=1; - 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->id, $arrayofselected)) $selected=1; + print ''; + } + print '
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.convertSecondToTime($totalarray['totalplannedworkload'],$plannedworkloadoutputformat).''.convertSecondToTime($totalarray['totaldurationeffective'],$timespentoutputformat).''.($totalarray['totalplannedworkload'] > 0 ? round(100 * $totalarray['totaldurationeffective'] / $totalarray['totalplannedworkload'], 2).' %' : '').'
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.convertSecondToTime($totalarray['totalplannedworkload'],$plannedworkloadoutputformat).''.convertSecondToTime($totalarray['totaldurationeffective'],$timespentoutputformat).''.($totalarray['totalplannedworkload'] > 0 ? round(100 * $totalarray['totaldurationeffective'] / $totalarray['totalplannedworkload'], 2).' %' : '').'
    '.$langs->trans("Comments").'
    '."\n"; -// Show logo (search order: logo defined by PAYBOX_LOGO_suffix, then PAYBOX_LOGO, then small company logo, large company logo, theme logo, common logo) +// Show logo (search order: logo defined by ONLINE_SIGN_LOGO_suffix, then ONLINE_SIGN_LOGO_, then small company logo, large company logo, theme logo, common logo) $width=0; // Define logo and logosmall $logosmall=$mysoc->logo_small; @@ -205,8 +207,8 @@ if (! empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT)) } if (empty($text)) { - $text.=''."\n"; - $text.=''."\n"; + $text.=''."\n"; + $text.=''."\n"; } print $text; @@ -219,45 +221,24 @@ $found=false; $error=0; $var=false; -// Free payment -if (! GETPOST("source")) -{ - $found=true; - $tag=GETPOST("tag"); - $fulltag=$tag; - - // Creditor - - print ''."\n"; - - - - // We do not add fields shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum - // as they don't exists (buyer is unknown, tag is free). -} - - // Payment on customer order -if (GETPOST("source") == 'order') +if ($source == 'proposal') { $found=true; - $langs->load("orders"); + $langs->load("proposal"); - require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $order=new Commande($db); - $result=$order->fetch('',$ref); - if ($result < 0) + $proposal=new Propal($db); + $result=$proposal->fetch('',$ref); + if ($result <= 0) { - $mesg=$order->error; + $mesg=$proposal->error; $error++; } else { - $result=$order->fetch_thirdparty($order->socid); + $result=$proposal->fetch_thirdparty($proposal->socid); } // Creditor @@ -270,336 +251,21 @@ if (GETPOST("source") == 'order') // Debitor print ''."\n"; } -// Payment on customer invoice -if (GETPOST("source") == 'invoice') -{ - $found=true; - $langs->load("bills"); - - require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - - $invoice=new Facture($db); - $result=$invoice->fetch('',$ref); - if ($result < 0) - { - $mesg=$invoice->error; - $error++; - } - else - { - $result=$invoice->fetch_thirdparty($invoice->socid); - } - - if ($action != 'dosign') // Do not change amount if we just click on first dosign - { - $amount=price2num($invoice->total_ttc - $invoice->getSommePaiement()); - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } - - // Creditor - - print ''."\n"; - - // Debitor - - print ''."\n"; - -} - -// Payment on contract line -if (GETPOST("source") == 'contractline') -{ - $found=true; - $langs->load("contracts"); - - require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; - - $contractline=new ContratLigne($db); - $result=$contractline->fetch('',$ref); - if ($result < 0) - { - $mesg=$contractline->error; - $error++; - } - else - { - if ($contractline->fk_contrat > 0) - { - $contract=new Contrat($db); - $result=$contract->fetch($contractline->fk_contrat); - if ($result > 0) - { - $result=$contract->fetch_thirdparty($contract->socid); - } - else - { - $mesg=$contract->error; - $error++; - } - } - else - { - $mesg='ErrorRecordNotFound'; - $error++; - } - } - - if ($action != 'dosign') // Do not change amount if we just click on first dosign - { - $amount=$contractline->total_ttc; - if ($contractline->fk_product) - { - $product=new Product($db); - $result=$product->fetch($contractline->fk_product); - - // We define price for product (TODO Put this in a method in product class) - if (! empty($conf->global->PRODUIT_MULTIPRICES)) - { - $pu_ht = $product->multiprices[$contract->thirdparty->price_level]; - $pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level]; - $price_base_type = $product->multiprices_base_type[$contract->thirdparty->price_level]; - } - else - { - $pu_ht = $product->price; - $pu_ttc = $product->price_ttc; - $price_base_type = $product->price_base_type; - } - - $amount=$pu_ttc; - if (empty($amount)) - { - dol_print_error('','ErrorNoPriceDefinedForThisProduct'); - exit; - } - } - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } - - $qty=1; - if (GETPOST('qty')) $qty=GETPOST('qty'); - - // Creditor - - print ''."\n"; - - // Debitor - - print ''."\n"; - - // Quantity - - $label=$langs->trans("Quantity"); - $qty=1; - $duration=''; - if ($contractline->fk_product) - { - if ($product->isService() && $product->duration_value > 0) - { - $label=$langs->trans("Duration"); - - // TODO Put this in a global method - if ($product->duration_value > 1) - { - $dur=array("h"=>$langs->trans("Hours"),"d"=>$langs->trans("DurationDays"),"w"=>$langs->trans("DurationWeeks"),"m"=>$langs->trans("DurationMonths"),"y"=>$langs->trans("DurationYears")); - } - else - { - $dur=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("DurationDay"),"w"=>$langs->trans("DurationWeek"),"m"=>$langs->trans("DurationMonth"),"y"=>$langs->trans("DurationYear")); - } - $duration=$product->duration_value.' '.$dur[$product->duration_unit]; - } - } - print ''; - print ''."\n"; - - // Amount - - print ''."\n"; - -} - -// Payment on member subscription -if (GETPOST("source") == 'membersubscription') -{ - $found=true; - $langs->load("members"); - - require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; - - $member=new Adherent($db); - $result=$member->fetch('',$ref); - if ($result < 0) - { - $mesg=$member->error; - $error++; - } - else - { - $subscription=new Subscription($db); - } - - if ($action != 'dosign') // Do not change amount if we just click on first dosign - { - $amount=$subscription->total_ttc; - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } - - $fulltag='MEM='.$member->id.'.DAT='.dol_print_date(dol_now(),'%Y%m%d%H%M'); - if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; } - $fulltag=dol_string_unaccent($fulltag); - - // Creditor - - print ''."\n"; - - // Debitor - - print ''."\n"; - - if ($member->last_subscription_date || $member->last_subscription_amount) - { - // Last subscription date - - print ''."\n"; - - // Last subscription amount - - print ''."\n"; - - if (empty($amount) && ! GETPOST('newamount')) $_GET['newamount']=$member->last_subscription_amount; - } - - // Amount - - print ''."\n"; - -} - - - if (! $found && ! $mesg) $mesg=$langs->trans("ErrorBadParameters"); @@ -617,7 +283,7 @@ if ($action != 'dosign') } else { - dol_print_error_email('ERRORNEWONLINESIGNPAYPAL'); + dol_print_error_email('ERRORNEWONLINESIGN'); } } else diff --git a/htdocs/public/paybox/newpayment.php b/htdocs/public/paybox/newpayment.php index 97a4c5452ff..0d8e930c95c 100644 --- a/htdocs/public/paybox/newpayment.php +++ b/htdocs/public/paybox/newpayment.php @@ -162,7 +162,7 @@ if (GETPOST('action','aZ09') == 'dopayment') */ $head=''; -if (! empty($conf->global->PAYBOX_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -171,9 +171,9 @@ llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'online // Common variables $creditor=$mysoc->name; -$paramcreditor='PAYBOX_CREDITOR_'.$suffix; +$paramcreditor='ONLINE_PAYMENT_CREDITOR_'.$suffix; if (! empty($conf->global->$paramcreditor)) $creditor=$conf->global->$paramcreditor; -else if (! empty($conf->global->PAYBOX_CREDITOR)) $creditor=$conf->global->PAYBOX_CREDITOR; +else if (! empty($conf->global->ONLINE_PAYMENT_CREDITOR)) $creditor=$conf->global->ONLINE_PAYMENT_CREDITOR; // Check link validity if (! empty($SOURCE) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) @@ -194,7 +194,7 @@ print ''; print ''; print "\n"; print ''."\n"; -print ''."\n"; +print ''."\n"; print ''."\n"; print ''."\n"; print ''."\n"; @@ -202,14 +202,14 @@ print "\n"; print '

    '.$langs->trans("WelcomeOnOnlineSignaturePage").'

    '.$langs->trans("ThisScreenAllowsYouToSignDocFrom",$creditor).'


    '.$langs->trans("WelcomeOnOnlineSignaturePage", $mysoc->name).'
    '.$langs->trans("ThisScreenAllowsYouToSignDocFrom",$creditor).'

    '.$langs->trans("Creditor"); - print ''.$creditor.''; - print ''; - print '
    '.$langs->trans("ThirdParty"); - print ''.$order->thirdparty->name.''; + print ''.$proposal->thirdparty->name.''; // Object - $text=''.$langs->trans("PaymentOrderRef",$order->ref).''; + $text=''.$langs->trans("SignatureProposalRef",$proposal->ref).''; print '
    '.$langs->trans("Designation"); print ''.$text; print ''; - print ''; + print ''; print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; - print ''; - print '
    '.$langs->trans("ThirdParty"); - print ''.$invoice->thirdparty->name.''; - - // Object - - $text=''.$langs->trans("PaymentInvoiceRef",$invoice->ref).''; - print '
    '.$langs->trans("Designation"); - print ''.$text; - print ''; - print ''; - print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; - print ''; - print '
    '.$langs->trans("ThirdParty"); - print ''.$contract->thirdparty->name.''; - - // Object - - $text=''.$langs->trans("PaymentRenewContractId",$contract->ref,$contractline->ref).''; - if ($contractline->fk_product) - { - $text.='
    '.$product->ref.($product->label?' - '.$product->label:''); - } - if ($contractline->description) $text.='
    '.dol_htmlentitiesbr($contractline->description); - //if ($contractline->date_fin_validite) { - // $text.='
    '.$langs->trans("DateEndPlanned").': '; - // $text.=dol_print_date($contractline->date_fin_validite); - //} - if ($contractline->date_fin_validite) - { - $text.='
    '.$langs->trans("ExpiredSince").': '.dol_print_date($contractline->date_fin_validite); - } - - print '
    '.$langs->trans("Designation"); - print ''.$text; - print ''; - print ''; - print '
    '.$label.''.($duration?$duration:$qty).''; - print ''; - print '
    '.$langs->trans("Amount"); - if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; - print ''; - if (empty($amount) || ! is_numeric($amount)) - { - print ''; - print ''; - } - else { - print ''.price($amount).''; - print ''; - print ''; - } - // Currency - print ' '.$langs->trans("Currency".$currency).''; - print ''; - print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; - print ''; - print '
    '.$langs->trans("Member"); - print ''; - if ($member->morphy == 'mor' && ! empty($member->societe)) print $member->societe; - else print $member->getFullName($langs); - print ''; - - // Object - - $text=''.$langs->trans("PaymentSubscription").''; - print '
    '.$langs->trans("Designation"); - print ''.$text; - print ''; - print ''; - print '
    '.$langs->trans("LastSubscriptionDate"); - print ''.dol_print_date($member->last_subscription_date,'day'); - print '
    '.$langs->trans("LastSubscriptionAmount"); - print ''.price($member->last_subscription_amount); - print '
    '.$langs->trans("Amount"); - if (empty($amount)) - { - print ' ('.$langs->trans("ToComplete"); - if (! empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - '.$langs->trans("SeeHere").''; - print ')'; - } - print ''; - if (empty($amount) || ! is_numeric($amount)) - { - $valtoshow=GETPOST("newamount",'int'); - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); - print ''; - print ''; - } - else { - $valtoshow=$amount; - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); - print ''.price($valtoshow).''; - print ''; - print ''; - } - // Currency - print ' '.$langs->trans("Currency".$currency).''; - print ''; - print '
    '."\n"; -// Show logo (search order: logo defined by PAYBOX_LOGO_suffix, then PAYBOX_LOGO, then small company logo, large company logo, theme logo, common logo) +// Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo) $width=0; // Define logo and logosmall $logosmall=$mysoc->logo_small; $logo=$mysoc->logo; -$paramlogo='PAYBOX_LOGO_'.$suffix; +$paramlogo='PAYMENT_LOGO_'.$suffix; if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo; -else if (! empty($conf->global->PAYBOX_LOGO)) $logosmall=$conf->global->PAYBOX_LOGO; +else if (! empty($conf->global->PAYMENT_LOGO)) $logosmall=$conf->global->PAYMENT_LOGO; //print ''."\n"; // Define urllogo $urllogo=''; @@ -234,17 +234,17 @@ if ($urllogo) // Output introduction text $text=''; -if (! empty($conf->global->PAYBOX_NEWFORM_TEXT)) +if (! empty($conf->global->PAYMENT_NEWFORM_TEXT)) { $langs->load("members"); - if (preg_match('/^\((.*)\)$/',$conf->global->PAYBOX_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."
    \n"; - else $text.=$conf->global->PAYBOX_NEWFORM_TEXT."
    \n"; + if (preg_match('/^\((.*)\)$/',$conf->global->PAYMENT_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."
    \n"; + else $text.=$conf->global->PAYMENT_NEWFORM_TEXT."
    \n"; $text=''."\n"; } if (empty($text)) { - $text.=''."\n"; - $text.=''."\n"; + $text.=''."\n"; + $text.=''."\n"; } print $text; @@ -802,7 +802,7 @@ print ''."\n"; print '
    '; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,1,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/paybox/paymentko.php b/htdocs/public/paybox/paymentko.php index f2b209a4add..feb4070c16b 100644 --- a/htdocs/public/paybox/paymentko.php +++ b/htdocs/public/paybox/paymentko.php @@ -82,26 +82,26 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice // Set by newpayment.php $paymentType = $_SESSION['PaymentType']; $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["Payment_Amount"]; + $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; // From env $ipaddress = $_SESSION['ipaddress']; - + // Appel des triggers include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; $interface=new Interfaces($db); $result=$interface->run_triggers('PAYBOX_PAYMENT_OK',$object,$user,$langs,$conf); if ($result < 0) { $error++; $errors=$interface->errors; } // Fin appel triggers - + // Send an email $sendemail = ''; - if (! empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->PAYBOX_PAYONLINE_SENDEMAIL; - + if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail=$conf->global->ONLINE_PAYMENT_SENDEMAIL; + if ($sendemail) { $sendto=$sendemail; $from=$conf->global->MAILING_EMAIL_FROM; - + // Define link to login card $appli=constant('DOL_APPLICATION_TITLE'); if (! empty($conf->global->MAIN_APPLICATION_TITLE)) @@ -114,7 +114,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice else $appli.=" ".DOL_VERSION; } else $appli.=" ".DOL_VERSION; - + $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentFailed"); $content=""; @@ -126,7 +126,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice $content.="tag=".$fulltag."\npaymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $mailfile = new CMailFile($topic, $sendto, $from, $content); - + $result=$mailfile->sendfile(); if ($result) { @@ -137,12 +137,12 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_paybox'); } } - + unset($_SESSION['ipaddress']); } $head=''; -if (! empty($conf->global->PAYBOX_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -156,12 +156,13 @@ print '
    '."\n"; print $langs->trans("YourPaymentHasNotBeenRecorded")."

    \n"; -if (! empty($conf->global->PAYBOX_MESSAGE_KO)) print $conf->global->PAYBOX_MESSAGE_KO; +$key='ONLINE_PAYMENT_MESSAGE_KO'; +if (! empty($conf->global->$key)) print $conf->global->$key; print "\n
    \n"; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,0,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/paybox/paymentok.php b/htdocs/public/paybox/paymentok.php index b1ed6411a1c..e3812c28dc1 100644 --- a/htdocs/public/paybox/paymentok.php +++ b/htdocs/public/paybox/paymentok.php @@ -84,7 +84,7 @@ dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_paybox'); $head=''; -if (! empty($conf->global->PAYBOX_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -105,7 +105,7 @@ $fulltag = $FULLTAG; // Set by newpayment.php $paymentType = $_SESSION['PaymentType']; $currencyCodeType = $_SESSION['currencyCodeType']; -$FinalPaymentAmt = $_SESSION["Payment_Amount"]; +$FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; // From env $ipaddress = $_SESSION['ipaddress']; @@ -115,7 +115,8 @@ dol_syslog("Call newpaymentok with token=".$onlinetoken." paymentType=".$payment print $langs->trans("YourPaymentHasBeenRecorded")."

    \n"; -if (! empty($conf->global->PAYBOX_MESSAGE_OK)) print $conf->global->PAYBOX_MESSAGE_OK; +$key='ONLINE_PAYMENT_MESSAGE_OK'; +if (! empty($conf->global->$key)) print $conf->global->$key; // Appel des triggers @@ -127,9 +128,9 @@ if ($result < 0) { $error++; $errors=$interface->errors; } // Send an email -if (! empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) +if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) { - $sendto=$conf->global->PAYBOX_PAYONLINE_SENDEMAIL; + $sendto=$conf->global->ONLINE_PAYMENT_SENDEMAIL; $from=$conf->global->MAILING_EMAIL_FROM; // Define $urlwithroot $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); @@ -148,7 +149,7 @@ if (! empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) else $appli.=" ".DOL_VERSION; } else $appli.=" ".DOL_VERSION; - + $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentReceived"); $tmptag=dolExplodeIntoArray($fulltag,'.','='); @@ -192,7 +193,7 @@ if (! empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) print "\n\n"; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,0,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index e1b215d4ebd..977c65d49a7 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -16,8 +16,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . * - * For paypal test: https://developer.paypal.com/ - * For paybox test: ??? + * For Paypal test: https://developer.paypal.com/ + * For Paybox test: ??? + * For Stripe test: Use credit card 4242424242424242 .More example on https://stripe.com/docs/testing */ /** @@ -52,7 +53,7 @@ $langs->load("companies"); $langs->load("errors"); $langs->load("paybox"); // File with generic data -$action=GETPOST('action','alpha'); +$action=GETPOST('action','aZ09'); // Input are: // type ('invoice','order','contractline'), @@ -61,28 +62,30 @@ $action=GETPOST('action','alpha'); // tag (a free text, required if type is empty) // currency (iso code) -$suffix=GETPOST("suffix",'alpha'); -$amount=price2num(GETPOST("amount")); +$suffix=GETPOST("suffix",'aZ09'); +$amount=price2num(GETPOST("amount",'alpha')); if (! GETPOST("currency",'alpha')) $currency=$conf->currency; else $currency=GETPOST("currency",'alpha'); +$source = GETPOST("s",'alpha')?GETPOST("s",'alpha'):GETPOST("source",'alpha'); +$download = GETPOST('d','int')?GETPOST('d','int'):GETPOST('download','int'); if (! $action) { - if (! GETPOST("amount") && ! GETPOST("source")) - { - dol_print_error('',$langs->trans('ErrorBadParameters')." - amount or source"); - exit; - } - if (is_numeric($amount) && ! GETPOST("tag") && ! GETPOST("source")) - { - dol_print_error('',$langs->trans('ErrorBadParameters')." - tag or source"); - exit; - } - if (GETPOST("source") && ! GETPOST("ref")) - { - dol_print_error('',$langs->trans('ErrorBadParameters')." - ref"); - exit; - } + if (! GETPOST("amount",'alpha') && ! $source) + { + print $langs->trans('ErrorBadParameters')." - amount or source"; + exit; + } + if (is_numeric($amount) && ! GETPOST("tag",'alpha') && ! $source) + { + print $langs->trans('ErrorBadParameters')." - tag or source"; + exit; + } + if ($source && ! GETPOST("ref",'alpha')) + { + print $langs->trans('ErrorBadParameters')." - ref"; + exit; + } } @@ -92,11 +95,11 @@ $validpaymentmethod=array(); // Detect $paymentmethod foreach($_POST as $key => $val) { - if (preg_match('/^dopayment_(.*)$/', $key, $reg)) - { - $paymentmethod=$reg[1]; - break; - } + if (preg_match('/^dopayment_(.*)$/', $key, $reg)) + { + $paymentmethod=$reg[1]; + break; + } } @@ -109,42 +112,46 @@ $urlok=$urlwithroot.'/public/payment/paymentok.php?'; $urlko=$urlwithroot.'/public/payment/paymentko.php?'; // Complete urls for post treatment -$SOURCE=GETPOST("source",'alpha'); $ref=$REF=GETPOST('ref','alpha'); $TAG=GETPOST("tag",'alpha'); $FULLTAG=GETPOST("fulltag",'alpha'); // fulltag is tag with more informations $SECUREKEY=GETPOST("securekey"); // Secure key if ($paymentmethod && ! preg_match('/'.preg_quote('PM='.$paymentmethod,'/').'/', $FULLTAG)) $FULLTAG.=($FULLTAG?'.':'').'PM='.$paymentmethod; -if (! empty($SOURCE)) +if (! empty($suffix)) { - $urlok.='source='.urlencode($SOURCE).'&'; - $urlko.='source='.urlencode($SOURCE).'&'; + $urlok.='suffix='.urlencode($suffix).'&'; + $urlko.='suffix='.urlencode($suffix).'&'; +} +if ($source) +{ + $urlok.='s='.urlencode($source).'&'; + $urlko.='s='.urlencode($source).'&'; } if (! empty($REF)) { - $urlok.='ref='.urlencode($REF).'&'; - $urlko.='ref='.urlencode($REF).'&'; + $urlok.='ref='.urlencode($REF).'&'; + $urlko.='ref='.urlencode($REF).'&'; } if (! empty($TAG)) { - $urlok.='tag='.urlencode($TAG).'&'; - $urlko.='tag='.urlencode($TAG).'&'; + $urlok.='tag='.urlencode($TAG).'&'; + $urlko.='tag='.urlencode($TAG).'&'; } if (! empty($FULLTAG)) { - $urlok.='fulltag='.urlencode($FULLTAG).'&'; - $urlko.='fulltag='.urlencode($FULLTAG).'&'; + $urlok.='fulltag='.urlencode($FULLTAG).'&'; + $urlko.='fulltag='.urlencode($FULLTAG).'&'; } if (! empty($SECUREKEY)) { - $urlok.='securekey='.urlencode($SECUREKEY).'&'; - $urlko.='securekey='.urlencode($SECUREKEY).'&'; + $urlok.='securekey='.urlencode($SECUREKEY).'&'; + $urlko.='securekey='.urlencode($SECUREKEY).'&'; } if (! empty($entity)) { - $urlok.='entity='.urlencode($entity).'&'; - $urlko.='entity='.urlencode($entity).'&'; + $urlok.='e='.urlencode($entity).'&'; + $urlko.='e='.urlencode($entity).'&'; } $urlok=preg_replace('/&$/','',$urlok); // Remove last & $urlko=preg_replace('/&$/','',$urlko); // Remove last & @@ -160,50 +167,28 @@ if (! empty($conf->paypal->enabled)) require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php'; require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php'; + // Check parameters $PAYPAL_API_OK=""; if ($urlok) $PAYPAL_API_OK=$urlok; $PAYPAL_API_KO=""; if ($urlko) $PAYPAL_API_KO=$urlko; if (empty($PAYPAL_API_USER)) { - dol_print_error('',"Paypal setup param PAYPAL_API_USER not defined"); - return -1; + dol_print_error('',"Paypal setup param PAYPAL_API_USER not defined"); + return -1; } if (empty($PAYPAL_API_PASSWORD)) { - dol_print_error('',"Paypal setup param PAYPAL_API_PASSWORD not defined"); - return -1; + dol_print_error('',"Paypal setup param PAYPAL_API_PASSWORD not defined"); + return -1; } if (empty($PAYPAL_API_SIGNATURE)) { - dol_print_error('',"Paypal setup param PAYPAL_API_SIGNATURE not defined"); - return -1; + dol_print_error('',"Paypal setup param PAYPAL_API_SIGNATURE not defined"); + return -1; } - // Check security token - $valid=true; - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN)) - { - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) - { - if ($SOURCE && $REF) $token = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . $SOURCE . $REF, 2); // Use the source in the hash to avoid duplicates if the references are identical - else $token = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - } - else - { - $token = $conf->global->PAYPAL_SECURITY_TOKEN; - } - if ($SECUREKEY != $token) $valid=false; - - if (! $valid) - { - print '
    Bad value for key.
    '; - //print 'SECUREKEY='.$SECUREKEY.' token='.$token.' valid='.$valid; - exit; - } - } - - $validpaymentmethod['paypal']='valid'; + $validpaymentmethod['paypal']='valid'; } if (! empty($conf->paybox->enabled)) @@ -212,39 +197,62 @@ if (! empty($conf->paybox->enabled)) // TODO - $validpaymentmethod['paybox']='valid'; + $validpaymentmethod['paybox']='valid'; +} + +if (! empty($conf->stripe->enabled)) +{ + $langs->load("stripe"); + + require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; + /* already included into /stripe/config.php + require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/stripe/lib/stripe.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/stripe/init.php'; + */ + + $validpaymentmethod['stripe']='valid'; } -// TODO Add check of other payment mode // Check security token $valid=true; if (! empty($conf->global->PAYMENT_SECURITY_TOKEN)) { - if (! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { - if ($SOURCE && $REF) $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . $SOURCE . $REF, 2); // Use the source in the hash to avoid duplicates if the references are identical - else $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - } - else - { - $token = $conf->global->PAYMENT_SECURITY_TOKEN; - } - if ($SECUREKEY != $token) $valid=false; + if (! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) + { + if ($source && $REF) $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . $source . $REF, 2); // Use the source in the hash to avoid duplicates if the references are identical + else $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + } + else + { + $token = $conf->global->PAYMENT_SECURITY_TOKEN; + } + if ($SECUREKEY != $token) $valid=false; - if (! $valid) - { - print '
    Bad value for key.
    '; - //print 'SECUREKEY='.$SECUREKEY.' token='.$token.' valid='.$valid; - exit; - } + if (! $valid) + { + print '
    Bad value for key.
    '; + //print 'SECUREKEY='.$SECUREKEY.' token='.$token.' valid='.$valid; + exit; + } } +if (empty($validpaymentmethod)) +{ + print 'No active payment module (Paypal, Stripe, Paybox, ...)'; + exit; +} - -if (empty($validpaymentmethod)) accessforbidden('', 0, 0, 1); +// Common variables +$creditor=$mysoc->name; +$paramcreditor='ONLINE_PAYMENT_CREDITOR'; +$paramcreditorlong='ONLINE_PAYMENT_CREDITOR_'.$suffix; +if (! empty($conf->global->$paramcreditorlong)) $creditor=$conf->global->$paramcreditorlong; +else if (! empty($conf->global->$paramcreditor)) $creditor=$conf->global->$paramcreditor; @@ -252,25 +260,24 @@ if (empty($validpaymentmethod)) accessforbidden('', 0, 0, 1); * Actions */ - if ($action == 'dopayment') { if ($paymentmethod == 'paypal') { $PAYPAL_API_PRICE=price2num(GETPOST("newamount"),'MT'); - $PAYPAL_PAYMENT_TYPE='Sale'; + $PAYPAL_PAYMENT_TYPE='Sale'; - $origfulltag=GETPOST("fulltag",'alpha'); - $shipToName=GETPOST("shipToName"); - $shipToStreet=GETPOST("shipToStreet"); - $shipToCity=GETPOST("shipToCity"); - $shipToState=GETPOST("shipToState"); - $shipToCountryCode=GETPOST("shipToCountryCode"); - $shipToZip=GETPOST("shipToZip"); - $shipToStreet2=GETPOST("shipToStreet2"); - $phoneNum=GETPOST("phoneNum"); - $email=GETPOST("email"); - $desc=GETPOST("desc"); + $origfulltag=GETPOST("fulltag",'alpha'); + $shipToName=GETPOST("shipToName"); + $shipToStreet=GETPOST("shipToStreet"); + $shipToCity=GETPOST("shipToCity"); + $shipToState=GETPOST("shipToState"); + $shipToCountryCode=GETPOST("shipToCountryCode"); + $shipToZip=GETPOST("shipToZip"); + $shipToStreet2=GETPOST("shipToStreet2"); + $phoneNum=GETPOST("phoneNum"); + $email=GETPOST("email"); + $desc=GETPOST("desc",'alpha'); $mesg=''; if (empty($PAYPAL_API_PRICE) || ! is_numeric($PAYPAL_API_PRICE)) $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Amount")); @@ -278,7 +285,7 @@ if ($action == 'dopayment') //elseif (! isValidEMail($EMAIL)) $mesg=$langs->trans("ErrorBadEMail",$EMAIL); elseif (! $origfulltag) $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("PaymentCode")); - //var_dump($_POST); + //var_dump($_POST); if (empty($mesg)) { dol_syslog("newpayment.php call paypal api and do redirect", LOG_DEBUG); @@ -287,39 +294,206 @@ if ($action == 'dopayment') $PAYPAL_API_DEVISE="USD"; //if ($currency == 'EUR') $PAYPAL_API_DEVISE="EUR"; //if ($currency == 'USD') $PAYPAL_API_DEVISE="USD"; - if (! empty($currency)) $PAYPAL_API_DEVISE=$currency; + if (! empty($currency)) $PAYPAL_API_DEVISE=$currency; - dol_syslog("Submit Paypal form", LOG_DEBUG); - dol_syslog("PAYPAL_API_USER: $PAYPAL_API_USER", LOG_DEBUG); - //dol_syslog("PAYPAL_API_PASSWORD: $PAYPAL_API_PASSWORD", LOG_DEBUG); // No password into log files - dol_syslog("PAYPAL_API_SIGNATURE: $PAYPAL_API_SIGNATURE", LOG_DEBUG); - dol_syslog("PAYPAL_API_SANDBOX: $PAYPAL_API_SANDBOX", LOG_DEBUG); - dol_syslog("PAYPAL_API_OK: $PAYPAL_API_OK", LOG_DEBUG); - dol_syslog("PAYPAL_API_KO: $PAYPAL_API_KO", LOG_DEBUG); - dol_syslog("PAYPAL_API_PRICE: $PAYPAL_API_PRICE", LOG_DEBUG); - dol_syslog("PAYPAL_API_DEVISE: $PAYPAL_API_DEVISE", LOG_DEBUG); - dol_syslog("shipToName: $shipToName", LOG_DEBUG); - dol_syslog("shipToStreet: $shipToStreet", LOG_DEBUG); - dol_syslog("shipToCity: $shipToCity", LOG_DEBUG); - dol_syslog("shipToState: $shipToState", LOG_DEBUG); - dol_syslog("shipToCountryCode: $shipToCountryCode", LOG_DEBUG); - dol_syslog("shipToZip: $shipToZip", LOG_DEBUG); - dol_syslog("shipToStreet2: $shipToStreet2", LOG_DEBUG); - dol_syslog("phoneNum: $phoneNum", LOG_DEBUG); - dol_syslog("email: $email", LOG_DEBUG); - dol_syslog("desc: $desc", LOG_DEBUG); + // Show var initialized by include fo paypal lib at begin of this file + dol_syslog("Submit Paypal form", LOG_DEBUG); + dol_syslog("PAYPAL_API_USER: $PAYPAL_API_USER", LOG_DEBUG); + dol_syslog("PAYPAL_API_PASSWORD: ".preg_replace('/./', '*', $PAYPAL_API_PASSWORD), LOG_DEBUG); // No password into log files + dol_syslog("PAYPAL_API_SIGNATURE: $PAYPAL_API_SIGNATURE", LOG_DEBUG); + dol_syslog("PAYPAL_API_SANDBOX: $PAYPAL_API_SANDBOX", LOG_DEBUG); + dol_syslog("PAYPAL_API_OK: $PAYPAL_API_OK", LOG_DEBUG); + dol_syslog("PAYPAL_API_KO: $PAYPAL_API_KO", LOG_DEBUG); + dol_syslog("PAYPAL_API_PRICE: $PAYPAL_API_PRICE", LOG_DEBUG); + dol_syslog("PAYPAL_API_DEVISE: $PAYPAL_API_DEVISE", LOG_DEBUG); + dol_syslog("shipToName: $shipToName", LOG_DEBUG); + dol_syslog("shipToStreet: $shipToStreet", LOG_DEBUG); + dol_syslog("shipToCity: $shipToCity", LOG_DEBUG); + dol_syslog("shipToState: $shipToState", LOG_DEBUG); + dol_syslog("shipToCountryCode: $shipToCountryCode", LOG_DEBUG); + dol_syslog("shipToZip: $shipToZip", LOG_DEBUG); + dol_syslog("shipToStreet2: $shipToStreet2", LOG_DEBUG); + dol_syslog("phoneNum: $phoneNum", LOG_DEBUG); + dol_syslog("email: $email", LOG_DEBUG); + dol_syslog("desc: $desc", LOG_DEBUG); - dol_syslog("SCRIPT_URI: ".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG); // If defined script uri must match domain of PAYPAL_API_OK and PAYPAL_API_KO - //$_SESSION["PaymentType"]=$PAYPAL_PAYMENT_TYPE; - //$_SESSION["currencyCodeType"]=$PAYPAL_API_DEVISE; - //$_SESSION["Payment_Amount"]=$PAYPAL_API_PRICE; + dol_syslog("SCRIPT_URI: ".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG); // If defined script uri must match domain of PAYPAL_API_OK and PAYPAL_API_KO + //$_SESSION["PaymentType"]=$PAYPAL_PAYMENT_TYPE; + //$_SESSION["currencyCodeType"]=$PAYPAL_API_DEVISE; + //$_SESSION["FinalPaymentAmt"]=$PAYPAL_API_PRICE; - // A redirect is added if API call successfull - print_paypal_redirect($PAYPAL_API_PRICE,$PAYPAL_API_DEVISE,$PAYPAL_PAYMENT_TYPE,$PAYPAL_API_OK,$PAYPAL_API_KO, $FULLTAG); + // A redirect is added if API call successfull + print_paypal_redirect($PAYPAL_API_PRICE,$PAYPAL_API_DEVISE,$PAYPAL_PAYMENT_TYPE,$PAYPAL_API_OK,$PAYPAL_API_KO, $FULLTAG); exit; } } + + if ($paymentmethod == 'paybox') + { + $PRICE=price2num(GETPOST("newamount"),'MT'); + $email=GETPOST("email"); + + $origfulltag=GETPOST("fulltag",'alpha'); + + // Securekey into back url useless for back url and we need an url lower than 150. + $urlok = preg_replace('/securekey=[^&]+/', '', $urlok); + $urlko = preg_replace('/securekey=[^&]+/', '', $urlko); + + $mesg=''; + if (empty($PRICE) || ! is_numeric($PRICE)) $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Amount")); + elseif (empty($email)) $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("YourEMail")); + elseif (! isValidEMail($email)) $mesg=$langs->trans("ErrorBadEMail",$email); + elseif (! $origfulltag) $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("PaymentCode")); + elseif (dol_strlen($urlok) > 150) $mesg='Error urlok too long '.$urlok.'( Paybox requires 150, found '.strlen($urlok).')'; + elseif (dol_strlen($urlko) > 150) $mesg='Error urlko too long '.$urlko.'( Paybox requires 150, found '.strlen($urlok).')'; + + if (empty($mesg)) + { + dol_syslog("newpayment.php call paybox api and do redirect", LOG_DEBUG); + + include_once DOL_DOCUMENT_ROOT.'/paybox/lib/paybox.lib.php'; + print_paybox_redirect($PRICE, $conf->currency, $email, $urlok, $urlko, $FULLTAG); + + session_destroy(); + exit; + } + } + + if ($paymentmethod == 'stripe') + { + if (GETPOST('newamount')) $amount = GETPOST('newamount'); + else + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); + $action = ''; + } + } +} + + +// Called when choosing Stripe mode, after the 'dopayment' +if ($action == 'charge') +{ + // Correct the amount according to unit of currency + // See https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support + $arrayzerounitcurrency=array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); + if (! in_array($currency, $arrayzerounitcurrency)) $amount=$amount * 100; + + dol_syslog("POST keys : ".join(',', array_keys($_POST)), LOG_DEBUG, 0, '_stripe'); + dol_syslog("POST values: ".join(',', $_POST), LOG_DEBUG, 0, '_stripe'); + + $stripeToken = GETPOST("stripeToken",'alpha'); + $email = GETPOST("stripeEmail",'alpha'); + $vatnumber = GETPOST('vatnumber','alpha'); + + dol_syslog("stripeToken = ".$stripeToken, LOG_DEBUG, 0, '_stripe'); + dol_syslog("email = ".$email, LOG_DEBUG, 0, '_stripe'); + dol_syslog("vatnumber = ".$vatnumber, LOG_DEBUG, 0, '_stripe'); + + $error = 0; + + try { + dol_syslog("Create customer card profile", LOG_DEBUG, 0, '_stripe'); + $customer = \Stripe\Customer::create(array( + 'email' => $email, + 'description' => ($email?'Customer card profile for '.$email:null), + 'metadata' => array('ipaddress'=>$_SERVER['REMOTE_ADDR']), + 'business_vat_id' => ($vatnumber?$vatnumber:null), + 'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?) + )); + // Return $customer = array('id'=>'cus_XXXX', ...) + + dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe'); + $charge = \Stripe\Charge::create(array( + 'customer' => $customer->id, + 'amount' => price2num($amount, 'MU'), + 'currency' => $currency, + 'description' => 'Stripe payment: '.$FULLTAG, + 'metadata' => array("FULLTAG" => $FULLTAG, 'Recipient' => $mysoc->name), + 'statement_descriptor' => dol_trunc(dol_trunc(dol_string_unaccent($mysoc->name), 6, 'right', 'UTF-8', 1).' '.$FULLTAG, 22, 'right', 'UTF-8', 1) // 22 chars that appears on bank receipt + )); + // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) + } catch(\Stripe\Error\Card $e) { + // Since it's a decline, \Stripe\Error\Card will be caught + $body = $e->getJsonBody(); + $err = $body['error']; + + print('Status is:' . $e->getHttpStatus() . "\n"); + print('Type is:' . $err['type'] . "\n"); + print('Code is:' . $err['code'] . "\n"); + // param is '' in this case + print('Param is:' . $err['param'] . "\n"); + print('Message is:' . $err['message'] . "\n"); + + $error++; + setEventMessages($e->getMessage(), null, 'errors'); + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + $action=''; + } catch (\Stripe\Error\RateLimit $e) { + // Too many requests made to the API too quickly + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (\Stripe\Error\InvalidRequest $e) { + // Invalid parameters were supplied to Stripe's API + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (\Stripe\Error\Authentication $e) { + // Authentication with Stripe's API failed + // (maybe you changed API keys recently) + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (\Stripe\Error\ApiConnection $e) { + // Network communication with Stripe failed + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (\Stripe\Error\Base $e) { + // Display a very generic error to the user, and maybe send + // yourself an email + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } catch (Exception $e) { + // Something else happened, completely unrelated to Stripe + $error++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + setEventMessages($e->getMessage(), null, 'errors'); + $action=''; + } + + $_SESSION["onlinetoken"] = $stripeToken; + $_SESSION["FinalPaymentAmt"] = $amount; + $_SESSION["currencyCodeType"] = $currency; + $_SESSION["paymentType"] = ''; + $_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR']; // Payer ip + $_SESSION['payerID'] = is_object($customer)?$customer->id:''; + $_SESSION['TRANSACTIONID'] = is_object($charge)?$charge->id:''; + + dol_syslog("Action charge stripe result=".$error." ip=".$_SESSION['ipaddress'], LOG_DEBUG, 0, '_stripe'); + dol_syslog("onlinetoken=".$_SESSION["onlinetoken"]." FinalPaymentAmt=".$_SESSION["FinalPaymentAmt"]." currencyCodeType=".$_SESSION["currencyCodeType"]." payerID=".$_SESSION['payerID']." TRANSACTIONID=".$_SESSION['TRANSACTIONID'], LOG_DEBUG, 0, '_stripe'); + dol_syslog("FULLTAG=".$FULLTAG, LOG_DEBUG, 0, '_stripe'); + dol_syslog("Now call the redirect to paymentok or paymentko", LOG_DEBUG, 0, '_stripe'); + + if ($error) + { + header("Location: ".$urlko); + exit; + } + else + { + header("Location: ".$urlok); + exit; + } + } @@ -328,7 +502,7 @@ if ($action == 'dopayment') */ $head=''; -if (! empty($conf->global->PAYMENT_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -336,28 +510,26 @@ $conf->dol_hide_leftmenu=1; llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); // Check link validity -if (! empty($SOURCE) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) +if ($source && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) { - $langs->load("errors"); - dol_print_error_email('BADREFINPAYMENTFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $SOURCE, $ref)); - llxFooter(); - $db->close(); - exit; + $langs->load("errors"); + dol_print_error_email('BADREFINPAYMENTFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref)); + llxFooter(); + $db->close(); + exit; } -if (! empty($conf->paypal->enabled)) -{ - // Common variables - $creditor=$mysoc->name; - $paramcreditor='PAYPAL_CREDITOR_'.$suffix; - if (! empty($conf->global->$paramcreditor)) $creditor=$conf->global->$paramcreditor; - else if (! empty($conf->global->PAYPAL_CREDITOR)) $creditor=$conf->global->PAYPAL_CREDITOR; - if (! empty($PAYPAL_API_SANDBOX)) - { - dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode'),'','warning'); - } +// Show sandbox warning +if (! empty($conf->paypal->enabled) && (! empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox','alpha'))) // We can force sand box with param 'forcesandbox' +{ + dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Paypal'),'','warning'); } +if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha'))) +{ + dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); +} + print ''."\n"; print '
    '."\n"; @@ -367,46 +539,51 @@ print ''."\n"; print ''."\n"; print ''."\n"; print ''."\n"; -print ''; +print ''; +print ''; print "\n"; print ''."\n"; +print ''."\n"; // Additionnal information for each payment system if (! empty($conf->paypal->enabled)) { print ''."\n"; print ''."\n"; - print ''."\n"; } if (! empty($conf->paybox->enabled)) { } -// TODO Add others +if (! empty($conf->stripe->enabled)) +{ + print ''."\n"; +} print ''."\n"; print ''."\n"; print "\n"; print '

    '.$text.'

    '.$langs->trans("WelcomeOnPaymentPage").'

    '.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'


    '.$langs->trans("WelcomeOnPaymentPage").'
    '.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'

    '."\n"; -// Show logo (search order: logo defined by PAYBOX_LOGO_suffix, then PAYBOX_LOGO, then small company logo, large company logo, theme logo, common logo) +// Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo) $width=0; // Define logo and logosmall $logosmall=$mysoc->logo_small; $logo=$mysoc->logo; -$paramlogo='PAYMENT_LOGO_'.$suffix; +$paramlogo='ONLINE_PAYMENT_LOGO_'.$suffix; if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo; -else if (! empty($conf->global->PAYMENT_LOGO)) $logosmall=$conf->global->PAYBOX_LOGO; +else if (! empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall=$conf->global->ONLINE_PAYMENT_LOGO; //print ''."\n"; // Define urllogo $urllogo=''; if (! empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode('thumbs/'.$logosmall); + $width=150; } elseif (! empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode($logo); - $width=96; + $width=150; } // Output html code for logo if ($urllogo) @@ -420,56 +597,57 @@ if ($urllogo) // Output introduction text $text=''; -if (! empty($conf->global->PAYPAL_NEWFORM_TEXT)) +if (! empty($conf->global->PAYMENT_NEWFORM_TEXT)) { - $langs->load("members"); - if (preg_match('/^\((.*)\)$/',$conf->global->PAYPAL_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."
    \n"; - else $text.=$conf->global->PAYPAL_NEWFORM_TEXT."
    \n"; - $text=''."\n"; + $langs->load("members"); + if (preg_match('/^\((.*)\)$/',$conf->global->PAYMENT_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."
    \n"; + else $text.=$conf->global->PAYMENT_NEWFORM_TEXT."
    \n"; + $text=''."\n"; } if (empty($text)) { - $text.=''."\n"; - $text.=''."\n"; + $text.=''."\n"; + $text.=''."\n"; } print $text; // Output payment summary form print ''; print ' '; print "\n"; -$var = true; foreach ($dirsociete as $dirroot) { $dir = dol_buildpath($dirroot,0); @@ -327,7 +326,6 @@ foreach ($dirsociete as $dirroot) if ($modCodeTiers->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($modCodeTiers->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; - $var = !$var; print ''."\n"; print ''."\n"; print ''."\n"; @@ -380,7 +378,6 @@ print ''; print ''; print "\n"; -$var=true; foreach ($dirsociete as $dirroot) { $dir = dol_buildpath($dirroot,0); @@ -403,7 +400,6 @@ foreach ($dirsociete as $dirroot) } $modCodeCompta = new $file; - $var = !$var; print ''; print ''; print ''; print "\n"; -$var=true; foreach ($dirsociete as $dirroot) { $dir = dol_buildpath($dirroot.'doc/',0); @@ -507,7 +502,6 @@ foreach ($dirsociete as $dirroot) if ($modulequalified) { - $var = !$var; print ''; print ''; print "\n"; -$profid[0][0]=$langs->trans("ProfId1"); -$profid[0][1]=$langs->transcountry('ProfId1', $mysoc->country_code); -$profid[1][0]=$langs->trans("ProfId2"); -$profid[1][1]=$langs->transcountry('ProfId2', $mysoc->country_code); -$profid[2][0]=$langs->trans("ProfId3"); -$profid[2][1]=$langs->transcountry('ProfId3', $mysoc->country_code); -$profid[3][0]=$langs->trans("ProfId4"); -$profid[3][1]=$langs->transcountry('ProfId4', $mysoc->country_code); -$profid[4][0]=$langs->trans("ProfId5"); -$profid[4][1]=$langs->transcountry('ProfId5', $mysoc->country_code); -$profid[5][0]=$langs->trans("ProfId6"); -$profid[5][1]=$langs->transcountry('ProfId6', $mysoc->country_code); - -$var = true; -$i=0; +$profid['IDPROF1'][0]=$langs->trans("ProfId1"); +$profid['IDPROF1'][1]=$langs->transcountry('ProfId1', $mysoc->country_code); +$profid['IDPROF2'][0]=$langs->trans("ProfId2"); +$profid['IDPROF2'][1]=$langs->transcountry('ProfId2', $mysoc->country_code); +$profid['IDPROF3'][0]=$langs->trans("ProfId3"); +$profid['IDPROF3'][1]=$langs->transcountry('ProfId3', $mysoc->country_code); +$profid['IDPROF4'][0]=$langs->trans("ProfId4"); +$profid['IDPROF4'][1]=$langs->transcountry('ProfId4', $mysoc->country_code); +$profid['IDPROF5'][0]=$langs->trans("ProfId5"); +$profid['IDPROF5'][1]=$langs->transcountry('ProfId5', $mysoc->country_code); +$profid['IDPROF6'][0]=$langs->trans("ProfId6"); +$profid['IDPROF6'][1]=$langs->transcountry('ProfId6', $mysoc->country_code); +$profid['EMAIL'][0]=$langs->trans("EMail"); +$profid['EMAIL'][1]=$langs->trans('Email'); $nbofloop=count($profid); -while ($i < $nbofloop) +foreach($profid as $key => $val) { - if ($profid[$i][1]!='-') + if ($profid[$key][1]!='-') { - $var = !$var; - print ''; - print ''; - $idprof_unique ='SOCIETE_IDPROF'.($i+1).'_UNIQUE'; - $idprof_mandatory ='SOCIETE_IDPROF'.($i+1).'_MANDATORY'; - $idprof_invoice_mandatory ='SOCIETE_IDPROF'.($i+1).'_INVOICE_MANDATORY'; + $idprof_unique ='SOCIETE_'.$key.'_UNIQUE'; + $idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY'; + $idprof_invoice_mandatory ='SOCIETE_'.$key.'_INVOICE_MANDATORY'; + $verif=(empty($conf->global->$idprof_unique)?false:true); $mandatory=(empty($conf->global->$idprof_mandatory)?false:true); $invoice_mandatory=(empty($conf->global->$idprof_invoice_mandatory)?false:true); if ($verif) { - print ''; } else { - print ''; } if ($mandatory) { - print ''; } else { - print ''; } if ($invoice_mandatory) { - print ''; } else { - print ''; } @@ -683,7 +675,6 @@ print load_fiche_titre($langs->trans("Other"),'',''); // Autres options $form=new Form($db); -$var=true; print ''; print ''; diff --git a/htdocs/societe/admin/societe_extrafields.php b/htdocs/societe/admin/societe_extrafields.php index a722ec61b86..8826f1e4750 100644 --- a/htdocs/societe/admin/societe_extrafields.php +++ b/htdocs/societe/admin/societe_extrafields.php @@ -38,7 +38,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/societe/agenda.php b/htdocs/societe/agenda.php index 497b9593142..73b662741cd 100644 --- a/htdocs/societe/agenda.php +++ b/htdocs/societe/agenda.php @@ -76,7 +76,7 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { // Cancel - if (GETPOST("cancel") && ! empty($backtopage)) + if (GETPOST('cancel','alpha') && ! empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -155,30 +155,32 @@ if ($socid > 0) } - print '
    '; + //print '
    '; + //print '
    '; + + $morehtmlcenter=''; if (! empty($conf->agenda->enabled)) { if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) { - print ''.$langs->trans("AddAction").''; + $morehtmlcenter.=''.$langs->trans("AddAction").''; } else { - print ''.$langs->trans("AddAction").''; + $morehtmlcenter.=''.$langs->trans("AddAction").''; } } - print '
    '; - if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) )) { + print '
    '; + $param='&socid='.$socid; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - - print load_fiche_titre($langs->trans("ActionsOnCompany"),'',''); + print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $morehtmlcenter, 0, -1, '', '', '', '', 0, 1, 1); // List of all actions $filters=array(); diff --git a/htdocs/societe/ajax/company.php b/htdocs/societe/ajax/company.php index 93af8509e32..349e19b0c26 100644 --- a/htdocs/societe/ajax/company.php +++ b/htdocs/societe/ajax/company.php @@ -28,7 +28,6 @@ if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); -if (empty($_GET['keysearch']) && ! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); require '../../main.inc.php'; @@ -74,7 +73,6 @@ else require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; $langs->load("companies"); - $langs->load("main"); top_httphead(); diff --git a/htdocs/societe/canvas/company/tpl/card_create.tpl.php b/htdocs/societe/canvas/company/tpl/card_create.tpl.php index d542f0553ba..45b5e76fcda 100644 --- a/htdocs/societe/canvas/company/tpl/card_create.tpl.php +++ b/htdocs/societe/canvas/company/tpl/card_create.tpl.php @@ -133,7 +133,7 @@ - + diff --git a/htdocs/societe/canvas/company/tpl/card_edit.tpl.php b/htdocs/societe/canvas/company/tpl/card_edit.tpl.php index 1f6201ec829..951d17c5b63 100644 --- a/htdocs/societe/canvas/company/tpl/card_edit.tpl.php +++ b/htdocs/societe/canvas/company/tpl/card_edit.tpl.php @@ -148,7 +148,7 @@ if ($this->control->tpl['fournisseur']) { - + diff --git a/htdocs/societe/canvas/individual/tpl/card_create.tpl.php b/htdocs/societe/canvas/individual/tpl/card_create.tpl.php index 1be20214c35..44bf9dadf58 100644 --- a/htdocs/societe/canvas/individual/tpl/card_create.tpl.php +++ b/htdocs/societe/canvas/individual/tpl/card_create.tpl.php @@ -143,7 +143,7 @@ - + diff --git a/htdocs/societe/canvas/individual/tpl/card_edit.tpl.php b/htdocs/societe/canvas/individual/tpl/card_edit.tpl.php index 90543958902..81e0b66c103 100644 --- a/htdocs/societe/canvas/individual/tpl/card_edit.tpl.php +++ b/htdocs/societe/canvas/individual/tpl/card_edit.tpl.php @@ -145,7 +145,7 @@ if ($this->control->tpl['fournisseur']) { - + diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index 4807591b9f3..02ec2a7da0b 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -56,10 +56,10 @@ if (! empty($conf->notification->enabled)) $langs->load("mails"); $mesg=''; $error=0; $errors=array(); $action = (GETPOST('action','aZ09') ? GETPOST('action','aZ09') : 'view'); -$cancel = GETPOST('cancel'); +$cancel = GETPOST('cancel','alpha'); $backtopage = GETPOST('backtopage','alpha'); $confirm = GETPOST('confirm'); -$socid = GETPOST('socid','int'); +$socid = GETPOST('socid','int')?GETPOST('socid','int'):GETPOST('id','int'); if ($user->societe_id) $socid=$user->societe_id; if (empty($socid) && $action == 'view') $action='create'; @@ -94,7 +94,6 @@ if (! empty($canvas)) $result = restrictedArea($user, 'societe', $socid, '&societe', '', 'fk_soc', 'rowid', $objcanvas); - /* * Actions */ @@ -176,16 +175,20 @@ if (empty($reshook)) } } - // TODO Merge categories - + // Merge categories + $static_cat = new Categorie($db); + $custcats = $static_cat->containing($soc_origin->id, 'customer', 'id'); + $object->setCategories($custcats, 'customer'); + $suppcats = $static_cat->containing($soc_origin->id, 'supplier', 'id'); + $object->setCategories($suppcats, 'supplier'); + // Update $object->update($object->id, $user); // Move links $objects = array( 'Adherent' => '/adherents/class/adherent.class.php', 'Societe' => '/societe/class/societe.class.php', - 'Bookmark' => '/bookmarks/class/bookmark.class.php', 'Categorie' => '/categories/class/categorie.class.php', 'ActionComm' => '/comm/action/class/actioncomm.class.php', 'Propal' => '/comm/propal/class/propal.class.php', @@ -292,11 +295,17 @@ if (empty($reshook)) $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); if ($ret < 0) $error++; + if (! $error) { $result = $object->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } + if ($error) $action = 'edit_extras'; } @@ -310,191 +319,155 @@ if (empty($reshook)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdPartyName")), null, 'errors'); $error++; - $action='create'; } if (GETPOST('client') < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProspectCustomer")), null, 'errors'); $error++; - $action='create'; } if (GETPOST('fournisseur') < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Supplier")), null, 'errors'); $error++; - $action='create'; + } - - if ($action == 'update') + if (! $error) { - $ret=$object->fetch($socid); - $object->oldcopy = clone $object; - } - else $object->canvas=$canvas; + if ($action == 'update') + { + $ret=$object->fetch($socid); + $object->oldcopy = clone $object; + } + else $object->canvas=$canvas; - if (GETPOST("private") == 1) - { - $object->particulier = GETPOST("private"); + if (GETPOST("private") == 1) // Ask to create a contact + { + $object->particulier = GETPOST("private"); - $object->name = dolGetFirstLastname(GETPOST('firstname','alpha'),GETPOST('name','alpha')); - $object->civility_id = GETPOST('civility_id'); // Note: civility id is a code, not an int - // Add non official properties - $object->name_bis = GETPOST('name','alpha'); - $object->firstname = GETPOST('firstname','alpha'); - } - else - { - $object->name = GETPOST('name', 'alpha'); - } - $object->name_alias = GETPOST('name_alias'); - $object->address = GETPOST('address'); - $object->zip = GETPOST('zipcode', 'alpha'); - $object->town = GETPOST('town', 'alpha'); - $object->country_id = GETPOST('country_id', 'int'); - $object->state_id = GETPOST('state_id', 'int'); - $object->skype = GETPOST('skype', 'alpha'); - $object->phone = GETPOST('phone', 'alpha'); - $object->fax = GETPOST('fax','alpha'); - $object->email = GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL); - $object->url = GETPOST('url', 'custom', 0, FILTER_SANITIZE_URL); - $object->idprof1 = GETPOST('idprof1', 'alpha'); - $object->idprof2 = GETPOST('idprof2', 'alpha'); - $object->idprof3 = GETPOST('idprof3', 'alpha'); - $object->idprof4 = GETPOST('idprof4', 'alpha'); - $object->idprof5 = GETPOST('idprof5', 'alpha'); - $object->idprof6 = GETPOST('idprof6', 'alpha'); - $object->prefix_comm = GETPOST('prefix_comm', 'alpha'); - $object->code_client = GETPOST('code_client', 'alpha'); - $object->code_fournisseur = GETPOST('code_fournisseur', 'alpha'); - $object->capital = GETPOST('capital', 'alpha'); - $object->barcode = GETPOST('barcode', 'alpha'); + $object->name = dolGetFirstLastname(GETPOST('firstname','alpha'),GETPOST('name','alpha')); + $object->civility_id = GETPOST('civility_id'); // Note: civility id is a code, not an int + // Add non official properties + $object->name_bis = GETPOST('name','alpha'); + $object->firstname = GETPOST('firstname','alpha'); + } + else + { + $object->name = GETPOST('name', 'alpha'); + } + $object->name_alias = GETPOST('name_alias'); + $object->address = GETPOST('address'); + $object->zip = GETPOST('zipcode', 'alpha'); + $object->town = GETPOST('town', 'alpha'); + $object->country_id = GETPOST('country_id', 'int'); + $object->state_id = GETPOST('state_id', 'int'); + $object->skype = GETPOST('skype', 'alpha'); + $object->phone = GETPOST('phone', 'alpha'); + $object->fax = GETPOST('fax','alpha'); + $object->email = trim(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL)); + $object->url = trim(GETPOST('url', 'custom', 0, FILTER_SANITIZE_URL)); + $object->idprof1 = trim(GETPOST('idprof1', 'alpha')); + $object->idprof2 = trim(GETPOST('idprof2', 'alpha')); + $object->idprof3 = trim(GETPOST('idprof3', 'alpha')); + $object->idprof4 = trim(GETPOST('idprof4', 'alpha')); + $object->idprof5 = trim(GETPOST('idprof5', 'alpha')); + $object->idprof6 = trim(GETPOST('idprof6', 'alpha')); + $object->prefix_comm = GETPOST('prefix_comm', 'alpha'); + $object->code_client = GETPOST('code_client', 'alpha'); + $object->code_fournisseur = GETPOST('code_fournisseur', 'alpha'); + $object->capital = GETPOST('capital', 'alpha'); + $object->barcode = GETPOST('barcode', 'alpha'); - $object->tva_intra = GETPOST('tva_intra', 'alpha'); - $object->tva_assuj = GETPOST('assujtva_value', 'alpha'); - $object->status = GETPOST('status', 'alpha'); + $object->tva_intra = GETPOST('tva_intra', 'alpha'); + $object->tva_assuj = GETPOST('assujtva_value', 'alpha'); + $object->status = GETPOST('status', 'alpha'); - // Local Taxes - $object->localtax1_assuj = GETPOST('localtax1assuj_value', 'alpha'); - $object->localtax2_assuj = GETPOST('localtax2assuj_value', 'alpha'); + // Local Taxes + $object->localtax1_assuj = GETPOST('localtax1assuj_value', 'alpha'); + $object->localtax2_assuj = GETPOST('localtax2assuj_value', 'alpha'); - $object->localtax1_value = GETPOST('lt1', 'alpha'); - $object->localtax2_value = GETPOST('lt2', 'alpha'); + $object->localtax1_value = GETPOST('lt1', 'alpha'); + $object->localtax2_value = GETPOST('lt2', 'alpha'); - $object->forme_juridique_code = GETPOST('forme_juridique_code', 'int'); - $object->effectif_id = GETPOST('effectif_id', 'int'); - $object->typent_id = GETPOST('typent_id'); + $object->forme_juridique_code = GETPOST('forme_juridique_code', 'int'); + $object->effectif_id = GETPOST('effectif_id', 'int'); + $object->typent_id = GETPOST('typent_id','int'); - $object->client = GETPOST('client', 'int'); - $object->fournisseur = GETPOST('fournisseur', 'int'); + $object->typent_code = dol_getIdFromCode($db, $object->typent_id, 'c_typent', 'id', 'code'); // Force typent_code too so check in verify() will be done on new type - $object->commercial_id = GETPOST('commercial_id', 'int'); - $object->default_lang = GETPOST('default_lang'); + $object->client = GETPOST('client', 'int'); + $object->fournisseur = GETPOST('fournisseur', 'int'); - // Webservices url/key - $object->webservices_url = GETPOST('webservices_url', 'custom', 0, FILTER_SANITIZE_URL); - $object->webservices_key = GETPOST('webservices_key', 'san_alpha'); + $object->commercial_id = GETPOST('commercial_id', 'int'); + $object->default_lang = GETPOST('default_lang'); - // Incoterms - if (!empty($conf->incoterm->enabled)) - { - $object->fk_incoterms = GETPOST('incoterm_id', 'int'); - $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); - } + // Webservices url/key + $object->webservices_url = GETPOST('webservices_url', 'custom', 0, FILTER_SANITIZE_URL); + $object->webservices_key = GETPOST('webservices_key', 'san_alpha'); - // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { - $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); - } + // Incoterms + if (!empty($conf->incoterm->enabled)) + { + $object->fk_incoterms = GETPOST('incoterm_id', 'int'); + $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); + } - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - if ($ret < 0) - { - $error++; - $action = ($action=='add'?'create':'edit'); - } + // Multicurrency + if (!empty($conf->multicurrency->enabled)) + { + $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); + } - if (GETPOST('deletephoto')) $object->logo = ''; - else if (! empty($_FILES['photo']['name'])) $object->logo = dol_sanitizeFileName($_FILES['photo']['name']); + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) + { + $error++; + } - // Check parameters - if (! GETPOST("cancel")) - { - if (! empty($object->email) && ! isValidEMail($object->email)) - { - $langs->load("errors"); - $error++; $errors[] = $langs->trans("ErrorBadEMail",$object->email); - $action = ($action=='add'?'create':'edit'); - } - if (! empty($object->url) && ! isValidUrl($object->url)) - { - $langs->load("errors"); - $error++; $errors[] = $langs->trans("ErrorBadUrl",$object->url); - $action = ($action=='add'?'create':'edit'); - } - if ($object->fournisseur && ! $conf->fournisseur->enabled) - { - $langs->load("errors"); - $error++; $errors[] = $langs->trans("ErrorSupplierModuleNotEnabled"); - $action = ($action=='add'?'create':'edit'); - } - if (! empty($object->webservices_url)) { - //Check if has transport, without any the soap client will give error - if (strpos($object->webservices_url, "http") === false) - { - $object->webservices_url = "http://".$object->webservices_url; - } - if (! isValidUrl($object->webservices_url)) { - $langs->load("errors"); - $error++; $errors[] = $langs->trans("ErrorBadUrl",$object->webservices_url); - $action = ($action=='add'?'create':'edit'); - } - } + if (GETPOST('deletephoto')) $object->logo = ''; + else if (! empty($_FILES['photo']['name'])) $object->logo = dol_sanitizeFileName($_FILES['photo']['name']); - // We set country_id, country_code and country for the selected country - $object->country_id=GETPOST('country_id')!=''?GETPOST('country_id'):$mysoc->country_id; - if ($object->country_id) - { - $tmparray=getCountry($object->country_id,'all'); - $object->country_code=$tmparray['code']; - $object->country=$tmparray['label']; - } + // Check parameters + if (! GETPOST('cancel','alpha')) + { + if (! empty($object->email) && ! isValidEMail($object->email)) + { + $langs->load("errors"); + $error++; + setEventMessages('', $langs->trans("ErrorBadEMail",$object->email), 'errors'); + } + if (! empty($object->url) && ! isValidUrl($object->url)) + { + $langs->load("errors"); + setEventMessages('', $langs->trans("ErrorBadUrl",$object->url), 'errors'); + } + if ($object->fournisseur && ! $conf->fournisseur->enabled) + { + $langs->load("errors"); + setEventMessages('', $langs->trans("ErrorSupplierModuleNotEnabled"), 'errors'); + } + if (! empty($object->webservices_url)) { + //Check if has transport, without any the soap client will give error + if (strpos($object->webservices_url, "http") === false) + { + $object->webservices_url = "http://".$object->webservices_url; + } + if (! isValidUrl($object->webservices_url)) { + $langs->load("errors"); + $error++; $errors[] = $langs->trans("ErrorBadUrl",$object->webservices_url); + } + } - // Check for duplicate or mandatory prof id - // Only for companies - if (!($object->particulier || $private)) - { - for ($i = 1; $i <= 6; $i++) - { - $slabel="idprof".$i; - $_POST[$slabel]=trim($_POST[$slabel]); - $vallabel=$_POST[$slabel]; - if ($vallabel && $object->id_prof_verifiable($i)) - { - if($object->id_prof_exists($i,$vallabel,$object->id)) - { - $langs->load("errors"); - $error++; $errors[] = $langs->transcountry('ProfId'.$i, $object->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel); - $action = (($action=='add'||$action=='create')?'create':'edit'); - } - } - - // Check for mandatory prof id (but only if country is than than ours) - if ($mysoc->country_id > 0 && $object->country_id == $mysoc->country_id) - { - $idprof_mandatory ='SOCIETE_IDPROF'.($i).'_MANDATORY'; - if (! $vallabel && ! empty($conf->global->$idprof_mandatory)) - { - $langs->load("errors"); - $error++; - $errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $object->country_code)); - $action = (($action=='add'||$action=='create')?'create':'edit'); - } - } - } - } + // We set country_id, country_code and country for the selected country + $object->country_id=GETPOST('country_id')!=''?GETPOST('country_id'):$mysoc->country_id; + if ($object->country_id) + { + $tmparray=getCountry($object->country_id,'all'); + $object->country_code=$tmparray['code']; + $object->country=$tmparray['label']; + } + } } if (! $error) @@ -512,16 +485,17 @@ if (empty($reshook)) { if ($object->particulier) { - dol_syslog("This thirdparty is a personal people",LOG_DEBUG); + dol_syslog("We ask to create a contact/address too", LOG_DEBUG); $result=$object->create_individual($user); - if (! $result >= 0) + if ($result < 0) { - $error=$object->error; $errors=$object->errors; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; } } // Customer categories association - $custcats = GETPOST( 'custcats', 'array' ); + $custcats = GETPOST('custcats', 'array'); $object->setCategories($custcats, 'customer'); // Supplier categories association @@ -578,7 +552,8 @@ if (empty($reshook)) $object->code_client = null; } - $error=$object->error; $errors=$object->errors; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; } if ($result >= 0) @@ -610,7 +585,7 @@ if (empty($reshook)) if ($action == 'update') { - if (GETPOST("cancel")) + if (GETPOST('cancel','alpha')) { if (! empty($backtopage)) { @@ -632,11 +607,12 @@ if (empty($reshook)) $result = $object->update($socid, $user, 1, $object->oldcopy->codeclient_modifiable(), $object->oldcopy->codefournisseur_modifiable(), 'update', 0); if ($result <= 0) { - $error = $object->error; $errors = $object->errors; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; } // Customer categories association - $categories = GETPOST( 'custcats', 'array' ); + $categories = GETPOST('custcats', 'array'); $object->setCategories($categories, 'customer'); // Supplier categories association @@ -686,7 +662,7 @@ if (empty($reshook)) } } else - { + { switch($_FILES['photo']['error']) { case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini @@ -716,7 +692,7 @@ if (empty($reshook)) if (! $error && ! count($errors)) { - if (! empty($backtopage)) + if (! empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -734,6 +710,10 @@ if (empty($reshook)) } } } + else + { + $action = ($action=='add'?'create':'edit'); + } } // Delete third party @@ -750,7 +730,8 @@ if (empty($reshook)) else { $langs->load("errors"); - $error=$langs->trans($object->error); $errors = $object->errors; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; $action=''; } } @@ -785,7 +766,6 @@ if (empty($reshook)) } - /* * View */ @@ -1017,13 +997,13 @@ else dol_htmloutput_mesg(is_numeric($error)?'':$error, $errors, 'error'); - print ''; + print ''; // Chrome ignor autocomplete print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) print ''; @@ -1069,7 +1049,7 @@ else // Prospect/Customer print ''; print ''; print ''; } @@ -1524,22 +1504,22 @@ if ($action == 'create') if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { - // Bank Account - print ''; - print ''; + // Bank Account + print ''; + print ''; } // Other attributes @@ -1645,7 +1625,7 @@ if ($action == 'create') include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
    '; + print '
    '; print '

    '.$text.'

    '.$text.'

    '.$langs->trans("WelcomeOnPaymentPage").'

    '.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'


    '.$langs->trans("WelcomeOnPaymentPage").'
    '.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'

    '; print ''; -print ''."\n"; +print ''."\n"; $found=false; $error=0; $var=false; +$object = null; + + // Free payment -if (! GETPOST("source")) +if (! $source) { $found=true; $tag=GETPOST("tag"); $fulltag=$tag; // Creditor - print ''."\n"; + print ''."\n"; // Amount - print ''."\n"; // Tag - print ''."\n"; - // We do not add fields shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum - // as they don't exists (buyer is unknown, tag is free). + // We do not add fields shipToName, shipToStreet, shipToCity, shipToState, shipToCountryCode, shipToZip, shipToStreet2, phoneNum + // as they don't exists (buyer is unknown, tag is free). } // Payment on customer order -if (GETPOST("source") == 'order') +if ($source == 'order') { $found=true; $langs->load("orders"); @@ -500,7 +677,7 @@ if (GETPOST("source") == 'order') $order=new Commande($db); $result=$order->fetch('',$ref); - if ($result < 0) + if ($result <= 0) { $mesg=$order->error; $error++; @@ -508,14 +685,16 @@ if (GETPOST("source") == 'order') else { $result=$order->fetch_thirdparty($order->socid); + + $object = $order; } - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { - $amount=$order->total_ttc; - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } + if ($action != 'dopayment') // Do not change amount if we just click on first dopayment + { + $amount=$order->total_ttc; + if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); + $amount=price2num($amount); + } $fulltag='ORD='.$order->ref.'.CUS='.$order->thirdparty->id; //$fulltag.='.NAM='.strtr($order->thirdparty->name,"-"," "); @@ -523,39 +702,43 @@ if (GETPOST("source") == 'order') $fulltag=dol_string_unaccent($fulltag); // Creditor - print ''."\n"; + print ''."\n"; // Debitor - print ''."\n"; // Amount - print ''."\n"; // Tag - print ''."\n"; + print ''."\n"; // Debitor - print ''."\n"; // Amount - print ''."\n"; // Tag - print ''."\n"; - // Shipping address - $shipToName=$invoice->thirdparty->name; - $shipToStreet=$invoice->thirdparty->address; - $shipToCity=$invoice->thirdparty->town; - $shipToState=$invoice->thirdparty->state_code; - $shipToCountryCode=$invoice->thirdparty->country_code; - $shipToZip=$invoice->thirdparty->zip; - $shipToStreet2=''; - $phoneNum=$invoice->thirdparty->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - } - else - { - print ''."\n"; - } - print ''."\n"; - print 'ref.'">'."\n"; + // Add download link + if ($download > 0) + { + print ''."\n"; + } + + // Shipping address + $shipToName=$invoice->thirdparty->name; + $shipToStreet=$invoice->thirdparty->address; + $shipToCity=$invoice->thirdparty->town; + $shipToState=$invoice->thirdparty->state_code; + $shipToCountryCode=$invoice->thirdparty->country_code; + $shipToZip=$invoice->thirdparty->zip; + $shipToStreet2=''; + $phoneNum=$invoice->thirdparty->phone; + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) + { + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + } + else + { + print ''."\n"; + } + print ''."\n"; + print ''."\n"; + $labeldesc=$langs->trans("Invoice").' '.$invoice->ref; + if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); + print ''."\n"; } // Payment on contract line -if (GETPOST("source") == 'contractline') +if ($source == 'contractline') { $found=true; $langs->load("contracts"); require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; + $contract=new Contrat($db); $contractline=new ContratLigne($db); + $result=$contractline->fetch('',$ref); - if ($result < 0) + if ($result <= 0) { $mesg=$contractline->error; $error++; @@ -728,7 +932,8 @@ if (GETPOST("source") == 'contractline') { if ($contractline->fk_contrat > 0) { - $contract=new Contrat($db); + $object = $contractline; + $result=$contract->fetch($contractline->fk_contrat); if ($result > 0) { @@ -747,39 +952,40 @@ if (GETPOST("source") == 'contractline') } } - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { - $amount=$contractline->total_ttc; + if ($action != 'dopayment') // Do not change amount if we just click on first dopayment + { + $amount=$contractline->total_ttc; - if ($contractline->fk_product && ! empty($conf->global->PAYMENT_USE_NEW_PRICE_FOR_CONTRACTLINES)) - { - $product=new Product($db); - $result=$product->fetch($contractline->fk_product); + if ($contractline->fk_product && ! empty($conf->global->PAYMENT_USE_NEW_PRICE_FOR_CONTRACTLINES)) + { + $product=new Product($db); + $result=$product->fetch($contractline->fk_product); - // We define price for product (TODO Put this in a method in product class) - if (! empty($conf->global->PRODUIT_MULTIPRICES)) - { - $pu_ht = $product->multiprices[$contract->thirdparty->price_level]; - $pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level]; - $price_base_type = $product->multiprices_base_type[$contract->thirdparty->price_level]; - } - else - { - $pu_ht = $product->price; - $pu_ttc = $product->price_ttc; - $price_base_type = $product->price_base_type; - } + // We define price for product (TODO Put this in a method in product class) + if (! empty($conf->global->PRODUIT_MULTIPRICES)) + { + $pu_ht = $product->multiprices[$contract->thirdparty->price_level]; + $pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level]; + $price_base_type = $product->multiprices_base_type[$contract->thirdparty->price_level]; + } + else + { + $pu_ht = $product->price; + $pu_ttc = $product->price_ttc; + $price_base_type = $product->price_base_type; + } - $amount=$pu_ttc; - if (empty($amount)) - { - dol_print_error('','ErrorNoPriceDefinedForThisProduct'); - exit; - } - } - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } + $amount=$pu_ttc; + if (empty($amount)) + { + dol_print_error('','ErrorNoPriceDefinedForThisProduct'); + exit; + } + } + + if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); + $amount=price2num($amount); + } $fulltag='COL='.$contractline->ref.'.CON='.$contract->ref.'.CUS='.$contract->thirdparty->id.'.DAT='.dol_print_date(dol_now(),'%Y%m%d%H%M'); //$fulltag.='.NAM='.strtr($contract->thirdparty->name,"-"," "); @@ -790,19 +996,16 @@ if (GETPOST("source") == 'contractline') if (GETPOST('qty')) $qty=GETPOST('qty'); // Creditor - print ''."\n"; // Debitor - print ''."\n"; // Quantity - $label=$langs->trans("Quantity"); $qty=1; $duration=''; @@ -853,18 +1062,17 @@ if (GETPOST("source") == 'contractline') print ''."\n"; // Amount - print ''."\n"; // Tag - print ''."\n"; - // Shipping address - $shipToName=$contract->thirdparty->name; - $shipToStreet=$contract->thirdparty->address; - $shipToCity=$contract->thirdparty->town; - $shipToState=$contract->thirdparty->state_code; - $shipToCountryCode=$contract->thirdparty->country_code; - $shipToZip=$contract->thirdparty->zip; - $shipToStreet2=''; - $phoneNum=$contract->thirdparty->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - } - else - { - print ''."\n"; - } - print ''."\n"; - print 'ref.'">'."\n"; + // Shipping address + $shipToName=$contract->thirdparty->name; + $shipToStreet=$contract->thirdparty->address; + $shipToCity=$contract->thirdparty->town; + $shipToState=$contract->thirdparty->state_code; + $shipToCountryCode=$contract->thirdparty->country_code; + $shipToZip=$contract->thirdparty->zip; + $shipToStreet2=''; + $phoneNum=$contract->thirdparty->phone; + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) + { + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + } + else + { + print ''."\n"; + } + print ''."\n"; + print ''."\n"; + $labeldesc=$langs->trans("Contract").' '.$contract->ref; + if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); + print ''."\n"; } // Payment on member subscription -if (GETPOST("source") == 'membersubscription') +if ($source == 'membersubscription') { $found=true; $langs->load("members"); @@ -919,22 +1129,24 @@ if (GETPOST("source") == 'membersubscription') $member=new Adherent($db); $result=$member->fetch('',$ref); - if ($result < 0) + if ($result <= 0) { $mesg=$member->error; $error++; } else { + $object = $member; + $subscription=new Subscription($db); } - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { - $amount=$subscription->total_ttc; - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } + if ($action != 'dopayment') // Do not change amount if we just click on first dopayment + { + $amount=$subscription->total_ttc; + if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); + $amount=price2num($amount); + } $fulltag='MEM='.$member->id.'.DAT='.dol_print_date(dol_now(),'%Y%m%d%H%M'); if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; } @@ -943,9 +1155,9 @@ if (GETPOST("source") == 'membersubscription') // Creditor print ''."\n"; + print ''."\n"; // Debitor @@ -958,10 +1170,11 @@ if (GETPOST("source") == 'membersubscription') // Object $text=''.$langs->trans("PaymentSubscription").''; + if (GETPOST('desc','alpha')) $text=''.$langs->trans(GETPOST('desc','alpha')).''; print ''."\n"; if ($member->last_subscription_date || $member->last_subscription_amount) @@ -986,23 +1199,38 @@ if (GETPOST("source") == 'membersubscription') print ''."\n"; - // Shipping address - $shipToName=$member->getFullName($langs); - $shipToStreet=$member->address; - $shipToCity=$member->town; - $shipToState=$member->state_code; - $shipToCountryCode=$member->country_code; - $shipToZip=$member->zip; - $shipToStreet2=''; - $phoneNum=$member->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - } - else - { - print ''."\n"; - } - print ''."\n"; - print ''."\n"; + // Shipping address + $shipToName=$member->getFullName($langs); + $shipToStreet=$member->address; + $shipToCity=$member->town; + $shipToState=$member->state_code; + $shipToCountryCode=$member->country_code; + $shipToZip=$member->zip; + $shipToStreet2=''; + $phoneNum=$member->phone; + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) + { + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + } + else + { + print ''."\n"; + } + print ''."\n"; + $labeldesc = $langs->trans("PaymentSubscription"); + if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); + print ''."\n"; } @@ -1058,51 +1288,233 @@ print "\n"; if ($action != 'dopayment') { - if ($found && ! $error) // We are in a management option and no error - { - // Buttons for all payments registration methods + if ($found && ! $error) // We are in a management option and no error + { + // Buttons for all payments registration methods - if (! empty($conf->paypal->enabled)) - { - if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY='integral'; + if (! empty($conf->paybox->enabled)) + { + // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of paybox + print '
    '; + } - if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') - { - print '
    '; - } - if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') - { - print '
    '; - } - } + if (! empty($conf->stripe->enabled)) + { + // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of stripe + print '
    '; + } - if (! empty($conf->paybox->enabled)) - { + if (! empty($conf->paypal->enabled)) + { + if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY='integral'; - - } - - // TODO Other methods - } - else - { - dol_print_error_email('ERRORNEWPAYMENTPAYPAL'); - } + if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') + { + print '
    '; + } + if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') + { + print '
    '; + } + } + } + else + { + dol_print_error_email('ERRORNEWPAYMENT'); + } } else { - // Print + // Print } print ''."\n"; print '
    '.$langs->trans("ThisIsInformationOnPayment").' :
    '.$langs->trans("ThisIsInformationOnPayment").' :
    '.$langs->trans("Creditor"); - print ''.$creditor.''; - print ''; - print '
    '.$creditor.''; + print ''; + print '
    '.$langs->trans("Amount"); if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; print ''; if (empty($amount) || ! is_numeric($amount)) { - print ''; - print ''; + print ''; + print ''; } else { print ''.price($amount).''; - print ''; + print ''; print ''; } // Currency @@ -478,20 +656,19 @@ if (! GETPOST("source")) print '
    '.$langs->trans("PaymentCode"); print ''.$fulltag.''; print ''; print ''; print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; - print ''; - print '
    '.$creditor.''; + print ''; + print '
    '.$langs->trans("ThirdParty"); print ''.$order->thirdparty->name.''; // Object - $text=''.$langs->trans("PaymentOrderRef",$order->ref).''; + if (GETPOST('desc','alpha')) $text=''.$langs->trans(GETPOST('desc','alpha')).''; print '
    '.$langs->trans("Designation"); print ''.$text; - print ''; - print ''; + print ''; + print ''; + $directdownloadlink = $order->getLastMainDocLink('commande'); + if ($directdownloadlink) + { + print '
    '; + print img_mime($order->last_main_doc,'').' '; + print $langs->trans("DownloadDocument").''; + } print '
    '.$langs->trans("Amount"); if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; print ''; if (empty($amount) || ! is_numeric($amount)) { - print ''; - print ''; + print ''; + print ''; } else { print ''.price($amount).''; - print ''; + print ''; print ''; } // Currency @@ -564,7 +747,6 @@ if (GETPOST("source") == 'order') print '
    '.$langs->trans("PaymentCode"); print ''.$fulltag.''; print ''; @@ -573,35 +755,38 @@ if (GETPOST("source") == 'order') // Shipping address $shipToName=$order->thirdparty->name; - $shipToStreet=$order->thirdparty->address; - $shipToCity=$order->thirdparty->town; - $shipToState=$order->thirdparty->state_code; - $shipToCountryCode=$order->thirdparty->country_code; - $shipToZip=$order->thirdparty->zip; - $shipToStreet2=''; - $phoneNum=$order->thirdparty->phone; - if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) - { - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - } - else - { - print ''."\n"; - } - print ''."\n"; - print 'ref.'">'."\n"; + $shipToStreet=$order->thirdparty->address; + $shipToCity=$order->thirdparty->town; + $shipToState=$order->thirdparty->state_code; + $shipToCountryCode=$order->thirdparty->country_code; + $shipToZip=$order->thirdparty->zip; + $shipToStreet2=''; + $phoneNum=$order->thirdparty->phone; + if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) + { + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + } + else + { + print ''."\n"; + } + print ''."\n"; + print ''."\n"; + $labeldesc=$langs->trans("Order").' '.$order->ref; + if (GETPOST('desc','alpha')) $labeldesc=GETPOST('desc','alpha'); + print ''."\n"; } // Payment on customer invoice -if (GETPOST("source") == 'invoice') +if ($source == 'invoice') { $found=true; $langs->load("bills"); @@ -610,7 +795,7 @@ if (GETPOST("source") == 'invoice') $invoice=new Facture($db); $result=$invoice->fetch('',$ref); - if ($result < 0) + if ($result <= 0) { $mesg=$invoice->error; $error++; @@ -618,14 +803,16 @@ if (GETPOST("source") == 'invoice') else { $result=$invoice->fetch_thirdparty($invoice->socid); + + $object = $invoice; } - if ($action != 'dopayment') // Do not change amount if we just click on first dopayment - { - $amount=price2num($invoice->total_ttc - $invoice->getSommePaiement()); - if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); - $amount=price2num($amount); - } + if ($action != 'dopayment') // Do not change amount if we just click on first dopayment + { + $amount=price2num($invoice->total_ttc - $invoice->getSommePaiement()); + if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); + $amount=price2num($amount); + } $fulltag='INV='.$invoice->ref.'.CUS='.$invoice->thirdparty->id; //$fulltag.='.NAM='.strtr($invoice->thirdparty->name,"-"," "); @@ -633,39 +820,43 @@ if (GETPOST("source") == 'invoice') $fulltag=dol_string_unaccent($fulltag); // Creditor - print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; - print ''; - print '
    '.$creditor.''; + print ''; + print '
    '.$langs->trans("ThirdParty"); print ''.$invoice->thirdparty->name.''; // Object - $text=''.$langs->trans("PaymentInvoiceRef",$invoice->ref).''; + if (GETPOST('desc','alpha')) $text=''.$langs->trans(GETPOST('desc','alpha')).''; print '
    '.$langs->trans("Designation"); print ''.$text; - print ''; - print ''; + print ''; + print ''; + $directdownloadlink = $invoice->getLastMainDocLink('facture'); + if ($directdownloadlink) + { + print '
    '; + print img_mime($invoice->last_main_doc,'').' '; + print $langs->trans("DownloadDocument").''; + } print '
    '.$langs->trans("Amount"); if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; print ''; if (empty($amount) || ! is_numeric($amount)) { - print ''; - print ''; + print ''; + print ''; } else { print ''.price($amount).''; - print ''; + print ''; print ''; } // Currency @@ -674,52 +865,65 @@ if (GETPOST("source") == 'invoice') print '
    '.$langs->trans("PaymentCode"); print ''.$fulltag.''; print ''; print ''; print '
    '.$langs->trans("Document"); + print ''; + print $invoice->getDirectExternalLink(1); + print '
    '.$langs->trans("Creditor"); print ''.$creditor.''; - print ''; + print ''; print '
    '.$langs->trans("ThirdParty"); print ''.$contract->thirdparty->name.''; // Object - $text=''.$langs->trans("PaymentRenewContractId",$contract->ref,$contractline->ref).''; if ($contractline->fk_product) { @@ -817,15 +1020,21 @@ if (GETPOST("source") == 'contractline') { $text.='
    '.$langs->trans("ExpiredSince").': '.dol_print_date($contractline->date_fin_validite); } - + if (GETPOST('desc','alpha')) $text=''.$langs->trans(GETPOST('desc','alpha')).''; print '
    '.$langs->trans("Designation"); print ''.$text; - print ''; - print ''; + print ''; + print ''; + $directdownloadlink = $contract->getLastMainDocLink('contract'); + if ($directdownloadlink) + { + print '
    '; + print img_mime($invoice->last_main_doc,'').' '; + print $langs->trans("DownloadDocument").''; + } print '
    '.$langs->trans("Amount"); if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; print ''; if (empty($amount) || ! is_numeric($amount)) { - print ''; - print ''; + print ''; + print ''; } else { print ''.price($amount).''; - print ''; + print ''; print ''; } // Currency @@ -873,43 +1081,45 @@ if (GETPOST("source") == 'contractline') print '
    '.$langs->trans("PaymentCode"); print ''.$fulltag.''; print ''; print ''; print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; - print ''; - print '
    '.$creditor.''; + print ''; + print '
    '.$langs->trans("Designation"); print ''.$text; - print ''; - print ''; + print ''; + print ''; print '
    '.$langs->trans("Amount"); if (empty($amount)) { - print ' ('.$langs->trans("ToComplete"); + if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ' ('.$langs->trans("ToComplete"); if (! empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - '.$langs->trans("SeeHere").''; - print ')'; + if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ')'; } print ''; if (empty($amount) || ! is_numeric($amount)) { - $valtoshow=GETPOST("newamount",'int'); - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); - print ''; - print ''; + $valtoshow=GETPOST("newamount",'int'); + // force default subscription amount to value defined into constant... + if (! empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { + if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + $valtoshow = $conf->global->MEMBER_NEWFORM_AMOUNT; + } + } + else { + if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + $amount = $conf->global->MEMBER_NEWFORM_AMOUNT; + } + } + } + if (empty($amount) || ! is_numeric($amount)) + { + //$valtoshow=GETPOST("newamount",'int'); + if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); + print ''; + print ''; } else { - $valtoshow=$amount; - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); - print ''.price($valtoshow).''; - print ''; + $valtoshow=$amount; + if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT,$valtoshow); + print ''.price($valtoshow).''; + print ''; print ''; } // Currency @@ -1018,32 +1246,34 @@ if (GETPOST("source") == 'membersubscription') print ''; print '
    '."\n"; + print ''."\n"; print ''."\n"; print '
    '; -htmlPrintOnlinePaymentFooter($mysoc,$langs); + +// Add more content on page for some services +if (preg_match('/^dopayment/',$action)) +{ + + // Strip + if (GETPOST('dopayment_stripe','alpha')) + { + // Simple checkout + /* + print ''; + */ + + // Personalized checkout + print ''; + + print ' + +
    +
    '; + + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''; + print ''."\n"; + print ''."\n"; + print ''; + + print ' + +
    + +
    + +
    + +
    + + + +
    +
    + + +
    + +
    + + + + + + '; + } +} + + +htmlPrintOnlinePaymentFooter($mysoc,$langs,1,$suffix,$object); llxFooter('', 'public'); diff --git a/htdocs/public/payment/paymentko.php b/htdocs/public/payment/paymentko.php index 9abcfcf2c58..bdc301a0dce 100644 --- a/htdocs/public/payment/paymentko.php +++ b/htdocs/public/payment/paymentko.php @@ -31,7 +31,7 @@ define("NOCSRFCHECK",1); // We accept to go on this page from external web site. // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); +$entity=(! empty($_GET['e']) ? (int) $_GET['e'] : (! empty($_POST['e']) ? (int) $_POST['e'] : 1)); if (is_numeric($entity)) define("DOLENTITY", $entity); require '../../main.inc.php'; @@ -51,6 +51,7 @@ $langs->load("bills"); $langs->load("companies"); $langs->load("paybox"); $langs->load("paypal"); +$langs->load("stripe"); if (! empty($conf->paypal->enabled)) { @@ -59,11 +60,18 @@ if (! empty($conf->paypal->enabled)) $PAYPALPAYERID=GETPOST('PAYERID'); if (empty($PAYPALPAYERID)) $PAYPALPAYERID=GETPOST('PayerID'); } -// TODO Other payment method +if (! empty($conf->paybox->enabled)) +{ +} +if (! empty($conf->stripe->enabled)) +{ +} $FULLTAG=GETPOST('FULLTAG'); if (empty($FULLTAG)) $FULLTAG=GETPOST('fulltag'); +$suffix=GETPOST("suffix",'aZ09'); + // Detect $paymentmethod $paymentmethod=''; @@ -106,7 +114,7 @@ $object = new stdClass(); // For triggers * View */ -dol_syslog("Callback url when a PayPal payment was canceled. query_string=".(empty($_SERVER["QUERY_STRING"])?'':$_SERVER["QUERY_STRING"])." script_uri=".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG, 0, '_payment'); +dol_syslog("Callback url when an online payment is canceled. query_string=".(empty($_SERVER["QUERY_STRING"])?'':$_SERVER["QUERY_STRING"])." script_uri=".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG, 0, '_payment'); $tracepost = ""; foreach($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; @@ -122,48 +130,29 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice // Set by newpayment.php $paymentType = $_SESSION['PaymentType']; $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["Payment_Amount"]; + $FinalPaymentAmt = $_SESSION['FinalPaymentAmt']; // From env $ipaddress = $_SESSION['ipaddress']; - + // Appel des triggers include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; $interface=new Interfaces($db); $result=$interface->run_triggers('PAYMENTONLINE_PAYMENT_KO',$object,$user,$langs,$conf); if ($result < 0) { $error++; $errors=$interface->errors; } // Fin appel triggers - + // Send an email $sendemail = ''; - if (! empty($conf->paypal->enabled)) - { - if (! empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) - { - $sendemail = $conf->global->PAYPAL_PAYONLINE_SENDEMAIL; - } + if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) + { + $sendemail = $conf->global->ONLINE_PAYMENT_SENDEMAIL; } - // Send an email - if (! empty($conf->paybox->enabled)) - { - if (! empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) - { - $sendemail = $conf->global->PAYBOX_PAYONLINE_SENDEMAIL; - } - } - // Send an email - if (! empty($conf->stripe->enabled)) - { - if (! empty($conf->global->STRIPE_PAYONLINE_SENDEMAIL)) - { - $sendemail = $conf->global->STRIPE_PAYONLINE_SENDEMAIL; - } - } - + if ($sendemail) { $from=$conf->global->MAILING_EMAIL_FROM; $sendto=$sendemail; - + // Define link to login card $appli=constant('DOL_APPLICATION_TITLE'); if (! empty($conf->global->MAIN_APPLICATION_TITLE)) @@ -176,7 +165,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice else $appli.=" ".DOL_VERSION; } else $appli.=" ".DOL_VERSION; - + $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentFailed"); $content=""; @@ -188,7 +177,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice $content.="tag=".$fulltag."\ntoken=".$onlinetoken." paymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $mailfile = new CMailFile($topic, $sendto, $from, $content); - + $result=$mailfile->sendfile(); if ($result) { @@ -199,12 +188,12 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment'); } } - + unset($_SESSION['ipaddress']); } $head=''; -if (! empty($conf->global->PAYMENT_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -215,13 +204,47 @@ llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'online // Show ko message print ''."\n"; print '
    '."\n"; + + +// Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo) +$width=0; +// Define logo and logosmall +$logosmall=$mysoc->logo_small; +$logo=$mysoc->logo; +$paramlogo='ONLINE_PAYMENT_LOGO_'.$suffix; +if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo; +else if (! empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall=$conf->global->ONLINE_PAYMENT_LOGO; +//print ''."\n"; +// Define urllogo +$urllogo=''; +if (! empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) +{ + $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode('thumbs/'.$logosmall); + $width=150; +} +elseif (! empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) +{ + $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode($logo); + $width=150; +} +// Output html code for logo +if ($urllogo) +{ + print '
    '; + print '
    '; +} + print $langs->trans("YourPaymentHasNotBeenRecorded")."

    "; -if (! empty($conf->global->PAYMENT_MESSAGE_KO)) print $conf->global->PAYMENT_MESSAGE_KO; +$key='ONLINE_PAYMENT_MESSAGE_KO'; +if (! empty($conf->global->$key)) print $conf->global->$key; + print "\n
    \n"; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,0,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/payment/paymentok.php b/htdocs/public/payment/paymentok.php index 26022dcd4f8..7ccd95abcdf 100644 --- a/htdocs/public/payment/paymentok.php +++ b/htdocs/public/payment/paymentok.php @@ -31,7 +31,7 @@ define("NOCSRFCHECK",1); // We accept to go on this page from external web site. // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); +$entity=(! empty($_GET['e']) ? (int) $_GET['e'] : (! empty($_POST['e']) ? (int) $_POST['e'] : 1)); if (is_numeric($entity)) define("DOLENTITY", $entity); require '../../main.inc.php'; @@ -67,21 +67,6 @@ if (! empty($conf->paypal->enabled)) if ($urlok) $PAYPAL_API_OK=$urlok; $PAYPAL_API_KO=""; if ($urlko) $PAYPAL_API_KO=$urlko; - if (empty($PAYPAL_API_USER)) - { - dol_print_error('',"Paypal setup param PAYPAL_API_USER not defined"); - return -1; - } - if (empty($PAYPAL_API_PASSWORD)) - { - dol_print_error('',"Paypal setup param PAYPAL_API_PASSWORD not defined"); - return -1; - } - if (empty($PAYPAL_API_SIGNATURE)) - { - dol_print_error('',"Paypal setup param PAYPAL_API_SIGNATURE not defined"); - return -1; - } $PAYPALTOKEN=GETPOST('TOKEN'); if (empty($PAYPALTOKEN)) $PAYPALTOKEN=GETPOST('token'); @@ -91,9 +76,11 @@ if (! empty($conf->paypal->enabled)) $FULLTAG=GETPOST('FULLTAG'); if (empty($FULLTAG)) $FULLTAG=GETPOST('fulltag'); -$source=GETPOST('source'); +$source=GETPOST('s','alpha')?GETPOST('s','alpha'):GETPOST('source','alpha'); $ref=GETPOST('ref'); +$suffix=GETPOST("suffix",'aZ09'); + // Detect $paymentmethod $paymentmethod=''; @@ -143,14 +130,14 @@ $object = new stdClass(); // For triggers * View */ -dol_syslog("Callback url when a payment was done. query_string=".(empty($_SERVER["QUERY_STRING"])?'':$_SERVER["QUERY_STRING"])." script_uri=".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG, 0, '_payment'); +dol_syslog("Callback url when a payment was done. query_string=".(dol_escape_htmltag($_SERVER["QUERY_STRING"])?dol_escape_htmltag($_SERVER["QUERY_STRING"]):'')." script_uri=".(dol_escape_htmltag($_SERVER["SCRIPT_URI"])?dol_escape_htmltag($_SERVER["SCRIPT_URI"]):''), LOG_DEBUG, 0, '_payment'); $tracepost = ""; foreach($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_payment'); $head=''; -if (! empty($conf->global->PAYMENT_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -158,78 +145,120 @@ $conf->dol_hide_leftmenu=1; llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); - // Show message print ''."\n"; print '
    '."\n"; -if (! empty($conf->paypal->enabled)) +// Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo) +$width=0; +// Define logo and logosmall +$logosmall=$mysoc->logo_small; +$logo=$mysoc->logo; +$paramlogo='ONLINE_PAYMENT_LOGO_'.$suffix; +if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo; +else if (! empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall=$conf->global->ONLINE_PAYMENT_LOGO; +//print ''."\n"; +// Define urllogo +$urllogo=''; +if (! empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { - if ($PAYPALTOKEN) - { - // Get on url call - $onlinetoken = $PAYPALTOKEN; - $fulltag = $FULLTAG; - $payerID = $PAYPALPAYERID; - // Set by newpayment.php - $paymentType = $_SESSION['PaymentType']; - $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["Payment_Amount"]; - // From env - $ipaddress = $_SESSION['ipaddress']; - - dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_paypal'); - - // Validate record - if (! empty($paymentType)) - { - dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment'); - $resArray=getDetails($onlinetoken); - //var_dump($resarray); - - dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment'); - $resArray=confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag); - - $ack = strtoupper($resArray["ACK"]); - if ($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING") - { - $object->source = $source; - $object->ref = $ref; - $object->payerID = $payerID; - $object->fulltag = $fulltag; - $object->resArray = $resArray; - - // resArray was built from a string like that - // TOKEN=EC%2d1NJ057703V9359028&TIMESTAMP=2010%2d11%2d01T11%3a40%3a13Z&CORRELATIONID=1efa8c6a36bd8&ACK=Success&VERSION=56&BUILD=1553277&TRANSACTIONID=9B994597K9921420R&TRANSACTIONTYPE=expresscheckout&PAYMENTTYPE=instant&ORDERTIME=2010%2d11%2d01T11%3a40%3a12Z&AMT=155%2e57&FEEAMT=5%2e54&TAXAMT=0%2e00&CURRENCYCODE=EUR&PAYMENTSTATUS=Completed&PENDINGREASON=None&REASONCODE=None - $PAYMENTSTATUS=urldecode($resArray["PAYMENTSTATUS"]); // Should contains 'Completed' - $TRANSACTIONID=urldecode($resArray["TRANSACTIONID"]); - $TAXAMT=urldecode($resArray["TAXAMT"]); - $NOTE=urldecode($resArray["NOTE"]); - - $ispaymentok=True; - } - else - { - //Display a user friendly Error on the page using any of the following error information returned by PayPal - $ErrorCode = urldecode($resArray["L_ERRORCODE0"]); - $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]); - $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]); - $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]); - } - } - else - { - dol_print_error('','Session expired'); - } - } - else - { - dol_print_error('','$PAYPALTOKEN not defined'); - } + $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode('thumbs/'.$logosmall); + $width=150; +} +elseif (! empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) +{ + $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode($logo); + $width=150; +} +// Output html code for logo +if ($urllogo) +{ + print '
    '; + print '
    '; } +if (! empty($conf->paypal->enabled)) +{ + if ($paymentmethod == 'paypal') + { + if ($PAYPALTOKEN) + { + // Get on url call + $onlinetoken = $PAYPALTOKEN; + $fulltag = $FULLTAG; + $payerID = $PAYPALPAYERID; + // Set by newpayment.php + $paymentType = $_SESSION['PaymentType']; + $currencyCodeType = $_SESSION['currencyCodeType']; + $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; + // From env + $ipaddress = $_SESSION['ipaddress']; + + dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_paypal'); + + // Validate record + if (! empty($paymentType)) + { + dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment'); + $resArray=getDetails($onlinetoken); + //var_dump($resarray); + + dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment'); + $resArray=confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag); + + $ack = strtoupper($resArray["ACK"]); + if ($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING") + { + $object->source = $source; + $object->ref = $ref; + $object->payerID = $payerID; + $object->fulltag = $fulltag; + $object->resArray = $resArray; + + // resArray was built from a string like that + // TOKEN=EC%2d1NJ057703V9359028&TIMESTAMP=2010%2d11%2d01T11%3a40%3a13Z&CORRELATIONID=1efa8c6a36bd8&ACK=Success&VERSION=56&BUILD=1553277&TRANSACTIONID=9B994597K9921420R&TRANSACTIONTYPE=expresscheckout&PAYMENTTYPE=instant&ORDERTIME=2010%2d11%2d01T11%3a40%3a12Z&AMT=155%2e57&FEEAMT=5%2e54&TAXAMT=0%2e00&CURRENCYCODE=EUR&PAYMENTSTATUS=Completed&PENDINGREASON=None&REASONCODE=None + $PAYMENTSTATUS=urldecode($resArray["PAYMENTSTATUS"]); // Should contains 'Completed' + $TRANSACTIONID=urldecode($resArray["TRANSACTIONID"]); + $TAXAMT=urldecode($resArray["TAXAMT"]); + $NOTE=urldecode($resArray["NOTE"]); + + $ispaymentok=True; + } + else + { + //Display a user friendly Error on the page using any of the following error information returned by PayPal + $ErrorCode = urldecode($resArray["L_ERRORCODE0"]); + $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]); + $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]); + $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]); + } + } + else + { + dol_print_error('','Session expired'); + } + } + else + { + dol_print_error('','$PAYPALTOKEN not defined'); + } + } +} + +if (! empty($conf->paybox->enabled)) +{ + if ($paymentmethod == 'paybox') $ispaymentok = true; // We call this page only if payment is ok +} + +if (! empty($conf->stripe->enabled)) +{ + if ($paymentmethod == 'stripe') $ispaymentok = true; // We call this page only if payment is ok +} + if ($ispaymentok) { @@ -240,10 +269,11 @@ if ($ispaymentok) // Set by newpayment.php $paymentType = $_SESSION['PaymentType']; $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["Payment_Amount"]; + $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; // From env $ipaddress = $_SESSION['ipaddress']; - + $TRANSACTIONID = $_SESSION['TRANSACTIONID']; + // Appel des triggers include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; $interface=new Interfaces($db); @@ -251,18 +281,16 @@ if ($ispaymentok) if ($result < 0) { $error++; $errors=$interface->errors; } // Fin appel triggers - + print $langs->trans("YourPaymentHasBeenRecorded")."
    \n"; print $langs->trans("ThisIsTransactionId",$TRANSACTIONID)."

    \n"; - if (! empty($conf->global->PAYMENT_MESSAGE_OK)) print $conf->global->PAYMENT_MESSAGE_OK; - + + $key='ONLINE_PAYMENT_MESSAGE_OK'; + if (! empty($conf->global->$key)) print $conf->global->$key; + $sendemail = ''; - if (! empty($conf->global->PAYMENTONLINE_SENDEMAIL)) $sendemail=$conf->global->PAYMENTONLINE_SENDEMAIL; - // TODO Remove local option to keep only the generic one ? - if ($paymentmethod == 'paypal' && ! empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->PAYPAL_PAYONLINE_SENDEMAIL; - if ($paymentmethod == 'paybox' && ! empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->PAYBOX_PAYONLINE_SENDEMAIL; - if ($paymentmethod == 'stripe' && ! empty($conf->global->STRIPE_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->STRIPE_PAYONLINE_SENDEMAIL; - + if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail=$conf->global->ONLINE_PAYMENT_SENDEMAIL; + // Send an email if ($sendemail) { @@ -285,7 +313,7 @@ if ($ispaymentok) else $appli.=" ".DOL_VERSION; } else $appli.=" ".DOL_VERSION; - + $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentReceived"); $tmptag=dolExplodeIntoArray($fulltag,'.','='); @@ -333,33 +361,33 @@ else // Set by newpayment.php $paymentType = $_SESSION['PaymentType']; $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["Payment_Amount"]; + $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; // From env $ipaddress = $_SESSION['ipaddress']; - + // Appel des triggers include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; $interface=new Interfaces($db); $result=$interface->run_triggers('PAYMENTONLINE_PAYMENT_KO',$object,$user,$langs,$conf); if ($result < 0) { $error++; $errors=$interface->errors; } // Fin appel triggers - + print $langs->trans('DoExpressCheckoutPaymentAPICallFailed') . "
    \n"; print $langs->trans('DetailedErrorMessage') . ": " . $ErrorLongMsg."
    \n"; print $langs->trans('ShortErrorMessage') . ": " . $ErrorShortMsg."
    \n"; print $langs->trans('ErrorCode') . ": " . $ErrorCode."
    \n"; print $langs->trans('ErrorSeverityCode') . ": " . $ErrorSeverityCode."
    \n"; - + if ($mysoc->email) print "\nPlease, send a screenshot of this page to ".$mysoc->email."
    \n"; - + $sendemail = ''; if (! empty($conf->global->PAYMENTONLINE_SENDEMAIL)) $sendemail=$conf->global->PAYMENTONLINE_SENDEMAIL; // TODO Remove local option to keep only the generic one ? if ($paymentmethod == 'paypal' && ! empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->PAYPAL_PAYONLINE_SENDEMAIL; if ($paymentmethod == 'paybox' && ! empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->PAYBOX_PAYONLINE_SENDEMAIL; if ($paymentmethod == 'stripe' && ! empty($conf->global->STRIPE_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->STRIPE_PAYONLINE_SENDEMAIL; - + // Send an email if ($sendemail) { @@ -369,7 +397,7 @@ else $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); $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 - + // Define link to login card $appli=constant('DOL_APPLICATION_TITLE'); if (! empty($conf->global->MAIN_APPLICATION_TITLE)) @@ -382,7 +410,7 @@ else else $appli.=" ".DOL_VERSION; } else $appli.=" ".DOL_VERSION; - + $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("ValidationOfPaymentFailed"); $content=""; @@ -392,12 +420,12 @@ else $content.=$langs->transnoentitiesnoconv("OnlinePaymentSystem").': '.$paymentmethod."\n"; $content.=$langs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."\n"; $content.="tag=".$fulltag."\ntoken=".$onlinetoken." paymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; - + $ishtml=dol_textishtml($content); // May contain urls - + require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml); - + $result=$mailfile->sendfile(); if ($result) { @@ -414,7 +442,7 @@ else print "\n
    \n"; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,0,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/paypal/newpayment.php b/htdocs/public/paypal/newpayment.php index 65fbfbd38a7..e7a73a64895 100644 --- a/htdocs/public/paypal/newpayment.php +++ b/htdocs/public/paypal/newpayment.php @@ -3,9 +3,9 @@ * Copyright (C) 2006-2017 Laurent Destailleur * Copyright (C) 2009-2012 Regis Houssin * - * This program is free software: you can redistribute it and/or modify + * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or + * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, @@ -16,7 +16,8 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . * - * For test: https://developer.paypal.com/ + * For paypal test: https://developer.paypal.com/ + * For paybox test: ??? */ /** @@ -242,7 +243,7 @@ if (GETPOST('action','aZ09') == 'dopayment') dol_syslog("SCRIPT_URI: ".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG); // If defined script uri must match domain of PAYPAL_API_OK and PAYPAL_API_KO //$_SESSION["PaymentType"]=$PAYPAL_PAYMENT_TYPE; //$_SESSION["currencyCodeType"]=$PAYPAL_API_DEVISE; - //$_SESSION["Payment_Amount"]=$PAYPAL_API_PRICE; + //$_SESSION["FinalPaymentAmt"]=$PAYPAL_API_PRICE; // A redirect is added if API call successfull print_paypal_redirect($PAYPAL_API_PRICE,$PAYPAL_API_DEVISE,$PAYPAL_PAYMENT_TYPE,$PAYPAL_API_OK,$PAYPAL_API_KO, $FULLTAG); @@ -258,7 +259,7 @@ if (GETPOST('action','aZ09') == 'dopayment') */ $head=''; -if (! empty($conf->global->PAYPAL_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -267,9 +268,9 @@ llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'online // Common variables $creditor=$mysoc->name; -$paramcreditor='PAYPAL_CREDITOR_'.$suffix; +$paramcreditor='ONLINE_PAYMENT_CREDITOR_'.$suffix; if (! empty($conf->global->$paramcreditor)) $creditor=$conf->global->$paramcreditor; -else if (! empty($conf->global->PAYPAL_CREDITOR)) $creditor=$conf->global->PAYPAL_CREDITOR; +else if (! empty($conf->global->ONLINE_PAYMENT_CREDITOR)) $creditor=$conf->global->ONLINE_PAYMENT_CREDITOR; // Check link validity if (! empty($SOURCE) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) @@ -281,7 +282,7 @@ if (! empty($SOURCE) && in_array($ref, array('member_ref', 'contractline_ref', ' exit; } -if (! empty($conf->global->PAYPAL_API_SANDBOX)) +if (! empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox','alpha')) { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode'),'','warning'); } @@ -295,6 +296,7 @@ print ''."\n" print ''."\n"; print ''."\n"; print ''; +print ''; print "\n"; print ''."\n"; print ''."\n"; @@ -306,14 +308,14 @@ print "\n"; print ''."\n"; -// Show logo (search order: logo defined by PAYBOX_LOGO_suffix, then PAYBOX_LOGO, then small company logo, large company logo, theme logo, common logo) +// Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo) $width=0; // Define logo and logosmall $logosmall=$mysoc->logo_small; $logo=$mysoc->logo; -$paramlogo='PAYBOX_LOGO_'.$suffix; +$paramlogo='PAYMENT_LOGO_'.$suffix; if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo; -else if (! empty($conf->global->PAYBOX_LOGO)) $logosmall=$conf->global->PAYBOX_LOGO; +else if (! empty($conf->global->PAYMENT_LOGO)) $logosmall=$conf->global->PAYMENT_LOGO; //print ''."\n"; // Define urllogo $urllogo=''; @@ -338,17 +340,17 @@ if ($urllogo) // Output introduction text $text=''; -if (! empty($conf->global->PAYPAL_NEWFORM_TEXT)) +if (! empty($conf->global->PAYMENT_NEWFORM_TEXT)) { $langs->load("members"); - if (preg_match('/^\((.*)\)$/',$conf->global->PAYPAL_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."
    \n"; - else $text.=$conf->global->PAYPAL_NEWFORM_TEXT."
    \n"; + if (preg_match('/^\((.*)\)$/',$conf->global->PAYMENT_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."
    \n"; + else $text.=$conf->global->PAYMENT_NEWFORM_TEXT."
    \n"; $text=''."\n"; } if (empty($text)) { - $text.=''."\n"; - $text.=''."\n"; + $text.=''."\n"; + $text.=''."\n"; } print $text; @@ -1014,7 +1016,7 @@ print '
    '; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,1,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/paypal/paymentko.php b/htdocs/public/paypal/paymentko.php index f7dd0cf6eeb..3e555379849 100644 --- a/htdocs/public/paypal/paymentko.php +++ b/htdocs/public/paypal/paymentko.php @@ -91,7 +91,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice // Set by newpayment.php $paymentType = $_SESSION['PaymentType']; $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["Payment_Amount"]; + $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; // From env $ipaddress = $_SESSION['ipaddress']; @@ -104,7 +104,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice // Send an email $sendemail = ''; - if (! empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->PAYPAL_PAYONLINE_SENDEMAIL; + if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail=$conf->global->ONLINE_PAYMENT_SENDEMAIL; if ($sendemail) { @@ -153,7 +153,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice $head=''; -if (! empty($conf->global->PAYPAL_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -166,11 +166,13 @@ print ''."\n"; print '
    '."\n"; print $langs->trans("YourPaymentHasNotBeenRecorded")."

    "; -if (! empty($conf->global->PAYPAL_MESSAGE_KO)) print $conf->global->PAYPAL_MESSAGE_KO; +$key='ONLINE_PAYMENT_MESSAGE_KO'; +if (! empty($conf->global->$key)) print $conf->global->$key; + print "\n
    \n"; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,0,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/paypal/paymentok.php b/htdocs/public/paypal/paymentok.php index e52a79057f4..9ae2e90795e 100644 --- a/htdocs/public/paypal/paymentok.php +++ b/htdocs/public/paypal/paymentok.php @@ -114,7 +114,7 @@ dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_paypal'); $head=''; -if (! empty($conf->global->PAYPAL_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -135,7 +135,7 @@ if ($PAYPALTOKEN) // Set by newpayment.php $paymentType = $_SESSION['PaymentType']; $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["Payment_Amount"]; + $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; // From env $ipaddress = $_SESSION['ipaddress']; @@ -170,7 +170,9 @@ if ($PAYPALTOKEN) print $langs->trans("YourPaymentHasBeenRecorded")."
    \n"; print $langs->trans("ThisIsTransactionId",$TRANSACTIONID)."

    \n"; - if (! empty($conf->global->PAYPAL_MESSAGE_OK)) print $conf->global->PAYPAL_MESSAGE_OK; + + $key='ONLINE_PAYMENT_MESSAGE_OK'; + if (! empty($conf->global->$key)) print $conf->global->$key; // Appel des triggers include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; @@ -180,9 +182,9 @@ if ($PAYPALTOKEN) // Fin appel triggers // Send an email - if (! empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) + if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) { - $sendto=$conf->global->PAYPAL_PAYONLINE_SENDEMAIL; + $sendto=$conf->global->ONLINE_PAYMENT_SENDEMAIL; $from=$conf->global->MAILING_EMAIL_FROM; // Define $urlwithroot $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); @@ -201,7 +203,7 @@ if ($PAYPALTOKEN) else $appli.=" ".DOL_VERSION; } else $appli.=" ".DOL_VERSION; - + $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentReceived"); $tmptag=dolExplodeIntoArray($fulltag,'.','='); @@ -248,7 +250,7 @@ if ($PAYPALTOKEN) $result=$interface->run_triggers('PAYPAL_PAYMENT_KO',$object,$user,$langs,$conf); if ($result < 0) { $error++; $errors=$interface->errors; } // Fin appel triggers - + //Display a user friendly Error on the page using any of the following error information returned by PayPal $ErrorCode = urldecode($resArray["L_ERRORCODE0"]); $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]); @@ -264,9 +266,9 @@ if ($PAYPALTOKEN) if ($mysoc->email) echo "\nPlease, send a screenshot of this page to ".$mysoc->email."
    \n"; // Send an email - if (! empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) + if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) { - $sendto=$conf->global->PAYPAL_PAYONLINE_SENDEMAIL; + $sendto=$conf->global->ONLINE_PAYMENT_SENDEMAIL; $from=$conf->global->MAILING_EMAIL_FROM; // Define $urlwithroot $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); @@ -285,7 +287,7 @@ if ($PAYPALTOKEN) else $appli.=" ".DOL_VERSION; } else $appli.=" ".DOL_VERSION; - + $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("ValidationOfPaymentFailed"); $content=""; @@ -326,7 +328,7 @@ else print "\n\n"; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,0,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/stripe/newpayment.php b/htdocs/public/stripe/newpayment.php index f735cc87da8..35ccba4ef1c 100644 --- a/htdocs/public/stripe/newpayment.php +++ b/htdocs/public/stripe/newpayment.php @@ -16,6 +16,8 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . + * + * Page is called with payment parameters then called with action='dopayment', then called with action='charge' then redirect is done on urlok/jo */ /** @@ -184,9 +186,9 @@ if (! empty($conf->global->STRIPE_SECURITY_TOKEN)) // Common variables $creditor=$mysoc->name; -$paramcreditor='STRIPE_CREDITOR_'.$suffix; +$paramcreditor='ONLINE_PAYMENT_CREDITOR_'.$suffix; if (! empty($conf->global->$paramcreditor)) $creditor=$conf->global->$paramcreditor; -else if (! empty($conf->global->STRIPE_CREDITOR)) $creditor=$conf->global->STRIPE_CREDITOR; +else if (! empty($conf->global->ONLINE_PAYMENT_CREDITOR)) $creditor=$conf->global->ONLINE_PAYMENT_CREDITOR; @@ -216,25 +218,28 @@ if ($action == 'charge') $stripeToken = GETPOST("stripeToken",'alpha'); $email = GETPOST("stripeEmail",'alpha'); + $vatnumber = GETPOST('vatnumber','alpha'); dol_syslog("stripeToken = ".$stripeToken, LOG_DEBUG, 0, '_stripe'); - dol_syslog("stripeEmail = ".$stripeEmail, LOG_DEBUG, 0, '_stripe'); + dol_syslog("email = ".$email, LOG_DEBUG, 0, '_stripe'); + dol_syslog("vatnumber = ".$vatnumber, LOG_DEBUG, 0, '_stripe'); $error = 0; try { - dol_syslog("Create customer", LOG_DEBUG, 0, '_stripe'); + dol_syslog("Create customer card profile", LOG_DEBUG, 0, '_stripe'); $customer = \Stripe\Customer::create(array( 'email' => $email, - 'description' => ($email?'Customer for '.$email:null), + 'description' => ($email?'Customer card profile for '.$email:null), 'metadata' => array('ipaddress'=>$_SERVER['REMOTE_ADDR']), - 'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?) + 'business_vat_id' => ($vatnumber?$vatnumber:null), + 'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?) )); // TODO Add 'business_vat_id' ? dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe'); $charge = \Stripe\Charge::create(array( - 'customer' => $customer->id, + 'customer' => $customer->id, // Will reuse default source of this customer card profile 'amount' => price2num($amount, 'MU'), 'currency' => $currency, 'description' => 'Stripe payment: '.$FULLTAG, @@ -298,7 +303,7 @@ if ($action == 'charge') } $_SESSION["onlinetoken"] = $stripeToken; - $_SESSION["Payment_Amount"] = $amount; + $_SESSION["FinalPaymentAmt"] = $amount; $_SESSION["currencyCodeType"] = $currency; $_SESSION["paymentType"] = ''; $_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR']; // Payer ip @@ -329,7 +334,7 @@ if ($action == 'charge') */ $head=''; -if (! empty($conf->global->STRIPE_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -346,7 +351,7 @@ if (! empty($SOURCE) && in_array($ref, array('member_ref', 'contractline_ref', ' exit; } -if (empty($conf->global->STRIPE_LIVE)) +if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha')) { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode'),'','warning'); } @@ -360,6 +365,7 @@ print ''."\n" print ''."\n"; print ''."\n"; print ''; +print ''; print "\n"; print ''."\n"; print ''."\n"; @@ -370,14 +376,14 @@ print "\n"; print '

    '.$text.'

    '.$langs->trans("WelcomeOnPaymentPage").'

    '.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'


    '.$langs->trans("WelcomeOnPaymentPage").'
    '.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'

    '."\n"; -// Show logo (search order: logo defined by PAYBOX_LOGO_suffix, then PAYBOX_LOGO, then small company logo, large company logo, theme logo, common logo) +// Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo) $width=0; // Define logo and logosmall $logosmall=$mysoc->logo_small; $logo=$mysoc->logo; -$paramlogo='STRIPE_LOGO_'.$suffix; +$paramlogo='PAYMENT_LOGO_'.$suffix; if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo; -else if (! empty($conf->global->STRIPE_LOGO)) $logosmall=$conf->global->STRIPE_LOGO; +else if (! empty($conf->global->PAYMENT_LOGO)) $logosmall=$conf->global->PAYMENT_LOGO; //print ''."\n"; // Define urllogo $urllogo=''; @@ -402,17 +408,17 @@ if ($urllogo) // Output introduction text $text=''; -if (! empty($conf->global->STRIPE_NEWFORM_TEXT)) +if (! empty($conf->global->PAYMENT_NEWFORM_TEXT)) { $langs->load("members"); - if (preg_match('/^\((.*)\)$/',$conf->global->STRIPE_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."
    \n"; - else $text.=$conf->global->STRIPE_NEWFORM_TEXT."
    \n"; + if (preg_match('/^\((.*)\)$/',$conf->global->PAYMENT_NEWFORM_TEXT,$reg)) $text.=$langs->trans($reg[1])."
    \n"; + else $text.=$conf->global->PAYMENT_NEWFORM_TEXT."
    \n"; $text=''."\n"; } if (empty($text)) { - $text.=''."\n"; - $text.=''."\n"; + $text.=''."\n"; + $text.=''."\n"; } print $text; @@ -576,6 +582,7 @@ if (GETPOST("source") == 'order') print ''."\n"; } print ''."\n"; + print ''."\n"; print 'ref.'">'."\n"; } @@ -686,6 +693,7 @@ if (GETPOST("source") == 'invoice') print ''."\n"; } print ''."\n"; + print ''."\n"; print 'ref.'">'."\n"; } @@ -885,6 +893,7 @@ if (GETPOST("source") == 'contractline') print ''."\n"; } print ''."\n"; + print ''."\n"; print 'ref.'">'."\n"; } @@ -1118,6 +1127,7 @@ if (preg_match('/^dopayment/',$action)) print ''; print ''."\n"; print ''."\n"; + print ''; print '

    '.$text.'

    '.$langs->trans("WelcomeOnPaymentPage").'

    '.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'


    '.$langs->trans("WelcomeOnPaymentPage").'
    '.$langs->trans("ThisScreenAllowsYouToPay",$creditor).'

    @@ -1229,7 +1239,7 @@ if (preg_match('/^dopayment/',$action)) -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,1,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/stripe/paymentko.php b/htdocs/public/stripe/paymentko.php index 01000939b37..a2462904b07 100644 --- a/htdocs/public/stripe/paymentko.php +++ b/htdocs/public/stripe/paymentko.php @@ -82,24 +82,24 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice $paymentType = $_SESSION['paymentType']; $FinalPaymentAmt = $_SESSION['FinalPaymentAmt']; $ipaddress = $_SESSION['ipaddress']; - + // Appel des triggers include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; $interface=new Interfaces($db); $result=$interface->run_triggers('STRIPE_PAYMENT_KO',$object,$user,$langs,$conf); if ($result < 0) { $error++; $errors=$interface->errors; } // Fin appel triggers - + // Send an email $sendemail = ''; - if (! empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->PAYPAL_PAYONLINE_SENDEMAIL; - + if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail=$conf->global->ONLINE_PAYMENT_SENDEMAIL; + if ($sendemail) { // Get on url call $sendto=$sendemail; $from=$conf->global->MAILING_EMAIL_FROM; - + // Define link to login card $appli=constant('DOL_APPLICATION_TITLE'); if (! empty($conf->global->MAIN_APPLICATION_TITLE)) @@ -112,7 +112,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice else $appli.=" ".DOL_VERSION; } else $appli.=" ".DOL_VERSION; - + $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentFailed"); $content=""; @@ -124,7 +124,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice $content.="tag=".$fulltag."\ntoken=".$onlinetoken." paymentType=".$paymentType." currencycodeType=".$currencyCodeType." payerId=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt; require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $mailfile = new CMailFile($topic, $sendto, $from, $content); - + $result=$mailfile->sendfile(); if ($result) { @@ -140,7 +140,7 @@ if (! empty($_SESSION['ipaddress'])) // To avoid to make action twice } $head=''; -if (! empty($conf->global->STRIPE_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -153,11 +153,13 @@ print ''."\n"; print '
    '."\n"; print $langs->trans("YourPaymentHasNotBeenRecorded")."

    "; -if (! empty($conf->global->STRIPE_MESSAGE_KO)) print $conf->global->STRIPE_MESSAGE_KO; +$key='ONLINE_PAYMENT_MESSAGE_KO'; +if (! empty($conf->global->$key)) print $conf->global->$key; + print "\n
    \n"; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,0,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/stripe/paymentok.php b/htdocs/public/stripe/paymentok.php index 4eede2e9544..f018bc98b7a 100644 --- a/htdocs/public/stripe/paymentok.php +++ b/htdocs/public/stripe/paymentok.php @@ -82,7 +82,7 @@ foreach($_POST as $k => $v) $tracepost .= "{$k} - {$v}\n"; dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_stripe'); $head=''; -if (! empty($conf->global->STRIPE_CSS_URL)) $head=''."\n"; +if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; $conf->dol_hide_topmenu=1; $conf->dol_hide_leftmenu=1; @@ -105,7 +105,7 @@ if ($ispaymentok) // Set by newpayment.php $paymentType = $_SESSION['PaymentType']; $currencyCodeType = $_SESSION['currencyCodeType']; - $FinalPaymentAmt = $_SESSION["Payment_Amount"]; + $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"]; // From env $ipaddress = $_SESSION['ipaddress']; $TRANSACTIONID = $_SESSION['TRANSACTIONID']; @@ -117,14 +117,16 @@ if ($ispaymentok) if ($result < 0) { $error++; $errors=$interface->errors; } // Fin appel triggers - + print $langs->trans("YourPaymentHasBeenRecorded")."
    \n"; print $langs->trans("ThisIsTransactionId",$TRANSACTIONID)."

    \n"; - if (! empty($conf->global->STRIPE_MESSAGE_OK)) print $conf->global->STRIPE_MESSAGE_OK; - + + $key='ONLINE_PAYMENT_MESSAGE_OK'; + if (! empty($conf->global->$key)) print $conf->global->$key; + $sendemail = ''; - if (! empty($conf->global->STRIPE_PAYONLINE_SENDEMAIL)) $sendemail=$conf->global->STRIPE_PAYONLINE_SENDEMAIL; - + if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) $sendemail=$conf->global->ONLINE_PAYMENT_SENDEMAIL; + // Send an email if ($sendemail) { @@ -147,7 +149,7 @@ if ($ispaymentok) else $appli.=" ".DOL_VERSION; } else $appli.=" ".DOL_VERSION; - + $urlback=$_SERVER["REQUEST_URI"]; $topic='['.$appli.'] '.$langs->transnoentitiesnoconv("NewOnlinePaymentReceived"); $tmptag=dolExplodeIntoArray($fulltag,'.','='); @@ -191,7 +193,7 @@ if ($ispaymentok) print "\n\n"; -htmlPrintOnlinePaymentFooter($mysoc,$langs); +htmlPrintOnlinePaymentFooter($mysoc,$langs,0,$suffix); llxFooter('', 'public'); diff --git a/htdocs/public/websites/index.php b/htdocs/public/website/index.php similarity index 78% rename from htdocs/public/websites/index.php rename to htdocs/public/website/index.php index 991ca11b683..0772965c5e6 100644 --- a/htdocs/public/websites/index.php +++ b/htdocs/public/website/index.php @@ -16,7 +16,7 @@ */ /** - * \file htdocs/public/websites/index.php + * \file htdocs/public/website/index.php * \ingroup website * \brief Page to output pages * \author Laurent Destailleur @@ -49,6 +49,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $error=0; $websitekey=GETPOST('website', 'alpha'); $pageid=GETPOST('page', 'alpha')?GETPOST('page', 'alpha'):GETPOST('pageid', 'alpha'); +$pageref=GETPOST('pageref', 'aZ09')?GETPOST('pageref', 'aZ09'):''; $accessallowed = 1; $type=''; @@ -65,12 +66,13 @@ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_AP if (empty($pageid)) { - require_once DOL_DOCUMENT_ROOT.'/websites/class/website.class.php'; - require_once DOL_DOCUMENT_ROOT.'/websites/class/websitepage.class.php'; + require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; + require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; $object=new Website($db); $object->fetch(0, $websitekey); - if (empty($object->id)) + + if (empty($object->id)) { if (empty($pageid)) { @@ -84,23 +86,34 @@ if (empty($pageid)) $objectpage=new WebsitePage($db); - if ($object->fk_default_home > 0) + if ($pageref) { - $result=$objectpage->fetch($object->fk_default_home); + $result=$objectpage->fetch(0, $object->id, $pageref); if ($result > 0) - { - $pageid = $objectpage->id; - } + { + $pageid = $objectpage->id; + } } - - if (empty($pageid)) + else { - $array=$objectpage->fetchAll($object->id); - if (is_array($array) && count($array) > 0) - { - $firstrep=reset($array); - $pageid=$firstrep->id; - } + if ($object->fk_default_home > 0) + { + $result=$objectpage->fetch($object->fk_default_home); + if ($result > 0) + { + $pageid = $objectpage->id; + } + } + + if (empty($pageid)) + { + $array=$objectpage->fetchAll($object->id); + if (is_array($array) && count($array) > 0) + { + $firstrep=reset($array); + $pageid=$firstrep->id; + } + } } } if (empty($pageid)) @@ -125,11 +138,11 @@ if ($pageid == 'css') // No more used ? //if (empty($dolibarr_nocache)) header('Cache-Control: max-age=3600, public, must-revalidate'); //else header('Cache-Control: no-cache'); - $original_file=$dolibarr_main_data_root.'/websites/'.$websitekey.'/styles.css.php'; + $original_file=$dolibarr_main_data_root.'/website/'.$websitekey.'/styles.css.php'; } else { - $original_file=$dolibarr_main_data_root.'/websites/'.$websitekey.'/page'.$pageid.'.tpl.php'; + $original_file=$dolibarr_main_data_root.'/website/'.$websitekey.'/page'.$pageid.'.tpl.php'; } // Find the subdirectory name as the reference @@ -177,7 +190,7 @@ if (! file_exists($original_file_osencoded)) // Output page content define('USEDOLIBARRSERVER', 1); -print ''."\n"; +print ''."\n"; include_once $original_file_osencoded; diff --git a/htdocs/public/websites/styles.css.php b/htdocs/public/website/styles.css.php similarity index 90% rename from htdocs/public/websites/styles.css.php rename to htdocs/public/website/styles.css.php index 14014577cea..694eaaf344f 100644 --- a/htdocs/public/websites/styles.css.php +++ b/htdocs/public/website/styles.css.php @@ -16,7 +16,7 @@ */ /** - * \file htdocs/public/websites/styles.css.php + * \file htdocs/public/website/styles.css.php * \ingroup website * \brief Page to output style page. Called with */ @@ -65,8 +65,8 @@ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_AP if (empty($pageid)) { - require_once DOL_DOCUMENT_ROOT.'/websites/class/website.class.php'; - require_once DOL_DOCUMENT_ROOT.'/websites/class/websitepage.class.php'; + require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; + require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; $object=new Website($db); if ($websiteid) @@ -97,7 +97,7 @@ if (empty($pageid)) // Security: Delete string ../ into $original_file global $dolibarr_main_data_root; -$original_file=$dolibarr_main_data_root.'/websites/'.$website.'/styles.css.php'; +$original_file=$dolibarr_main_data_root.'/website/'.$website.'/styles.css.php'; // Find the subdirectory name as the reference $refname=basename(dirname($original_file)."/"); @@ -139,6 +139,8 @@ if (! file_exists($original_file_osencoded)) // Output page content +define('USEDOLIBARRSERVER', 1); +print '/* Page content '.$original_file.' : CSS content that was saved into tpl dir */'."\n"; require_once $original_file_osencoded; diff --git a/htdocs/resource/card.php b/htdocs/resource/card.php index db6eed63b3b..211631e3dd5 100644 --- a/htdocs/resource/card.php +++ b/htdocs/resource/card.php @@ -43,7 +43,7 @@ $langs->load("main"); // Get parameters $id = GETPOST('id','int'); $action = GETPOST('action','alpha'); -$ref = GETPOST('ref'); +$ref = GETPOST('ref','alpha'); $description = GETPOST('description'); $confirm = GETPOST('confirm'); $fk_code_type_resource = GETPOST('fk_code_type_resource','alpha'); @@ -58,8 +58,8 @@ if (! $user->rights->resource->read) accessforbidden(); $object = new Dolresource($db); -$objectFetchRes = $object->fetch($id); -if (! ($objectFetchRes > 0)) dol_print_error($db, $object->error); +$result = $object->fetch($id, $ref); +if (! ($result > 0)) dol_print_error($db, $object->error); $extrafields = new ExtraFields($db); @@ -68,7 +68,7 @@ $extrafields = new ExtraFields($db); $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); $hookmanager->initHooks(array('resource_card','globalcard')); -$parameters=array('resource_id'=>$id); +$parameters=array('resource_id'=>$object->id); $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'); @@ -159,17 +159,17 @@ if (empty($reshook)) * * Put here all code to build page ****************************************************/ + $pagetitle = $langs->trans('ResourceCard'); llxHeader('',$pagetitle,''); $form = new Form($db); $formresource = new FormResource($db); -if ( $objectFetchRes > 0 ) +if ($object->id > 0) { $head=resource_prepare_head($object); - if ($action == 'edit' ) { if ( ! $user->rights->resource->write ) @@ -189,7 +189,7 @@ if ( $objectFetchRes > 0 ) // Ref print ''; - print ''; + print ''; // Type print ''; @@ -200,7 +200,7 @@ if ( $objectFetchRes > 0 ) // Description print ''; print ''; // Other attributes @@ -232,7 +232,7 @@ if ( $objectFetchRes > 0 ) // Confirm deleting resource line if ($action == 'delete') { - $formconfirm = $form->formconfirm("card.php?&id=".$id,$langs->trans("DeleteResource"),$langs->trans("ConfirmDeleteResource"),"confirm_delete_resource",'','',1); + $formconfirm = $form->formconfirm("card.php?&id=".$object->id,$langs->trans("DeleteResource"),$langs->trans("ConfirmDeleteResource"),"confirm_delete_resource",'','',1); } // Print form confirm @@ -246,7 +246,7 @@ if ( $objectFetchRes > 0 ) $morehtmlref.=''; - dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); print '
    '; @@ -302,7 +302,7 @@ if ( $objectFetchRes > 0 ) if($user->rights->resource->write) { print ''; } } @@ -312,7 +312,7 @@ if ( $objectFetchRes > 0 ) if($user->rights->resource->delete) { print ''; } } diff --git a/htdocs/resource/class/dolresource.class.php b/htdocs/resource/class/dolresource.class.php index 10485dda4be..10c7c2f9f85 100644 --- a/htdocs/resource/class/dolresource.class.php +++ b/htdocs/resource/class/dolresource.class.php @@ -33,7 +33,7 @@ class Dolresource extends CommonObject 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; @@ -169,10 +169,11 @@ class Dolresource extends CommonObject /** * Load object in memory from database * - * @param int $id id object - * @return int <0 if KO, >0 if OK + * @param int $id Id of object + * @param string $ref Ref of object + * @return int <0 if KO, >0 if OK */ - function fetch($id) + function fetch($id, $ref='') { global $langs; $sql = "SELECT"; @@ -187,7 +188,8 @@ class Dolresource extends CommonObject $sql.= " ty.label as type_label"; $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource"; - $sql.= " WHERE t.rowid = ".$this->db->escape($id); + if ($id) $sql.= " WHERE t.rowid = ".$this->db->escape($id); + else $sql.= " WHERE t.ref = '".$this->db->escape($ref)."'"; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -751,75 +753,6 @@ class Dolresource extends CommonObject return 0; } - /** - * Load properties id_previous and id_next - * - * @param string $filter Optional filter - * @param int $fieldid Name of field to use for the select MAX and MIN - * @param int $nodbprefix Do not include DB prefix to forge table name - * @return int <0 if KO, >0 if OK - */ - function load_previous_next_ref($filter, $fieldid, $nodbprefix =0) - { - global $conf, $user; - - if (! $this->table_element) - { - dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined"); - return -1; - } - - // this->ismultientitymanaged contains - // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - $alias = 's'; - - - $sql = "SELECT MAX(te.".$fieldid.")"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && empty($user->rights->societe->client->voir))) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; - $sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->id)."'"; - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; - if (! empty($filter)) $sql.=" AND ".$filter; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; - - //print $sql."
    "; - $result = $this->db->query($sql); - if (! $result) - { - $this->error=$this->db->error(); - return -1; - } - $row = $this->db->fetch_row($result); - $this->ref_previous = $row[0]; - - - $sql = "SELECT MIN(te.".$fieldid.")"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; - $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->id)."'"; - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; - if (! empty($filter)) $sql.=" AND ".$filter; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; - // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null - - //print $sql."
    "; - $result = $this->db->query($sql); - if (! $result) - { - $this->error=$this->db->error(); - return -2; - } - $row = $this->db->fetch_row($result); - $this->ref_next = $row[0]; - - return 1; - } - - /** * Update element resource into database * @@ -843,7 +776,7 @@ class Dolresource extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."element_resources SET"; $sql.= " resource_id=".(isset($this->resource_id)?"'".$this->db->escape($this->resource_id)."'":"null").","; - $sql.= " resource_type=".(isset($this->resource_type)?"'".$this->resource_type."'":"null").","; + $sql.= " resource_type=".(isset($this->resource_type)?"'".$this->db->escape($this->resource_type)."'":"null").","; $sql.= " element_id=".(isset($this->element_id)?$this->element_id:"null").","; $sql.= " element_type=".(isset($this->element_type)?"'".$this->db->escape($this->element_type)."'":"null").","; $sql.= " busy=".(isset($this->busy)?$this->busy:"null").","; @@ -1019,8 +952,8 @@ class Dolresource extends CommonObject $result.=$link.$this->ref.$linkend; return $result; } - - + + /** * Retourne le libelle du status d'un user (actif, inactif) * @@ -1031,7 +964,7 @@ class Dolresource extends CommonObject { return $this->LibStatut($this->status,$mode); } - + /** * Return the status * @@ -1042,7 +975,7 @@ class Dolresource extends CommonObject static function LibStatut($status,$mode=0) { global $langs; - + return ''; - } + } } diff --git a/htdocs/resource/contact.php b/htdocs/resource/contact.php index 007ecd8025d..543e69b83ef 100644 --- a/htdocs/resource/contact.php +++ b/htdocs/resource/contact.php @@ -36,7 +36,7 @@ $langs->load("sendings"); $langs->load("companies"); $id = GETPOST('id','int'); -$ref = GETPOST('ref', 'alpha'); +$ref = GETPOST('ref','alpha'); $action = GETPOST('action','alpha'); // Security check @@ -123,19 +123,19 @@ if ($id > 0 || ! empty($ref)) $linkback = '' . $langs->trans("BackToList") . ''; - - + + $morehtmlref='
    '; $morehtmlref.='
    '; - - - dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); - - + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; print '
    '; - - + + // Object print '
    '.$langs->trans("ResourceFormLabel_ref").'
    '.$langs->trans("ResourceType").'
    '.$langs->trans("Description").''; - print ''; + print ''; print '
    '; @@ -152,7 +152,7 @@ if ($id > 0 || ! empty($ref)) 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 f3c48f754ec..64ac151fede 100644 --- a/htdocs/resource/document.php +++ b/htdocs/resource/document.php @@ -40,7 +40,7 @@ $langs->load("resource"); $langs->load("companies"); $id = GETPOST('id','int'); -$ref = GETPOST('ref', 'alpha'); +$ref = GETPOST('ref','alpha'); $action = GETPOST('action','alpha'); $confirm = GETPOST('confirm','alpha'); @@ -100,20 +100,20 @@ if ($object->id) $totalsize+=$file['size']; } - + $linkback = '' . $langs->trans("BackToList") . ''; - - + + $morehtmlref='
    '; $morehtmlref.='
    '; - - - dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); - - + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; print '
    '; - + print '
    '; // Resource type @@ -131,10 +131,10 @@ if ($object->id) print ''; dol_fiche_end(); - + $modulepart = 'dolresource'; $permission = $user->rights->resource->write; - $param = '&id=' . $object->id; + include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } diff --git a/htdocs/resource/element_resource.php b/htdocs/resource/element_resource.php index a886dcf475b..e10fc07a6ef 100644 --- a/htdocs/resource/element_resource.php +++ b/htdocs/resource/element_resource.php @@ -108,7 +108,7 @@ if ($action == 'add_element_resource' && ! $cancel) } // Update ressource -if ($action == 'update_linked_resource' && $user->rights->resource->write && !GETPOST('cancel') ) +if ($action == 'update_linked_resource' && $user->rights->resource->write && !GETPOST('cancel','alpha') ) { $res = $object->fetch_element_resource($lineid); if($res) @@ -205,14 +205,13 @@ else // Link to other agenda views $out=''; - $out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewPerUser").''; - $out.='
    '; - $out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewCal").''; - $out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewWeek").''; - $out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); + $out.='
  • '.img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewDay").''; $linkback.=$out; @@ -238,13 +237,13 @@ else } } $morehtmlref.=''; - + dol_banner_tab($act, 'element_id', $linkback, ($user->societe_id?0:1), 'id', 'ref', $morehtmlref, '&element='.$element, 0, '', ''); print '
    '; - + print '
    '; - + print '
  • '; // Type @@ -315,7 +314,7 @@ else print '
    '; print ''; - + dol_fiche_end(); } } @@ -364,16 +363,16 @@ else $fichinter = new Fichinter($db); $fichinter->fetch($element_id, $element_ref); $fichinter->fetch_thirdparty(); - - if (is_object($fichinter)) + + if (is_object($fichinter)) { $head=fichinter_prepare_head($fichinter); dol_fiche_head($head, 'resource', $langs->trans("InterventionCard"), -1, 'intervention'); // Intervention card $linkback = ''.$langs->trans("BackToList").''; - - + + $morehtmlref='
    '; // Ref customer //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -414,9 +413,9 @@ else } } $morehtmlref.='
    '; - + dol_banner_tab($fichinter, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '&element='.$element, 0, '', '', 1); - + dol_fiche_end(); } } @@ -440,7 +439,7 @@ else { $element_prop = getElementProperties($resource_obj); - //print '/'.$modresources.'/class/'.$resource_obj.'.class.php
    '; + //print '/'.$modresources.'/class/'.$resource_obj.'.class.php
    '; $path = ''; if(strpos($resource_obj,'@')) diff --git a/htdocs/resource/note.php b/htdocs/resource/note.php index 20d96591c7b..5fe1751d1f4 100644 --- a/htdocs/resource/note.php +++ b/htdocs/resource/note.php @@ -33,7 +33,7 @@ $langs->load('companies'); $langs->load("interventions"); $id = GETPOST('id','int'); -$ref = GETPOST('ref', 'alpha'); +$ref = GETPOST('ref','alpha'); $action=GETPOST('action','alpha'); // Security check @@ -67,18 +67,18 @@ if ($id > 0 || ! empty($ref)) 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); - - + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; print '
    '; - + print ''; // Resource type @@ -88,11 +88,11 @@ if ($id > 0 || ! empty($ref)) print $object->type_label; print ''; print ''; - + print "
    "; print '
    '; - + $permission=$user->rights->resource->write; $cssclass='titlefield'; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; diff --git a/htdocs/societe/admin/contact_extrafields.php b/htdocs/societe/admin/contact_extrafields.php index 2a60252f7f8..f97ceedcca3 100644 --- a/htdocs/societe/admin/contact_extrafields.php +++ b/htdocs/societe/admin/contact_extrafields.php @@ -37,7 +37,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/societe/admin/societe.php b/htdocs/societe/admin/societe.php index 89ef7d0323d..ed4704471d0 100644 --- a/htdocs/societe/admin/societe.php +++ b/htdocs/societe/admin/societe.php @@ -167,23 +167,6 @@ if ($action == 'setdoc') } } -//Activate ProfId -if ($action == 'setprofid') -{ - $status = GETPOST('status','alpha'); - - $idprof="SOCIETE_IDPROF".$value."_UNIQUE"; - if (dolibarr_set_const($db, $idprof,$status,'chaine',0,'',$conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } - else - { - dol_print_error($db); - } -} - //Activate Set ref in list if ($action=="setaddrefinlist") { $setaddrefinlist = GETPOST('value','int'); @@ -214,16 +197,33 @@ if ($action=="setaskforshippingmet") { } } +//Activate ProfId unique +if ($action == 'setprofid') +{ + $status = GETPOST('status','alpha'); + + $idprof="SOCIETE_".$value."_UNIQUE"; + if (dolibarr_set_const($db, $idprof, $status, 'chaine', 0, '', $conf->entity) > 0) + { + //header("Location: ".$_SERVER["PHP_SELF"]); + //exit; + } + else + { + dol_print_error($db); + } +} + //Activate ProfId mandatory if ($action == 'setprofidmandatory') { $status = GETPOST('status','alpha'); - $idprof="SOCIETE_IDPROF".$value."_MANDATORY"; - if (dolibarr_set_const($db, $idprof,$status,'chaine',0,'',$conf->entity) > 0) + $idprof="SOCIETE_".$value."_MANDATORY"; + if (dolibarr_set_const($db, $idprof, $status, 'chaine', 0, '', $conf->entity) > 0) { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; + //header("Location: ".$_SERVER["PHP_SELF"]); + //exit; } else { @@ -236,11 +236,11 @@ if ($action == 'setprofidinvoicemandatory') { $status = GETPOST('status','alpha'); - $idprof="SOCIETE_IDPROF".$value."_INVOICE_MANDATORY"; - if (dolibarr_set_const($db, $idprof,$status,'chaine',0,'',$conf->entity) > 0) + $idprof="SOCIETE_".$value."_INVOICE_MANDATORY"; + if (dolibarr_set_const($db, $idprof, $status, 'chaine', 0, '', $conf->entity) > 0) { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; + //header("Location: ".$_SERVER["PHP_SELF"]); + //exit; } else { @@ -298,7 +298,6 @@ print '
    '.$langs->trans("Status").''.$langs->trans("ShortInfo").'
    '.$modCodeTiers->name.''.$modCodeTiers->info($langs).''.$langs->trans("Status").''.$langs->trans("ShortInfo").'
    '.$modCodeCompta->name."\n"; @@ -474,7 +470,6 @@ print ''.$langs->trans("ShortInfo").''.$langs->trans("Preview").'
    '; print $module->name; print "\n"; @@ -597,76 +591,74 @@ print ''.$langs->trans("MustBeMandatory").''.$langs->trans("MustBeInvoiceMandatory").'
    '.$profid[$i][0]."\n"; - print $profid[$i][1]; + print ''.$profid[$key][0]."\n"; + print $profid[$key][1]; print ''; + print ''; print img_picto($langs->trans("Activated"),'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"),'switch_off'); print ''; + print ''; print img_picto($langs->trans("Activated"),'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"),'switch_off'); print ''; + print ''; print img_picto($langs->trans("Activated"),'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"),'switch_off'); print '
    trans('EMail').($conf->global->SOCIETE_MAIL_REQUIRED?'*':''); ?>trans('EMail').($conf->global->SOCIETE_EMAIL_MANDATORY?'*':''); ?> trans('Web'); ?>
    trans('EMail').($conf->global->SOCIETE_MAIL_REQUIRED?'*':''); ?>trans('EMail').($conf->global->SOCIETE_EMAIL_MANDATORY?'*':''); ?> trans('Web'); ?>
    trans('EMail').($conf->global->SOCIETE_MAIL_REQUIRED?'*':''); ?>trans('EMail').($conf->global->SOCIETE_EMAIL_MANDATORY?'*':''); ?> trans('Web'); ?>
    trans('EMail').($conf->global->SOCIETE_MAIL_REQUIRED?'*':''); ?>trans('EMail').($conf->global->SOCIETE_EMAIL_MANDATORY?'*':''); ?> trans('Web'); ?>
    '.fieldLabel('ProspectCustomer','customerprospect',1).''; - $selected=isset($_POST['client'])?GETPOST('client'):$object->client; + $selected=GETPOST('client','int')!=''?GETPOST('client','int'):$object->client; print ''.fieldLabel('Supplier','fournisseur',1).''; $default = -1; if (! empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)) $default=1; - print $form->selectyesno("fournisseur", (isset($_POST['fournisseur'])?GETPOST('fournisseur'):(GETPOST("type") == '' ? $default : $object->fournisseur)), 1, 0, (GETPOST("type") == '' ? 1 : 0)); + print $form->selectyesno("fournisseur", (GETPOST('fournisseur','int')!=''?GETPOST('fournisseur','int'):(GETPOST("type",'alpha') == '' ? $default : $object->fournisseur)), 1, 0, (GETPOST("type",'alpha') == '' ? 1 : 0)); print ''.fieldLabel('SupplierCode','supplier_code').''; print ''; + print ''; print ''; print ''; print ''; @@ -1385,11 +1365,12 @@ else * Edition */ + //print load_fiche_titre($langs->trans("EditCompany")); if ($socid) { - $res=$object->fetch_optionals($object->id,$extralabels); + $res=$object->fetch_optionals($object->id,$extralabels); //if ($res < 0) { dol_print_error($db); exit; } $head = societe_prepare_head($object); @@ -1432,7 +1413,7 @@ else $object->oldcopy = clone $object; - if (GETPOST('name')) + if (GETPOSTISSET('name')) { // We overwrite with values if posted $object->name = GETPOST('name', 'alpha'); @@ -1495,8 +1476,6 @@ else } } - dol_htmloutput_errors($error,$errors); - if($object->localtax1_assuj==0){ $sub=0; }else{$sub=1;} @@ -1504,7 +1483,6 @@ else $sub2=0; }else{$sub2=1;} - print "\n".''; } diff --git a/htdocs/stripe/config.php b/htdocs/stripe/config.php index 9aaed7cf0b9..9f5f0e4de96 100644 --- a/htdocs/stripe/config.php +++ b/htdocs/stripe/config.php @@ -33,19 +33,19 @@ global $conf; //use \includes\stripe as stripe; $stripe = array(); -if (empty($conf->global->STRIPE_LIVE)) +if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox','alpha')) { $stripe = array( "secret_key" => $conf->global->STRIPE_TEST_SECRET_KEY, "publishable_key" => $conf->global->STRIPE_TEST_PUBLISHABLE_KEY ); } -else +else { $stripe = array( "secret_key" => $conf->global->STRIPE_LIVE_SECRET_KEY, "publishable_key" => $conf->global->STRIPE_LIVE_PUBLISHABLE_KEY - ); + ); } require_once DOL_DOCUMENT_ROOT."/includes/stripe/lib/Stripe.php"; diff --git a/htdocs/supplier_proposal/admin/supplier_proposal_extrafields.php b/htdocs/supplier_proposal/admin/supplier_proposal_extrafields.php index 8d6d437f466..0e84519e406 100644 --- a/htdocs/supplier_proposal/admin/supplier_proposal_extrafields.php +++ b/htdocs/supplier_proposal/admin/supplier_proposal_extrafields.php @@ -32,7 +32,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); @@ -90,7 +90,7 @@ print "\n"; $var=True; foreach($extrafields->attribute_type as $key => $value) { - + print ''; print "\n"; print "\n"; diff --git a/htdocs/supplier_proposal/admin/supplier_proposaldet_extrafields.php b/htdocs/supplier_proposal/admin/supplier_proposaldet_extrafields.php index 2b0a22c51fa..c8d6cf4cae1 100644 --- a/htdocs/supplier_proposal/admin/supplier_proposaldet_extrafields.php +++ b/htdocs/supplier_proposal/admin/supplier_proposaldet_extrafields.php @@ -39,7 +39,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); @@ -94,7 +94,7 @@ print "\n"; $var=True; foreach($extrafields->attribute_type as $key => $value) { - + print ''; print "\n"; print "\n"; diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index c39f7e1e0ea..75ea0cd12ed 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -115,7 +115,15 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if ($cancel) $action=''; + if ($cancel) + { + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + $action=''; + } include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once @@ -186,8 +194,8 @@ if (empty($reshook)) // Validation else if ($action == 'confirm_validate' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->validate_advance))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->validate_advance))) ) { $result = $object->valid($user); @@ -250,7 +258,7 @@ if (empty($reshook)) if ($object->fetch(GETPOST('copie_supplier_proposal')) > 0) { $object->ref = GETPOST('ref'); $object->date_livraison = $date_delivery; - $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); @@ -260,7 +268,7 @@ if (empty($reshook)) $object->fk_project = GETPOST('projectid'); $object->modelpdf = GETPOST('model'); $object->author = $user->id; // deprecated - $object->note = GETPOST('note'); + $object->note = GETPOST('note','none'); $object->statut = SupplierProposal::STATUS_DRAFT; $id = $object->create_from($user); @@ -271,14 +279,14 @@ if (empty($reshook)) $object->ref = GETPOST('ref'); $object->date_livraison = $date_delivery; $object->demand_reason_id = GETPOST('demand_reason_id'); - $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); $object->fk_project = GETPOST('projectid'); $object->modelpdf = GETPOST('model'); $object->author = $user->id; // deprecated - $object->note = GETPOST('note'); + $object->note = GETPOST('note','none'); $object->origin = GETPOST('origin'); $object->origin_id = GETPOST('originid'); @@ -373,7 +381,7 @@ if (empty($reshook)) // Hooks $parameters = array('objFrom' => $srcobject); $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if ($reshook < 0) $error ++; } else { @@ -396,23 +404,23 @@ if (empty($reshook)) { $db->commit(); - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } + $ret = $object->fetch($id); // Reload to get new records + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); exit(); @@ -434,7 +442,7 @@ if (empty($reshook)) } // Reopen proposal - else if ($action == 'confirm_reopen' && $user->rights->supplier_proposal->cloturer && ! GETPOST('cancel')) { + else if ($action == 'confirm_reopen' && $user->rights->supplier_proposal->cloturer && ! GETPOST('cancel','alpha')) { // prevent browser refresh from reopening proposal several times if ($object->statut == SupplierProposal::STATUS_SIGNED || $object->statut == SupplierProposal::STATUS_NOTSIGNED || $object->statut == SupplierProposal::STATUS_CLOSE) { $object->reopen($user, SupplierProposal::STATUS_VALIDATED); @@ -442,36 +450,39 @@ if (empty($reshook)) } // Close proposal - else if ($action == 'close' && $user->rights->supplier_proposal->cloturer && ! GETPOST('cancel')) { - // prevent browser refresh from reopening proposal several times - if ($object->statut == SupplierProposal::STATUS_SIGNED) { + else if ($action == 'close' && $user->rights->supplier_proposal->cloturer && ! GETPOST('cancel','alpha')) { + // prevent browser refresh from reopening proposal several times + if ($object->statut == SupplierProposal::STATUS_SIGNED) { $object->setStatut(SupplierProposal::STATUS_CLOSE); } } // Set accepted/refused - else if ($action == 'setstatut' && $user->rights->supplier_proposal->cloturer && ! GETPOST('cancel')) { + else if ($action == 'setstatut' && $user->rights->supplier_proposal->cloturer && ! GETPOST('cancel','alpha')) { if (! GETPOST('statut')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("CloseAs")), null, 'errors'); $action = 'statut'; } else { // prevent browser refresh from closing proposal several times if ($object->statut == SupplierProposal::STATUS_VALIDATED) { - $object->cloture($user, GETPOST('statut'), GETPOST('note')); + $object->cloture($user, GETPOST('statut'), GETPOST('note','none')); } } } - // Action for direct print + // Actions when printing a doc from card include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $trigger_name='SUPPLIER_PROPOSAL_SENTBYMAIL'; - $paramname='id'; - $mode='emailfromsupplierproposal'; + $trigger_name='PROPOSAL_SUPPLIER_SENTBYMAIL'; + $autocopy='MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO'; $trackid='spr'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + // Actions to build doc + $upload_dir = $conf->supplier_proposal->dir_output; + $permissioncreate = $user->rights->supplier_proposal->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; // Go back to draft @@ -507,12 +518,12 @@ if (empty($reshook)) // Add a product line if ($action == 'addline' && $user->rights->supplier_proposal->creer) { - $langs->load('errors'); - $error = 0; + $langs->load('errors'); + $error = 0; // Set if we used free entry or predefined product - $predef=''; - $ref_fourn = GETPOST('fourn_ref'); + $predef=''; + $ref_fourn = GETPOST('fourn_ref'); $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); $date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); @@ -572,117 +583,117 @@ if (empty($reshook)) // Ecrase $txtva par celui du produit if ((GETPOST('prod_entry_mode') != 'free') && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' { - $productsupplier = new ProductFournisseur($db); + $productsupplier = new ProductFournisseur($db); - if (empty($conf->global->SUPPLIER_PROPOSAL_WITH_NOPRICEDEFINED)) // TODO this test seems useless - { - $idprod=0; - if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) - } - if (preg_match('/^idprod_([0-9]+)$/',GETPOST('idprodfournprice'), $reg)) - { - $idprod=$reg[1]; - $res=$productsupplier->fetch($idprod); - // Call to init properties of $productsupplier - // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price - $productsupplier->get_buyprice(0, -1, $idprod, 'none'); // We force qty to -1 to be sure to find if a supplier price exist - } - elseif (GETPOST('idprodfournprice') > 0) - { - //$qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. - $qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist - $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qtytosearch); - $res=$productsupplier->fetch($idprod); - } + if (empty($conf->global->SUPPLIER_PROPOSAL_WITH_NOPRICEDEFINED)) // TODO this test seems useless + { + $idprod=0; + if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + } + if (preg_match('/^idprod_([0-9]+)$/',GETPOST('idprodfournprice'), $reg)) + { + $idprod=$reg[1]; + $res=$productsupplier->fetch($idprod); + // Call to init properties of $productsupplier + // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price + $productsupplier->get_buyprice(0, -1, $idprod, 'none'); // We force qty to -1 to be sure to find if a supplier price exist + } + elseif (GETPOST('idprodfournprice') > 0) + { + //$qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. + $qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist + $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qtytosearch); + $res=$productsupplier->fetch($idprod); + } - if ($idprod > 0) - { - $pu_ht = $productsupplier->fourn_pu; - $price_base_type = $productsupplier->fourn_price_base_type; - $type = $productsupplier->type; - $label = $productsupplier->label; - $desc = $productsupplier->description; - if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); + if ($idprod > 0) + { + $pu_ht = $productsupplier->fourn_pu; + $price_base_type = $productsupplier->fourn_price_base_type; + $type = $productsupplier->type; + $label = $productsupplier->label; + $desc = $productsupplier->description; + if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); - $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); - $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); - if (empty($tva_tx)) $tva_npr=0; - $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); - $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); + $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); + $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); + if (empty($tva_tx)) $tva_npr=0; + $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); + $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); - $result=$object->addline( - $desc, - $pu_ht, - $qty, - $tva_tx, - $localtax1_tx, - $localtax2_tx, - $productsupplier->id, - $remise_percent, - $price_base_type, - $pu_ttc, - $tva_npr, - $type, - -1, - 0, - GETPOST('fk_parent_line'), - $fournprice, - $buyingprice, - $label, - $array_options, - $ref_fourn, - $fk_unit - ); - //var_dump($tva_tx);var_dump($productsupplier->fourn_pu);var_dump($price_base_type);exit; - } - if ($idprod == -99 || $idprod == 0) - { - // Product not selected - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")).' '.$langs->trans("or").' '.$langs->trans("NoPriceDefinedForThisSupplier"), null, 'errors'); - } - if ($idprod == -1) - { - // Quantity too low - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); - } + $result=$object->addline( + $desc, + $pu_ht, + $qty, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $productsupplier->id, + $remise_percent, + $price_base_type, + $pu_ttc, + $tva_npr, + $type, + -1, + 0, + GETPOST('fk_parent_line'), + $fournprice, + $buyingprice, + $label, + $array_options, + $ref_fourn, + $fk_unit + ); + //var_dump($tva_tx);var_dump($productsupplier->fourn_pu);var_dump($price_base_type);exit; + } + if ($idprod == -99 || $idprod == 0) + { + // Product not selected + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")).' '.$langs->trans("or").' '.$langs->trans("NoPriceDefinedForThisSupplier"), null, 'errors'); + } + if ($idprod == -1) + { + // Quantity too low + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); + } } else if((GETPOST('price_ht')!=='' || GETPOST('price_ttc')!=='') && empty($error)) // Free product { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); - $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); - $tva_tx = str_replace('*', '', $tva_tx); - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - $desc = $product_desc; - $type = GETPOST('type'); + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); + $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); + $tva_tx = str_replace('*', '', $tva_tx); + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + $desc = $product_desc; + $type = GETPOST('type'); - $fk_unit= GETPOST('units', 'alpha'); + $fk_unit= GETPOST('units', 'alpha'); - $tva_tx = price2num($tva_tx); // When vat is text input field + $tva_tx = price2num($tva_tx); // When vat is text input field - // Local Taxes - $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); + // Local Taxes + $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - if (GETPOST('price_ht')!=='') - { - $price_base_type = 'HT'; - $ht = price2num(GETPOST('price_ht')); - $ttc = 0; - } - else - { - $ttc = price2num(GETPOST('price_ttc')); - $ht = $ttc / (1 + ($tva_tx / 100)); - $price_base_type = 'HT'; - } + if (GETPOST('price_ht')!=='') + { + $price_base_type = 'HT'; + $ht = price2num(GETPOST('price_ht')); + $ttc = 0; + } + else + { + $ttc = price2num(GETPOST('price_ttc')); + $ht = $ttc / (1 + ($tva_tx / 100)); + $price_base_type = 'HT'; + } $result = $object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $ttc, $info_bits, $type, - 1, 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, $ref_fourn, $fk_unit); - //$result = $object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, $ttc, $type,'','', $date_start, $date_end, $array_options, $fk_unit); + //$result = $object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, $ttc, $type,'','', $date_start, $date_end, $array_options, $fk_unit); } @@ -695,9 +706,9 @@ if (empty($reshook)) { $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -705,7 +716,7 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); + if ($result < 0) dol_print_error($db,$result); } unset($_POST['prod_entry_mode']); @@ -718,7 +729,7 @@ if (empty($reshook)) unset($_POST['multicurrency_price_ht']); unset($_POST['price_ttc']); unset($_POST['tva_tx']); - unset($_POST['label']); + unset($_POST['label']); unset($_POST['product_ref']); unset($_POST['product_label']); unset($_POST['product_desc']); @@ -763,7 +774,7 @@ if (empty($reshook)) $info_bits |= 0x01; // Clean parameters - $description = dol_htmlcleanlastbr(GETPOST('product_desc')); + $description = dol_htmlcleanlastbr(GETPOST('product_desc','none')); // Define vat_rate $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); @@ -871,49 +882,11 @@ if (empty($reshook)) } } - else if ($action == 'updateligne' && $user->rights->supplier_proposal->creer && GETPOST('cancel') == $langs->trans('Cancel')) { + else if ($action == 'updateligne' && $user->rights->supplier_proposal->creer && GETPOST('cancel','alpha') == $langs->trans('Cancel')) { header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $object->id); // Pour reaffichage de la fiche en cours d'edition exit(); } - // Generation doc (depuis lien ou depuis cartouche doc) - else if ($action == 'builddoc' && $user->rights->supplier_proposal->creer) { - if (GETPOST('model')) { - $object->setDocModel($user, GETPOST('model')); - } - - // Define output language - $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { - $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id','aZ09') ? GETPOST('lang_id','aZ09') : $object->thirdparty->default_lang); - $outputlangs->setDefaultLang($newlang); - } - $ret = $object->fetch($id); // Reload to get new records - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $action=''; - } - } - - // Remove file in doc form - else if ($action == 'remove_file' && $user->rights->supplier_proposal->creer) { - if ($object->id > 0) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - - $langs->load("other"); - $upload_dir = $conf->supplier_proposal->dir_output; - $file = $upload_dir . '/' . GETPOST('file'); - $ret = dol_delete_file($file, 0, 0, 0, $object); - if ($ret) - setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else - setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); - } - } - // Set project else if ($action == 'classin' && $user->rights->supplier_proposal->creer) { $object->setProject($_POST['projectid']); @@ -957,11 +930,17 @@ if (empty($reshook)) $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); if ($ret < 0) $error++; + if (! $error) { $result = $object->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } + if ($error) $action = 'edit_extras'; } } @@ -985,9 +964,9 @@ $now = dol_now(); // Add new askprice if ($action == 'create') { - $currency_code = $conf->currency; + $currency_code = $conf->currency; - print load_fiche_titre($langs->trans("NewAskPrice")); + print load_fiche_titre($langs->trans("NewAskPrice")); $soc = new Societe($db); if ($socid > 0) @@ -1024,8 +1003,8 @@ if ($action == 'create') if (!empty($conf->multicurrency->enabled)) { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; } } else @@ -1063,6 +1042,7 @@ if ($action == 'create') } else { print ''; } print '' . "\n"; @@ -1077,19 +1057,19 @@ if ($action == 'create') $form->select_types_paiements(GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $mode_reglement_id, 'mode_reglement_id'); print ''; - // Bank Account - if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { - print ''; - } + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { + print ''; + } - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + } // Delivery date (or manufacturing) print ''; @@ -1141,15 +1121,15 @@ if ($action == 'create') { print ''; print ''; - print ''; } // Other attributes $parameters = array('colspan' => ' colspan="3"'); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields, 'edit'); } @@ -1207,7 +1187,7 @@ if ($action == 'create') if (! empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) { - print '
    '; @@ -1152,7 +1132,7 @@ else } // Email web - print '
    '.fieldLabel('EMail','email').(! empty($conf->global->SOCIETE_MAIL_REQUIRED)?'*':'').'
    '.fieldLabel('EMail','email',$conf->global->SOCIETE_EMAIL_MANDATORY).'
    '.fieldLabel('Web','url').'
    ".$extrafields->attribute_pos[$key]."".$extrafields->attribute_label[$key]."
    ".$extrafields->attribute_label[$key]."".$key."'; print $form->select_company('', 'socid', 's.fournisseur = 1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); + print ' '.$langs->trans("AddThirdParty").''; print '
    ' . $langs->trans('BankAccount') . ''; - $form->select_comptes(GETPOST('fk_account')>0 ? GETPOST('fk_account','int') : $fk_account, 'fk_account', 0, '', 1); - print '
    ' . $langs->trans('BankAccount') . ''; + $form->select_comptes(GETPOST('fk_account')>0 ? GETPOST('fk_account','int') : $fk_account, 'fk_account', 0, '', 1); + print '
    ' . $langs->trans('SendingMethod') . ''; - print $form->selectShippingMethod(GETPOST('shipping_method_id') > 0 ? GETPOST('shipping_method_id', 'int') : $shipping_method_id, 'shipping_method_id', '', 1); - print '
    ' . $langs->trans('SendingMethod') . ''; + print $form->selectShippingMethod(GETPOST('shipping_method_id') > 0 ? GETPOST('shipping_method_id', 'int') : $shipping_method_id, 'shipping_method_id', '', 1); + print '
    ' . $langs->trans("DeliveryDate") . '
    '.fieldLabel('Currency','multicurrency_code').''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print '
    '; + print '
    '; // For backward compatibility print ''; @@ -1353,7 +1333,7 @@ if ($action == 'create') // Supplier proposal card - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; @@ -1365,34 +1345,34 @@ if ($action == 'create') // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->supplier_proposal->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$object->socid:-1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->supplier_proposal->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$object->socid:-1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } } $morehtmlref.='
    '; @@ -1494,17 +1474,17 @@ if ($action == 'create') print '
    '; print '
    '; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { - if($action == 'actualizemulticurrencyrate') { + if($action == 'actualizemulticurrencyrate') { list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); - } - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); + } + $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); - if($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { - print '
            '; - print ''.$langs->trans("ActualizeCurrency").''; - print '
    '; - } + $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); + if($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { + print '
            '; + print ''.$langs->trans("ActualizeCurrency").''; + print '
    '; + } } print '
    '; - print ''; - if ($action != 'editbankaccount' && $user->rights->supplier_proposal->creer) - print ''; - print '
    '; - print $langs->trans('BankAccount'); - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; - print '
    '; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print '
    '; + print ''; + if ($action != 'editbankaccount' && $user->rights->supplier_proposal->creer) + print ''; + print '
    '; + print $langs->trans('BankAccount'); + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; + print '
    '; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print '
    '; // Add free products/services form @@ -1669,7 +1649,7 @@ if ($action == 'create') } print '
    '; - print '
    '; + print '
    '; print "\n"; dol_fiche_end(); @@ -1710,15 +1690,15 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { if ($action != 'statut' && $action != 'editline') { // Validate if ($object->statut == SupplierProposal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0 && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->validate_advance))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->validate_advance))) ) { if (count($object->lines) > 0) print ''; @@ -1759,8 +1739,8 @@ if ($action == 'create') // Close if ($object->statut == SupplierProposal::STATUS_SIGNED && $user->rights->supplier_proposal->cloturer) { - print ''; + print ''; } // Clone @@ -1805,113 +1785,23 @@ if ($action == 'create') // List of actions on element include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'supplier_proposal', $socid); + $somethingshown = $formactions->showactions($object, 'supplier_proposal', $socid, 1); print ''; } - /* - * Action presend - */ + // Select mail models is same action as presend if (GETPOST('modelselected')) { $action = 'presend'; } - if ($action == 'presend') - { - $object->fetch_projet(); - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($conf->supplier_proposal->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; + // Presend form + $modelmail='supplier_proposal_send'; + $defaulttopic='SendAskRef'; + $diroutput = $conf->supplier_proposal->dir_output; + $trackid = 'spr'.$object->id; - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - - if (!empty($newlang)) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($newlang); - $outputlangs->load('commercial'); - $outputlangs->load('supplier_proposal'); - } - - // Build document if it not exists - if (! $file || ! is_readable($file)) { - $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - dol_print_error($db, $object->error, $object->errors); - exit(); - } - $fileparams = dol_most_recent_file($conf->supplier_proposal->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - } - - print '
    '; - print '
    '; - print '
    '; - print load_fiche_titre($langs->trans('SendAskByMail')); - - dol_fiche_head(''); - - // Create form object - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - $formmail->trackid='spr'.$object->id; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'spr'.$object->id); - } - - $formmail->withfrom = 1; - $liste = array(); - foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) - $liste [$key] = $value; - $formmail->withto = GETPOST("sendto") ? GETPOST("sendto") : $liste; - $formmail->withtocc = $liste; - $formmail->withtoccc = (! empty($conf->global->MAIN_EMAIL_USECCC) ? $conf->global->MAIN_EMAIL_USECCC : false); - - $formmail->withtopic = $outputlangs->trans('SendAskRef', '__SUPPLIERPROPREF__'); - - $formmail->withfile = 2; - $formmail->withbody = 1; - $formmail->withdeliveryreceipt = 1; - $formmail->withcancel = 1; - - // Tableau des substitutions - $formmail->setSubstitFromObject($object); - $formmail->substit['__SUPPLIERPROPREF__'] = $object->ref; - - // Tableau des parametres complementaires - $formmail->param['action'] = 'send'; - $formmail->param['models'] = 'supplier_proposal_send'; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['id'] = $object->id; - $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; - // Init list of files - if (GETPOST("mode") == 'init') { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file, basename($file), dol_mimetype($file)); - } - - print $formmail->get_form(); - - dol_fiche_end(); - } + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } // End of page diff --git a/htdocs/supplier_proposal/class/supplier_proposal.class.php b/htdocs/supplier_proposal/class/supplier_proposal.class.php index 2751e89763c..2b30b550f38 100644 --- a/htdocs/supplier_proposal/class/supplier_proposal.class.php +++ b/htdocs/supplier_proposal/class/supplier_proposal.class.php @@ -48,7 +48,7 @@ class SupplierProposal extends CommonObject public $table_element='supplier_proposal'; public $table_element_line='supplier_proposaldet'; public $fk_element='fk_supplier_proposal'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='propal'; /** @@ -1141,8 +1141,8 @@ class SupplierProposal extends CommonObject $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN (' . getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term').')'; $sql.= " WHERE p.fk_statut = c.id"; $sql.= " AND p.entity = ".$conf->entity; if ($ref) $sql.= " AND p.ref='".$ref."'"; @@ -1222,9 +1222,7 @@ class SupplierProposal extends CommonObject $this->lines = array(); - /* - * Lignes askprice liees a un produit ou non - */ + // Lines of supplier proposals $sql = "SELECT d.rowid, d.fk_supplier_proposal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,"; $sql.= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,"; $sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,'; @@ -1329,44 +1327,6 @@ class SupplierProposal extends CommonObject } } - /** - * Update value of extrafields on the proposal - * - * @param User $user Object user that modify - * @return int <0 if ko, >0 if ok - */ - function update_extrafields($user) - { - $action='update'; - - // Actions on extra fields (by external module or standard code) - $hookmanager->initHooks(array('supplier_proposaldao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - else if ($reshook < 0) $error++; - - if (!$error) - { - return 1; - } - else - { - return -1; - } - - } - /** * Set status to validated * @@ -1404,7 +1364,7 @@ class SupplierProposal extends CommonObject $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; - $sql.= " SET ref = '".$num."',"; + $sql.= " SET ref = '".$this->db->escape($num)."',"; $sql.= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; @@ -1474,6 +1434,11 @@ class SupplierProposal extends CommonObject return -1; } } + else + { + dol_syslog("You don't have permission to validate supplier proposal", LOG_WARNING); + return -2; + } } /** @@ -2389,13 +2354,14 @@ class SupplierProposal extends CommonObject /** * Return clicable link of object (with eventually picto) * - * @param int $withpicto Add picto into link - * @param string $option Where point the link ('compta', 'expedition', 'document', ...) - * @param string $get_params Parametres added to url - * @param int $notooltip 1=Disable tooltip - * @return string String with URL + * @param int $withpicto Add picto into link + * @param string $option Where point the link ('compta', 'expedition', 'document', ...) + * @param string $get_params Parametres added to url + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - function getNomUrl($withpicto=0,$option='', $get_params='', $notooltip=0) + function getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1) { global $langs, $conf, $user; @@ -2422,6 +2388,14 @@ class SupplierProposal extends CommonObject $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id. $get_params; } + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + $linkclose=''; if (empty($notooltip) && $user->rights->propal->lire) { @@ -2440,12 +2414,11 @@ class SupplierProposal extends CommonObject $picto='supplier_proposal'; + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; - if ($withpicto) - $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) - $result.=' '; - $result.=$linkstart.$this->ref.$linkend; return $result; } @@ -2854,27 +2827,27 @@ class SupplierProposalLine extends CommonObjectLine $sql.= ' ref_fourn,'; $sql.= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc, fk_unit)'; $sql.= " VALUES (".$this->fk_supplier_proposal.","; - $sql.= " ".($this->fk_parent_line>0?"'".$this->fk_parent_line."'":"null").","; + $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").","; $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; $sql.= " '".$this->db->escape($this->desc)."',"; - $sql.= " ".($this->fk_product?"'".$this->fk_product."'":"null").","; - $sql.= " '".$this->product_type."',"; - $sql.= " ".($this->fk_remise_except?"'".$this->fk_remise_except."'":"null").","; + $sql.= " ".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":"null").","; + $sql.= " '".$this->db->escape($this->product_type)."',"; + $sql.= " ".($this->fk_remise_except?"'".$this->db->escape($this->fk_remise_except)."'":"null").","; $sql.= " ".price2num($this->qty).","; $sql.= " ".price2num($this->tva_tx).","; $sql.= " ".price2num($this->localtax1_tx).","; $sql.= " ".price2num($this->localtax2_tx).","; - $sql.= " '".$this->localtax1_type."',"; - $sql.= " '".$this->localtax2_type."',"; + $sql.= " '".$this->db->escape($this->localtax1_type)."',"; + $sql.= " '".$this->db->escape($this->localtax2_type)."',"; $sql.= " ".(!empty($this->subprice)?price2num($this->subprice):"null").","; $sql.= " ".price2num($this->remise_percent).","; - $sql.= " ".(isset($this->info_bits)?"'".$this->info_bits."'":"null").","; + $sql.= " ".(isset($this->info_bits)?"'".$this->db->escape($this->info_bits)."'":"null").","; $sql.= " ".price2num($this->total_ht).","; $sql.= " ".price2num($this->total_tva).","; $sql.= " ".price2num($this->total_localtax1).","; $sql.= " ".price2num($this->total_localtax2).","; $sql.= " ".price2num($this->total_ttc).","; - $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->fk_fournprice."'":"null").","; + $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null").","; $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").","; $sql.= ' '.$this->special_code.','; $sql.= ' '.$this->rang.','; @@ -3050,7 +3023,7 @@ class SupplierProposalLine extends CommonObjectLine $sql.= " , total_localtax1=".price2num($this->total_localtax1).""; $sql.= " , total_localtax2=".price2num($this->total_localtax2).""; } - $sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->fk_fournprice."'":"null"); + $sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null"); $sql.= " , buy_price_ht=".price2num($this->pa_ht); if (strlen($this->special_code)) $sql.= " , special_code=".$this->special_code; $sql.= " , fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); diff --git a/htdocs/supplier_proposal/document.php b/htdocs/supplier_proposal/document.php index 4985fd34629..9bb7db0222b 100644 --- a/htdocs/supplier_proposal/document.php +++ b/htdocs/supplier_proposal/document.php @@ -94,7 +94,7 @@ if ($object->id > 0) // Supplier proposal card - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; diff --git a/htdocs/supplier_proposal/info.php b/htdocs/supplier_proposal/info.php index 8cee304e3bb..9f134b332ae 100644 --- a/htdocs/supplier_proposal/info.php +++ b/htdocs/supplier_proposal/info.php @@ -58,7 +58,7 @@ $head = supplier_proposal_prepare_head($object); dol_fiche_head($head, 'info', $langs->trans('CommRequest'), -1, 'supplier_proposal'); // Supplier proposal card -$linkback = '' . $langs->trans("BackToList") . ''; +$linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; diff --git a/htdocs/supplier_proposal/list.php b/htdocs/supplier_proposal/list.php index 4240ca72a08..d3ce6ce6a27 100644 --- a/htdocs/supplier_proposal/list.php +++ b/htdocs/supplier_proposal/list.php @@ -126,39 +126,39 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'p.ref'=>'Ref', - 's.nom'=>'Supplier', - 'pd.description'=>'Description', - 'p.note_public'=>'NotePublic', + 'p.ref'=>'Ref', + 's.nom'=>'Supplier', + 'pd.description'=>'Description', + 'p.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["p.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'sp.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("Supplier"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'sp.date_valid'=>array('label'=>$langs->trans("Date"), 'checked'=>1), - 'sp.date_livraison'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), - 'sp.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'sp.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'sp.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), - 'sp.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'sp.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'sp.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'sp.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("Supplier"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'sp.date_valid'=>array('label'=>$langs->trans("Date"), 'checked'=>1), + 'sp.date_livraison'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), + 'sp.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'sp.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'sp.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), + 'sp.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'sp.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'sp.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } } @@ -168,8 +168,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -180,38 +180,38 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_ref=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_login=''; - $search_product_category=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_author=''; - $yearvalid=''; - $monthvalid=''; - $year=''; - $month=''; - $search_status=''; - $object_statut=''; + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_ref=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_login=''; + $search_product_category=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $search_author=''; + $yearvalid=''; + $monthvalid=''; + $year=''; + $month=''; + $search_status=''; + $object_statut=''; } if (empty($reshook)) { - $objectclass='SupplierProposal'; - $objectlabel='SupplierProposals'; - $permtoread = $user->rights->supplier_proposal->lire; - $permtodelete = $user->rights->supplier_proposal->supprimer; - $uploaddir = $conf->supplier_proposal->dir_output; + $objectclass='SupplierProposal'; + $objectlabel='SupplierProposals'; + $permtoread = $user->rights->supplier_proposal->lire; + $permtodelete = $user->rights->supplier_proposal->supprimer; + $uploaddir = $conf->supplier_proposal->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -263,8 +263,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = sp.fk_projet"; if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE sp.fk_soc = s.rowid'; $sql.= ' AND sp.entity IN ('.getEntity('supplier_proposal').')'; @@ -288,12 +288,12 @@ if ($socid) $sql.= ' AND s.rowid = '.$socid; if ($search_status >= 0 && $search_status != '') $sql.= ' AND sp.fk_statut IN ('.$db->escape($search_status).')'; if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND sp.date_livraison BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND sp.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(sp.date_livraison, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND sp.date_livraison BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND sp.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(sp.date_livraison, '%m') = '".$month."'"; } else if ($year > 0) { @@ -301,12 +301,12 @@ else if ($year > 0) } if ($monthvalid > 0) { - if ($yearvalid > 0 && empty($dayvalid)) - $sql.= " AND sp.date_valid BETWEEN '".$db->idate(dol_get_first_day($yearvalid,$monthvalid,false))."' AND '".$db->idate(dol_get_last_day($yearvalid,$monthvalid,false))."'"; - else if ($yearvalid > 0 && ! empty($dayvalid)) - $sql.= " AND sp.date_valid BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $monthvalid, $dayvalid, $yearvalid))."' AND '".$db->idate(dol_mktime(23, 59, 59, $monthvalid, $dayvalid, $yearvalid))."'"; - else - $sql.= " AND date_format(sp.date_valid, '%m') = '".$monthvalid."'"; + if ($yearvalid > 0 && empty($dayvalid)) + $sql.= " AND sp.date_valid BETWEEN '".$db->idate(dol_get_first_day($yearvalid,$monthvalid,false))."' AND '".$db->idate(dol_get_last_day($yearvalid,$monthvalid,false))."'"; + else if ($yearvalid > 0 && ! empty($dayvalid)) + $sql.= " AND sp.date_valid BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $monthvalid, $dayvalid, $yearvalid))."' AND '".$db->idate(dol_mktime(23, 59, 59, $monthvalid, $dayvalid, $yearvalid))."'"; + else + $sql.= " AND date_format(sp.date_valid, '%m') = '".$monthvalid."'"; } else if ($yearvalid > 0) { @@ -315,21 +315,21 @@ else if ($yearvalid > 0) if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) { - $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='supplier_proposal' AND tc.source='internal' AND c.element_id = sp.rowid AND c.fk_socpeople = ".$search_user; + $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='supplier_proposal' AND tc.source='internal' AND c.element_id = sp.rowid AND c.fk_socpeople = ".$search_user; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -357,13 +357,13 @@ if ($resql) if ($socid > 0) { - $soc = new Societe($db); - $soc->fetch($socid); - $title = $langs->trans('ListOfSupplierProposals') . ' - '.$soc->name; + $soc = new Societe($db); + $soc->fetch($socid); + $title = $langs->trans('ListOfSupplierProposals') . ' - '.$soc->name; } else { - $title = $langs->trans('ListOfSupplierProposals'); + $title = $langs->trans('ListOfSupplierProposals'); } $num = $db->num_rows($resql); @@ -371,13 +371,13 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $param.='&sall='.$sall; if ($month) $param.='&month='.$month; if ($year) $param.='&year='.$year; - if ($search_ref) $param.='&search_ref=' .$search_ref; - if ($search_societe) $param.='&search_societe=' .$search_societe; + if ($search_ref) $param.='&search_ref=' .$search_ref; + if ($search_societe) $param.='&search_societe=' .$search_societe; if ($search_user > 0) $param.='&search_user='.$search_user; if ($search_sale > 0) $param.='&search_sale='.$search_sale; if ($search_montant_ht) $param.='&search_montant_ht='.$search_montant_ht; @@ -390,15 +390,15 @@ if ($resql) // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->supplier_proposal->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); if ($massaction == 'presend') $arrayofmassactions=array(); @@ -418,106 +418,18 @@ if ($resql) if ($massaction == 'presend') { - $langs->load("mails"); + $topicmail="SendSupplierProposalRef"; + $modelmail="supplier_proposal_send"; + $objecttmp=new SupplierProposal($db); + $trackid='spro'.$object->id; - if (! GETPOST('cancel')) - { - $objecttmp=new SupplierProposal($db); - $listofselectedid=array(); - $listofselectedthirdparties=array(); - $listofselectedref=array(); - foreach($arrayofselected as $toselectid) - { - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofselectedid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - $listofselectedthirdparties[$thirdpartyid]=$thirdpartyid; - $listofselectedref[$thirdpartyid][$toselectid]=$objecttmp->ref; - } - } - } - - print ''; - - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - - dol_fiche_head(null, '', ''); - - $topicmail="SendProposalRef"; - $modelmail="propal_send"; - - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->withform=-1; - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 1)) // If bit 1 is set - { - $formmail->trackid='ord'.$object->id; - } - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'ord'.$object->id); - } - $formmail->withfrom=1; - $liste=$langs->trans("AllRecipientSelected"); - if (count($listofselectedthirdparties) == 1) - { - $liste=array(); - $thirdpartyid=array_shift($listofselectedthirdparties); - $soc=new Societe($db); - $soc->fetch($thirdpartyid); - foreach ($soc->thirdparty_and_contact_email_array(1) as $key=>$value) - { - $liste[$key]=$value; - } - $formmail->withtoreadonly=0; - } - else - { - $formmail->withtoreadonly=1; - } - $formmail->withto=$liste; - $formmail->withtofree=0; - $formmail->withtocc=1; - $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic=$langs->transnoentities($topicmail, '__REF__', '__REFCLIENT__'); - $formmail->withfile=$langs->trans("OnlyPDFattachmentSupported"); - $formmail->withbody=1; - $formmail->withdeliveryreceipt=1; - $formmail->withcancel=1; - // Tableau des substitutions - $formmail->substit['__REF__']='__REF__'; // We want to keep the tag - $formmail->substit['__SIGNATURE__']=$user->signature; - $formmail->substit['__REFCLIENT__']='__REFCLIENT__'; // We want to keep the tag - $formmail->substit['__PERSONALIZED__']=''; - $formmail->substit['__CONTACTCIVNAME__']=''; - - // Tableau des parametres complementaires du post - $formmail->param['action']=$action; - $formmail->param['models']=$modelmail; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['id']=join(',',$arrayofselected); - //$formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id; - - print $formmail->get_form(); - - dol_fiche_end(); + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; } if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } $i = 0; @@ -536,20 +448,20 @@ if ($resql) // If the user can view prospects other than his' if ($user->rights->societe->client->voir || $socid) { - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); - $moreforfilter.='
    '; + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + $moreforfilter.='
    '; } // If the user can view products if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { - include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='
    '; + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); + $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); + $moreforfilter.='
    '; } $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook @@ -557,18 +469,18 @@ if ($resql) else $moreforfilter = $hookmanager->resPrint; if (! empty($moreforfilter)) - { - print '
    '; - print $moreforfilter; - print '
    '; - } + { + print '
    '; + print $moreforfilter; + print '
    '; + } - $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); + $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"; + print '
    '; + print '
    '."\n"; print ''; if (! empty($arrayfields['sp.ref']['checked'])) @@ -586,26 +498,26 @@ if ($resql) if (! empty($arrayfields['s.town']['checked'])) print ''; if (! empty($arrayfields['s.zip']['checked'])) print ''; // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print ''; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - } + if (! empty($arrayfields['state.nom']['checked'])) + { + print ''; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + } // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - } + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + } // Date if (! empty($arrayfields['sp.date_valid']['checked'])) { @@ -631,54 +543,54 @@ if ($resql) if (! empty($arrayfields['sp.total_ht']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['sp.total_vat']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['sp.total_ttc']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['u.login']['checked'])) { - // Author - print ''; + // Author + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -687,14 +599,14 @@ if ($resql) // Date creation if (! empty($arrayfields['sp.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['sp.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['sp.fk_statut']['checked'])) @@ -731,19 +643,19 @@ if ($resql) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['sp.datec']['checked'])) print_liste_field_titre($arrayfields['sp.datec']['label'],$_SERVER["PHP_SELF"],"sp.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['sp.tms']['checked'])) print_liste_field_titre($arrayfields['sp.tms']['label'],$_SERVER["PHP_SELF"],"sp.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['sp.fk_statut']['checked'])) print_liste_field_titre($arrayfields['sp.fk_statut']['label'],$_SERVER["PHP_SELF"],"sp.fk_statut","",$param,'align="right"',$sortfield,$sortorder); @@ -812,164 +724,164 @@ if ($resql) // Thirdparty if (! empty($arrayfields['s.nom']['checked'])) { - print ''; if (! $i) $totalarray['nbfield']++; } // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Date proposal - if (! empty($arrayfields['sp.date_valid']['checked'])) - { - print '\n"; if (! $i) $totalarray['nbfield']++; - } + } // Date delivery - if (! empty($arrayfields['sp.date_livraison']['checked'])) - { - print '\n"; if (! $i) $totalarray['nbfield']++; - } + } - // Amount HT - if (! empty($arrayfields['sp.total_ht']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['sp.total_vat']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount TTC - if (! empty($arrayfields['sp.total_ttc']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } + // Amount HT + if (! empty($arrayfields['sp.total_ht']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['sp.total_vat']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount TTC + if (! empty($arrayfields['sp.total_ttc']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } $userstatic->id=$obj->fk_user_author; $userstatic->login=$obj->login; - // Author - if (! empty($arrayfields['u.login']['checked'])) - { + // Author + if (! empty($arrayfields['u.login']['checked'])) + { print '\n"; - if (! $i) $totalarray['nbfield']++; - } + if (! $i) $totalarray['nbfield']++; + } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['sp.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['sp.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['sp.fk_statut']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['sp.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['sp.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['sp.fk_statut']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; @@ -981,28 +893,28 @@ if ($resql) // Show total line if (isset($totalarray['totalhtfield']) - || isset($totalarray['totalvatfield']) - || isset($totalarray['totalttcfield']) - || isset($totalarray['totalamfield']) - || isset($totalarray['totalrtpfield']) - ) + || isset($totalarray['totalvatfield']) + || isset($totalarray['totalttcfield']) + || isset($totalarray['totalamfield']) + || isset($totalarray['totalrtpfield']) + ) { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''; - else print ''; - } - elseif ($totalarray['totalhtfield'] == $i) print ''; - elseif ($totalarray['totalvatfield'] == $i) print ''; - elseif ($totalarray['totalttcfield'] == $i) print ''; - else print ''; - } - print ''; + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } + elseif ($totalarray['totalhtfield'] == $i) print ''; + elseif ($totalarray['totalvatfield'] == $i) print ''; + elseif ($totalarray['totalttcfield'] == $i) print ''; + else print ''; + } + print ''; } $db->free($resql); @@ -1012,28 +924,28 @@ if ($resql) print $hookmanager->resPrint; print '
    '; - print ''; - print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print ''; + print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + 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 ''; + 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 ''; - print ''; + print ''; + print ''; print $companystatic->getNomUrl(1,'customer'); print ''; - print $obj->town; - print ''; - print $obj->zip; - print '".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; + print $obj->town; + print ''; + print $obj->zip; + print '".$obj->state_name."'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; + if (! empty($arrayfields['sp.date_valid']['checked'])) + { + print ''; print dol_print_date($db->jdate($obj->date_valid), 'day'); print "'; + if (! empty($arrayfields['sp.date_livraison']['checked'])) + { + print ''; print dol_print_date($db->jdate($obj->dp), 'day'); print "'.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_ttc)."'.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_ttc)."'; if ($userstatic->id) print $userstatic->getLoginUrl(1); else print ' '; print "'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$objectstatic->LibStatut($obj->fk_statut,5)."'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$objectstatic->LibStatut($obj->fk_statut,5)."'; - 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 ''; + 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 '
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
    '."\n"; - print '
    '."\n"; + print '
    '."\n"; print ''."\n"; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; + $filedir=$diroutputmassaction; - $genallowed=$user->rights->supplier_proposal->lire; - $delallowed=$user->rights->supplier_proposal->creer; + $genallowed=$user->rights->supplier_proposal->lire; + $delallowed=$user->rights->supplier_proposal->creer; - print $formfile->showdocuments('massfilesarea_supplier_proposal','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); + print $formfile->showdocuments('massfilesarea_supplier_proposal','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); } else { - print '
    '.$langs->trans("ShowTempMassFilesArea").''; + print '
    '.$langs->trans("ShowTempMassFilesArea").''; } } diff --git a/htdocs/supplier_proposal/note.php b/htdocs/supplier_proposal/note.php index 10a9668382c..997cb67db2f 100644 --- a/htdocs/supplier_proposal/note.php +++ b/htdocs/supplier_proposal/note.php @@ -71,7 +71,7 @@ if ($id > 0 || ! empty($ref)) if ($object->fetch($id, $ref)) { $object->fetch_thirdparty(); - + $societe = new Societe($db); if ( $societe->fetch($object->socid) ) { @@ -80,9 +80,9 @@ if ($id > 0 || ! empty($ref)) // Supplier proposal card - $linkback = '' . $langs->trans("BackToList") . ''; - - + $linkback = '' . $langs->trans("BackToList") . ''; + + $morehtmlref='
    '; // Ref supplier //$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->creer, 'string', '', 0, 1); @@ -123,17 +123,17 @@ if ($id > 0 || ! empty($ref)) } } $morehtmlref.='
    '; - - + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - - + + print '
    '; print '
    '; - + $cssclass="titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; - + print '
    '; dol_fiche_end(); diff --git a/htdocs/theme/common/cheque.png b/htdocs/theme/common/cheque.png new file mode 100644 index 00000000000..34b89a1e1d0 Binary files /dev/null and b/htdocs/theme/common/cheque.png differ diff --git a/htdocs/theme/common/credit_card.png b/htdocs/theme/common/credit_card.png new file mode 100644 index 00000000000..1d2fc827f61 Binary files /dev/null and b/htdocs/theme/common/credit_card.png differ diff --git a/htdocs/theme/eldy/ckeditor/config.js b/htdocs/theme/eldy/ckeditor/config.js index cddbef17dd1..b70e371fcfb 100644 --- a/htdocs/theme/eldy/ckeditor/config.js +++ b/htdocs/theme/eldy/ckeditor/config.js @@ -34,10 +34,10 @@ CKEDITOR.editorConfig = function( config ) [ ['Templates','NewPage'], ['Save'], - ['Source','Maximize','Preview'], + ['Maximize','Preview'], ['PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'], // 'Cut','Copy','Paste','-', are useless, can be done with right click, even on smarpthone ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], - ['CreateDiv','ShowBlocks'], + ['CreateDiv','ShowBlocks'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'], @@ -46,13 +46,14 @@ CKEDITOR.editorConfig = function( config ) ['Link','Unlink','Anchor'], ['Image','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe'], ['Styles','Format','Font','FontSize'], - ['TextColor','BGColor'] + ['TextColor','BGColor'], + ['Source'] ]; // Used for mailing fields config.toolbar_dolibarr_mailings = [ - ['Source','Maximize','Preview'], + ['Maximize','Preview'], ['SpellChecker', 'Scayt'], ['Undo','Redo','-','Find','Replace'], ['CreateDiv','ShowBlocks'], @@ -60,38 +61,42 @@ CKEDITOR.editorConfig = function( config ) ['Bold','Italic','Underline','Strike','Subscript','Superscript','-','TextColor','RemoveFormat'], ['NumberedList','BulletedList','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], - ['Link','Unlink','Anchor','Image','Table','HorizontalRule','SpecialChar'] + ['Link','Unlink','Anchor','Image','Table','HorizontalRule','SpecialChar'], + ['Source'] ]; // Used for notes fields config.toolbar_dolibarr_notes = [ - ['Source','Maximize'], + ['Maximize'], ['SpellChecker', 'Scayt'], // 'Cut','Copy','Paste','-', are useless, can be done with right click, even on smarpthone ['Undo','Redo','-','Find','Replace'], ['Format','Font','FontSize'], ['Bold','Italic','Underline','Strike','Subscript','Superscript','-','TextColor','RemoveFormat'], ['NumberedList','BulletedList','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], - ['Link','Unlink','Image','Table','HorizontalRule','SpecialChar'] + ['Link','Unlink','Image','Table','HorizontalRule','SpecialChar'], + ['Source'] ]; // Used for details lines config.toolbar_dolibarr_details = [ - ['Source','Maximize'], + ['Maximize'], ['SpellChecker', 'Scayt'], // 'Cut','Copy','Paste','-', are useless, can be done with right click, even on smarpthone ['Format','Font','FontSize'], ['Bold','Italic','Underline','Strike','-','TextColor','RemoveFormat'], // ,'Subscript','Superscript' useless ['NumberedList','BulletedList','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], - ['Link','Unlink','SpecialChar'] + ['Link','Unlink','SpecialChar'], + ['Source'] ]; // Used for mailing fields config.toolbar_dolibarr_readonly = [ - ['Source','Maximize'], - ['Find'] + ['Maximize'], + ['Find'], + ['Source'] ]; }; diff --git a/htdocs/theme/eldy/img/object_movement.png b/htdocs/theme/eldy/img/object_movement.png new file mode 100644 index 00000000000..aec344a3f8d Binary files /dev/null and b/htdocs/theme/eldy/img/object_movement.png differ diff --git a/htdocs/theme/eldy/img/object_phoning_mobile.png b/htdocs/theme/eldy/img/object_phoning_mobile.png new file mode 100644 index 00000000000..c94fd72ae14 Binary files /dev/null and b/htdocs/theme/eldy/img/object_phoning_mobile.png differ diff --git a/htdocs/theme/eldy/img/object_website.png b/htdocs/theme/eldy/img/object_website.png new file mode 100644 index 00000000000..aae8bf6eba0 Binary files /dev/null and b/htdocs/theme/eldy/img/object_website.png differ diff --git a/htdocs/theme/eldy/img/off.png b/htdocs/theme/eldy/img/off.png deleted file mode 100644 index f4217646b26..00000000000 Binary files a/htdocs/theme/eldy/img/off.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/on.png b/htdocs/theme/eldy/img/on.png deleted file mode 100644 index 728bb393536..00000000000 Binary files a/htdocs/theme/eldy/img/on.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/stcomm0.png b/htdocs/theme/eldy/img/stcomm0.png index b6c11d4569a..1220cf8113e 100644 Binary files a/htdocs/theme/eldy/img/stcomm0.png and b/htdocs/theme/eldy/img/stcomm0.png differ diff --git a/htdocs/theme/eldy/img/working2.gif b/htdocs/theme/eldy/img/working2.gif deleted file mode 100644 index bf0fc8f2167..00000000000 Binary files a/htdocs/theme/eldy/img/working2.gif and /dev/null differ diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php index 515015b5b5a..f4c7e1c4546 100644 --- a/htdocs/theme/eldy/style.css.php +++ b/htdocs/theme/eldy/style.css.php @@ -47,6 +47,7 @@ $colorbacklineimpair2='255,255,255'; // line impair $colorbacklinepair1='248,248,248'; // line pair $colorbacklinepair2='248,248,248'; // line pair $colorbacklinepairhover='238,246,252'; // line pair +$colorbacklinebreak='214,218,220'; // line break $colorbackbody='255,255,255'; $colortexttitlenotab='100,60,20'; $colortexttitle='0,0,0'; @@ -100,26 +101,27 @@ $dol_no_mouse_hover=$conf->dol_no_mouse_hover; //$user->conf->THEME_ELDY_ENABLE_PERSONALIZED=0; //var_dump($user->conf->THEME_ELDY_RGB); -$useboldtitle=(isset($conf->global->THEME_ELDY_USEBOLDTITLE)?$conf->global->THEME_ELDY_USEBOLDTITLE:1); +$useboldtitle=(isset($conf->global->THEME_ELDY_USEBOLDTITLE)?$conf->global->THEME_ELDY_USEBOLDTITLE:0); $borderwith=2; // Case of option always editable if (! isset($conf->global->THEME_ELDY_BACKBODY)) $conf->global->THEME_ELDY_BACKBODY=$colorbackbody; if (! isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) $conf->global->THEME_ELDY_TOPMENU_BACK1=$colorbackhmenu1; +if (! isset($conf->global->THEME_ELDY_VERMENU_BACK1)) $conf->global->THEME_ELDY_VERMENU_BACK1=$colorbackvmenu1; if (! isset($conf->global->THEME_ELDY_BACKTITLE1)) $conf->global->THEME_ELDY_BACKTITLE1=$colorbacktitle1; if (! isset($conf->global->THEME_ELDY_USE_HOVER)) $conf->global->THEME_ELDY_USE_HOVER=$colorbacklinepairhover; +if (! isset($conf->global->THEME_ELDY_LINEBREAK)) $conf->global->THEME_ELDY_LINEBREAK=$colorbacklinebreak; if (! isset($conf->global->THEME_ELDY_TEXTTITLENOTAB)) $conf->global->THEME_ELDY_TEXTTITLENOTAB=$colortexttitlenotab; if (! isset($conf->global->THEME_ELDY_TEXTLINK)) $conf->global->THEME_ELDY_TEXTLINK=$colortextlink; // Case of option editable only if option THEME_ELDY_ENABLE_PERSONALIZED is on if (empty($conf->global->THEME_ELDY_ENABLE_PERSONALIZED)) { - $conf->global->THEME_ELDY_VERMENU_BACK1='255,255,255'; // vmenu - $conf->global->THEME_ELDY_BACKTABCARD1='255,255,255'; // card - $conf->global->THEME_ELDY_BACKTABACTIVE='234,234,234'; - $conf->global->THEME_ELDY_TEXT='0,0,0'; - $conf->global->THEME_ELDY_FONT_SIZE1='13'; - $conf->global->THEME_ELDY_FONT_SIZE2='12'; + $conf->global->THEME_ELDY_BACKTABCARD1='255,255,255'; // card + $conf->global->THEME_ELDY_BACKTABACTIVE='234,234,234'; + $conf->global->THEME_ELDY_TEXT='0,0,0'; + $conf->global->THEME_ELDY_FONT_SIZE1='13'; + $conf->global->THEME_ELDY_FONT_SIZE2='12'; } // Case of option availables only if THEME_ELDY_ENABLE_PERSONALIZED is on @@ -133,6 +135,7 @@ $colorbacklineimpair1=empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty( $colorbacklineimpair2=empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_LINEIMPAIR2) ?$colorbacklineimpair2:$conf->global->THEME_ELDY_LINEIMPAIR2):(empty($user->conf->THEME_ELDY_LINEIMPAIR2)?$colorbacklineimpair2:$user->conf->THEME_ELDY_LINEIMPAIR2); $colorbacklinepair1 =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_LINEPAIR1) ?$colorbacklinepair1:$conf->global->THEME_ELDY_LINEPAIR1) :(empty($user->conf->THEME_ELDY_LINEPAIR1)?$colorbacklinepair1:$user->conf->THEME_ELDY_LINEPAIR1); $colorbacklinepair2 =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_LINEPAIR2) ?$colorbacklinepair2:$conf->global->THEME_ELDY_LINEPAIR2) :(empty($user->conf->THEME_ELDY_LINEPAIR2)?$colorbacklinepair2:$user->conf->THEME_ELDY_LINEPAIR2); +$colorbacklinebreak =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_LINEBREAK) ?$colorbacklinebreak:$conf->global->THEME_ELDY_LINEBREAK) :(empty($user->conf->THEME_ELDY_LINEBREAK)?$colorbacklinebreak:$user->conf->THEME_ELDY_LINEBREAK); $colorbackbody =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_BACKBODY) ?$colorbackbody:$conf->global->THEME_ELDY_BACKBODY) :(empty($user->conf->THEME_ELDY_BACKBODY)?$colorbackbody:$user->conf->THEME_ELDY_BACKBODY); $colortexttitlenotab =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_TEXTTITLENOTAB)?$colortexttitlenotab:$conf->global->THEME_ELDY_TEXTTITLENOTAB) :(empty($user->conf->THEME_ELDY_TEXTTITLENOTAB)?$colortexttitlenotab:$user->conf->THEME_ELDY_TEXTTITLENOTAB); $colortexttitle =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_TEXTTITLE) ?$colortexttitle:$conf->global->THEME_ELDY_TEXTTITLE) :(empty($user->conf->THEME_ELDY_TEXTTITLE)?$colortexttitle:$user->conf->THEME_ELDY_TEXTTITLE); @@ -145,7 +148,7 @@ $fontsizesmaller =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty( $colorbacklinepairhover=((! isset($conf->global->THEME_ELDY_USE_HOVER) || (string) $conf->global->THEME_ELDY_USE_HOVER === '0')?'':($conf->global->THEME_ELDY_USE_HOVER === '1'?'edf4fb':$conf->global->THEME_ELDY_USE_HOVER)); if (! empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)) { - $colorbacklinepairhover=((! isset($user->conf->THEME_ELDY_USE_HOVER) || $user->conf->THEME_ELDY_USE_HOVER === '0')?'':($user->conf->THEME_ELDY_USE_HOVER === '1'?'edf4fb':$user->conf->THEME_ELDY_USE_HOVER)); + $colorbacklinepairhover=((! isset($user->conf->THEME_ELDY_USE_HOVER) || $user->conf->THEME_ELDY_USE_HOVER === '0')?'':($user->conf->THEME_ELDY_USE_HOVER === '1'?'edf4fb':$user->conf->THEME_ELDY_USE_HOVER)); } //$colortopbordertitle1=$colorbackhmenu1; @@ -167,9 +170,9 @@ $colorbacktitle1=join(',',colorStringToArray($colorbacktitle1)); // Normalize $tmppart=explode(',',$colorbacktitle1); if ($colortexttitle == '') { - $tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0); - if ($tmpval <= 460) { $colortexttitle='FFFFFF'; $colorshadowtitle='888888'; } - else { $colortexttitle='000000'; $colorshadowtitle='FFFFFF'; } + $tmpval=(! empty($tmppart[0]) ? $tmppart[0] : 0)+(! empty($tmppart[1]) ? $tmppart[1] : 0)+(! empty($tmppart[2]) ? $tmppart[2] : 0); + if ($tmpval <= 460) { $colortexttitle='FFFFFF'; $colorshadowtitle='888888'; } + else { $colortexttitle='000000'; $colorshadowtitle='FFFFFF'; } } $colorbacktabcard1=join(',',colorStringToArray($colorbacktabcard1)); // Normalize value to 'x,y,z' @@ -248,7 +251,8 @@ body { trans("DIRECTION").";\n"; ?> } -th a, .thumbstat, a.tab { color: rgb() !important; font-weight: bold !important; } +.thumbstat, a.tab { color: rgb() !important; font-weight: bold !important; } +th a { font-weight: !important; } a.tab { font-weight: bold !important; } a:link, a:visited, a:hover, a:active { font-family: ; font-weight: normal; color: rgb(); text-decoration: none; } @@ -343,17 +347,61 @@ input.smallpadd { /* Used for timesheet input */ input.buttongen { vertical-align: middle; } +input.buttonpayment { + min-width: 290px; + margin-bottom: 15px; + background-image: none; + line-height: 24px; + padding: 8px; + background: none; + padding-left: 30px; + text-align: ; + border: 2px solid #666666; +} +input.buttonpaymentcb { + background-image: url(); + background-size: 26px; + background-repeat: no-repeat; + background-position: 2px 11px; +} +input.buttonpaymentcheque { + background-image: url(); + background-size: 24px; + background-repeat: no-repeat; + background-position: 2px 8px; +} +input.buttonpaymentpaypal { + background-image: url(); + background-repeat: no-repeat; + background-position: 8px 11px; +} +input.buttonpaymentpaybox { + background-image: url(); + background-repeat: no-repeat; + background-position: 8px 11px; +} +input.buttonpaymentstripe { + background-image: url(); + background-repeat: no-repeat; + background-position: 8px 11px; +} +/* Used by timesheets */ span.timesheetalreadyrecorded input { border: none; border-bottom: solid 1px rgba(0,0,0,0.4); margin-right: 1px !important; } - +td.onholidaymorning, td.onholidayafternoon { + background-color: #fdf6f2; +} +td.onholidayallday { + background-color: #f4eede; +} select.flat, form.flat select { font-weight: normal; } .optionblue { - color: rgb() !important; + color: rgb(); } .select2-results .select2-highlighted.optionblue { color: #FFF !important; @@ -399,21 +447,26 @@ input:-webkit-autofill { ::-moz-placeholder { color:#bbb; } /* firefox 19+ */ :-ms-input-placeholder { color:#ccc; } /* ie */ input:-moz-placeholder { color:#ccc; } -input[name=weight], input[name=volume], input[name=surface], input[name=sizeheight] { margin-right: 6px; } +input[name=weight], input[name=volume], input[name=surface], input[name=sizeheight], select[name=incoterm_id] { margin-right: 6px; } input[name=surface] { margin-right: 4px; } fieldset { border: 1px solid #AAAAAA !important; } .legendforfieldsetstep { padding-bottom: 10px; } +.trextrafieldseparator td { + border-bottom: 2px solid rgb(120,120,120) !important; +} hr { border: 0; border-top: 1px solid #ccc; } .button, .buttonDelete, input[name="sbmtConnexion"] { + margin-bottom: 0; + margin-top: 0; + margin-left: 5px; + margin-right: 5px; font-family: ; border-color: #c5c5c5; border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); display: inline-block; padding: 3px 14px; - margin-bottom: 0; - margin-top: 0; text-align: center; cursor: pointer; text-decoration: none !important; @@ -436,9 +489,9 @@ hr { border: 0; border-top: 1px solid #ccc; } border-radius: 2px; } .button:focus, .buttonDelete:focus { - -moz-box-shadow: 0px 0px 6px 1px rgba(0, 0, 60, 0.2), 0px 0px 0px rgba(60,60,60,0.1); - -webkit-box-shadow: 0px 0px 6px 1px rgba(0, 0, 60, 0.2), 0px 0px 0px rgba(60,60,60,0.1); - box-shadow: 0px 0px 6px 1px rgba(0, 0, 60, 0.2), 0px 0px 0px rgba(60,60,60,0.1); + -moz-box-shadow: 0px 0px 5px 1px rgba(0, 0, 60, 0.2), 0px 0px 0px rgba(60,60,60,0.1); + -webkit-box-shadow: 0px 0px 5px 1px rgba(0, 0, 60, 0.2), 0px 0px 0px rgba(60,60,60,0.1); + box-shadow: 0px 0px 5px 1px rgba(0, 0, 60, 0.2), 0px 0px 0px rgba(60,60,60,0.1); } .button:hover, .buttonDelete:hover { /* warning: having a larger shadow has side effect when button is completely on left of a table */ @@ -528,6 +581,9 @@ textarea.centpercent { .right { text-align: ; } +.justify { + text-align: justify; +} .nowrap { white-space: ; } @@ -558,6 +614,9 @@ textarea.centpercent { .cursormove { cursor: move; } +.cursornotallowed { + cursor: not-allowed; +} .badge { display: inline-block; min-width: 10px; @@ -604,6 +663,10 @@ div.myavailability { padding-top: 4px; padding-bottom: 4px; } +.paddingtopbottom { + padding-top: 10px; + padding-bottom: 10px; +} .checkallactions { /* vertical-align: text-bottom; margin-top: 6px; */ @@ -638,8 +701,8 @@ div.myavailability { text-overflow: ellipsis; white-space: nowrap; } -.tdoverflowmax200 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 200px; +.tdoverflowmax150 { /* For tdoverflow, the max-midth become a minimum ! */ + max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -680,7 +743,9 @@ div.myavailability { margin-top: 6px; margin-bottom: 12px; } - +#builddoc_form ~ .showlinkedobjectblock { + margin-top: 20px; +} /* For the long description of module */ .moduledesclong p img, .moduledesclong p a img { @@ -717,6 +782,9 @@ div.fiche>form>div.div-table-responsive, div.fiche>form>div.div-table-responsive div.fiche>form>div.div-table-responsive { min-height: 392px; } +div.fiche>div.tabBar>form>div.div-table-responsive { + min-height: 392px; +} .flexcontainer { browser->name, array('chrome','firefox'))) echo 'display: inline-flex;'."\n"; ?> @@ -739,6 +807,13 @@ div.fiche>form>div.div-table-responsive { align-self: flex-start; } +select.selectarrowonleft { + direction: rtl; +} +select.selectarrowonleft option { + direction: ltr; +} + /* ============================================================================== */ /* Styles to hide objects */ @@ -773,6 +848,7 @@ div.fiche>form>div.div-table-responsive { .maxwidth50 { max-width: 50px; } .maxwidth75 { max-width: 75px; } .maxwidth100 { max-width: 100px; } +.maxwidth125 { max-width: 125px; } .maxwidth150 { max-width: 150px; } .maxwidth200 { max-width: 200px; } .maxwidth300 { max-width: 300px; } @@ -787,6 +863,16 @@ div.fiche>form>div.div-table-responsive { .titlefieldmiddle { width: 50%; } .imgmaxwidth180 { max-width: 180px; } +.width20p { width:20%; } +.width25p { width:25%; } +.width40p { width:40%; } +.width50p { width:50%; } +.width60p { width:60%; } +.width75p { width:75%; } +.width80p { width:80%; } +.width100p { width:100%; } + + /* Force values for small screen 1400 */ @media only screen and (max-width: 1400px) { @@ -814,9 +900,21 @@ div.fiche>form>div.div-table-responsive { .minwidth500imp { min-width: 250px !important; } } +/* Force values for small screen 767 */ +@media only screen and (max-width: 767px) +{ + body { + font-size: px; + } +} + /* Force values for small screen 570 */ @media only screen and (max-width: 570px) { + body { + font-size: px; + } + .divmainbodylarge { margin-left: 20px !important; margin-right: 20px !important; } .tdoverflowonsmartphone { @@ -947,6 +1045,14 @@ td.showDragHandle { height: calc(100% - 50px);*/ } +global->THEME_DISABLE_STICKY_TOPMENU)) { ?> +.side-nav-vert { + position: sticky; + top: 0px; + z-index: 210; +} + + .side-nav { display: table-cell; border-right: 1px solid #d0d0d0; @@ -1018,12 +1124,12 @@ div.fiche { div.fiche { margin-: px; - margin-: dol_optimize_smallscreen)?'16':'12')); ?>px; + margin-: dol_optimize_smallscreen)?'20':'12')); ?>px; dol_hide_leftmenu) && ! empty($conf->dol_hide_topmenu)) print 'margin-top: 4px;'."\n"; ?> dol_hide_leftmenu)) print 'margin-bottom: 12px;'."\n"; ?> } body.onlinepaymentbody div.fiche { /* For online payment page */ - margin: 40px !important; + margin: 20px !important; } div.fiche>table:first-child { margin-bottom: 15px !important; @@ -1144,6 +1250,10 @@ div.attacharea { padding-top: 18px; padding-bottom: 10px; } +div.attachareaformuserfileecm { + padding-top: 0; + padding-bottom: 0; +} div.arearef { padding-top: 2px; @@ -1160,6 +1270,9 @@ div.heightref { div.divphotoref { padding-right: 20px; } +div.paginationref { + padding-bottom: 10px; +} div.statusref { float: right; padding-left: 12px; @@ -1224,21 +1337,6 @@ div#id-top { display:none; background: rgb(); - /*-webkit-box-shadow: 0 0 6px rgba(0,0,0,0.4); - box-shadow: 0 0 6px rgba(0,0,0,0.4); */ - /* - background-image: linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -o-linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -moz-linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -webkit-linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -ms-linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -webkit-gradient( linear, left top, left bottom, color-stop(0, rgba(255,255,255,.1)), color-stop(1, rgba(0,0,0,.4)) ); - */ - /* - height: 34px; - - height: px; - */ } @@ -1310,15 +1408,6 @@ ul.tmenu { /* t r b l */ display: table; } ul.tmenu li { /* We need this to have background color when menu entry wraps on new lines */ - /* background: rgb(); - /* - background-image: linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -o-linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -moz-linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -webkit-linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -ms-linear-gradient(top, rgba(255,255,255,.1) 0%, rgba(0,0,0,.4) 100%); - background-image: -webkit-gradient( linear, left top, left bottom, color-stop(0, rgba(255,255,255,.1)), color-stop(1, rgba(0,0,0,.4)) ); - */ } li.tmenu, li.tmenusel { @@ -1418,6 +1507,10 @@ div.mainmenu.home{ background-position-x: center; } +div.mainmenu.billing { + background-image: url(); +} + div.mainmenu.accountancy { background-image: url(); } @@ -1479,7 +1572,7 @@ div.mainmenu.tools { background-image: url(); } -div.mainmenu.websites { +div.mainmenu.website { background-image: url(); } @@ -1503,7 +1596,7 @@ $mainmenuusedarray=array_unique(explode(',',$mainmenuused)); $generic=1; // Put here list of menu entries when the div.mainmenu.menuentry was previously defined -$divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','ftp','holiday','hrm','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','stripe','webservices','websites'); +$divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','ftp','holiday','hrm','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','stripe','webservices','website'); // Put here list of menu entries we are sure we don't want $divnotrequired=array('multicurrency','salaries','margin','opensurvey','paybox','expensereport','incoterm','prelevement','propal','workflow','notification','supplier_proposal','cron','product','productbatch','expedition'); foreach($mainmenuusedarray as $val) @@ -1662,11 +1755,14 @@ table.login_table_securitycode tr td { max-height: 90px; } +div.backgroundsemitransparent { + background:rgba(255,255,255,0.6); +} div.login_block { position: absolute; text-align: ; - : 5px; - top: 4px; + : 0; + top: 0; font-weight: bold; max-width: px; @@ -1693,6 +1789,7 @@ div.login a:hover { } div.login_block_user { display: inline-block; + padding-top: 3px; global->THEME_TOPMENU_DISABLE_IMAGE)) { ?> min-width: 120px; @@ -1957,26 +2054,8 @@ td.ecmroot { } .largebutton { - /*background-image: -o-linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - background-image: -moz-linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - background-image: -webkit-linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - background-image: -ms-linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - background-image: linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - - background: #FFF; - background-repeat: repeat-x !important; - */ - border-top: 1px solid #CCC !important; - - /*-moz-border-radius: 4px 4px 4px 4px !important; - -webkit-border-radius: 4px 4px 4px 4px !important; - border-radius: 4px 4px 4px 4px !important; - -moz-box-shadow: 2px 2px 4px #DDD; - -webkit-box-shadow: 2px 2px 4px #DDD; - box-shadow: 2px 2px 4px #DDD; - */ - - padding: 10px 4px 14px 4px !important; + /* border-top: 1px solid #CCC !important; */ + padding: 0px 4px 14px 4px !important; min-height: 32px; } @@ -2010,7 +2089,9 @@ div.tabs { div.tabsElem { margin-top: 1px; } /* To avoid overlap of tabs when not browser */ - +div.tabsElem a { + font-weight: normal !important; +} div.tabBar { color: #; padding-top: 16px; @@ -2023,7 +2104,7 @@ div.tabBar { background: rgb(); } div.tabBar div.titre { - padding-top: 10px; + padding-top: 20px; } div.tabBarWithBottom { @@ -2152,7 +2233,7 @@ span.butAction, span.butActionDelete { .butAction, .butAction:link, .butAction:visited, .butAction:hover, .butAction:active, .butActionDelete, .butActionDelete:link, .butActionDelete:visited, .butActionDelete:hover, .butActionDelete:active { text-decoration: none; - margin: 0em em; + margin: 0em em !important; padding: 0.6em em; font-family: ; font-weight: normal; @@ -2369,6 +2450,7 @@ table.liste th, table.noborder th, table.noborder tr.liste_titre td, table.nobor } table.liste td, table.noborder td, div.noborder form div { padding: 7px 2px 7px 3px; /* t r b l */ + line-height: 1.2em; } div.liste_titre_bydiv .divsearchfield { padding: 2px 1px 2px 0px; /* t r b l */ @@ -2608,7 +2690,9 @@ td.evenodd, tr.nohoverpair td { background-color: # !important; background: # !important; } - +.trforbreak td { + background-color: # !important; +} table.dataTable td { padding: 5px 2px 5px 3px !important; @@ -2632,18 +2716,11 @@ tr.nobottom td, tr.nobottom , td.nobottom { div.liste_titre .tagtd { vertical-align: middle; } -/*div.liste_titre { - box-shadow: 2px 2px 4px #CCC; -}*/ div.liste_titre { min-height: 26px !important; /* We cant use height because it's a div and it should be higher if content is more. but min-height does not work either for div */ padding-top: 2px; padding-bottom: 2px; - -/* border-top-width: 1px; - border-top-color: #BBB; - border-top-style: solid;*/ } div.liste_titre_bydiv { border-top-width: px; @@ -2654,7 +2731,8 @@ div.liste_titre_bydiv { display: table; padding: 2px 0px 2px 0; box-shadow: none; - width: calc(100% - 1px); /* 1px more, i don't know why */ + /*width: calc(100% - 1px); 1px more, i don't know why so i remove */ + width: calc(100%); } tr.liste_titre, tr.liste_titre_sel, form.liste_titre, form.liste_titre_sel, table.dataTable.tr { @@ -2722,14 +2800,16 @@ input.liste_titre { line-height: 24px; } -.noborder tr.liste_total, .noborder tr.liste_total td, tr.liste_total, form.liste_total { - /* height: 32px; */ +.noborder tr.liste_total td, tr.liste_total td, form.liste_total div, .noborder tr.liste_total_wrap td, tr.liste_total_wrap td, form.liste_total_wrap div { + color: #551188; + font-weight: normal; } .noborder tr.liste_total td, tr.liste_total td, form.liste_total div { - color: #552266; - font-weight: normal; white-space: nowrap; } +.noborder tr.liste_total_wrap td, tr.liste_total_wrap td, form.liste_total_wrap div { + white-space: normal; +} form.liste_total div { border-top: 1px solid #DDDDDD; } @@ -2894,13 +2974,11 @@ span.dashboardlineko { float: right; position: relative; text-align: right; - top: -24px; - padding: 1px 2px 1px 2px; + top: -26px; + padding: 0px 5px 0px 5px; border-radius: .25em; background-color: #9f4705; - padding: 0px 5px 0px 5px; - top: -26px; } .imglatecoin { padding: 1px 3px 1px 1px; @@ -2998,11 +3076,12 @@ div.warning { color: #302020; padding: 0.3em 0.3em 0.3em 0.3em; margin: 0.5em 0em 0.5em 0em; - border: 1px solid #e0d0b0; + /* border: 1px solid #e0d0b0; */ + border: 2px solid #805000; -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px; - background: #EFDF9A; + /* background: #EFDF9A; */ text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); } @@ -3103,17 +3182,16 @@ td.legendLabel { padding: 2px 2px 2px 0 !important; } div.titre { font-family: ; - font-size: 14px; - font-weight: bold; + font-size: 1.1em; + /* font-weight: bold; */ color: rgb(); text-decoration: none; padding-top: 5px; padding-bottom: 5px; - /* text-shadow: 1px 1px 2px #FFFFFF; */ } -#dolpaymenttable { width: 600px; font-size: 13px; } -#tablepublicpayment { border: 1px solid #CCCCCC !important; width: 100%; } +#dolpaymenttable { min-width: 310px; font-size: 16px; } /* Width must have min to make stripe input area visible */ +#tablepublicpayment { border: 1px solid #CCCCCC !important; width: 100%; padding: 20px; } #tablepublicpayment .CTableRow1 { background-color: #F0F0F0 !important; } #tablepublicpayment tr.liste_total { border-bottom: 1px solid #CCCCCC !important; } #tablepublicpayment tr.liste_total td { border-top: none; } @@ -3173,6 +3251,19 @@ div.titre { font-size: px !important; } + +/* ============================================================================== */ +/* For content of image preview */ +/* ============================================================================== */ + +/* +.ui-dialog-content.ui-widget-content > object { + max-height: none; + width: auto; margin-left: auto; margin-right: auto; display: block; +} +*/ + + /* ============================================================================== */ /* Formulaire confirmation (When HTML is used) */ /* ============================================================================== */ @@ -3200,30 +3291,29 @@ table.valid { /* Tooltips */ /* ============================================================================== */ -#tooltip { - position: absolute; - width: px; +/* For tooltip using dialog */ +.ui-dialog.highlight.ui-widget.ui-widget-content.ui-front { + z-index: 3000; +} + +div.ui-tooltip { + max-width: px !important; +} +.mytooltip { border-top: solid 1px #BBBBBB; border-: solid 1px #BBBBBB; border-: solid 1px #444444; border-bottom: solid 1px #444444; - padding: 2px; - z-index: 3000; - background-color: #FFF; - opacity: 1; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; -} -#tiptip_content { - -moz-border-radius:0px; - -webkit-border-radius: 0px; - border-radius: 0px; - background-color: rgb(255,255,255); - line-height: 1.4em; - min-width: 200px; + padding: 5px 20px; + border-radius: 0; + box-shadow: 0 0 4px grey; + margin: 2px; + font-stretch: condensed; } + + + /* ============================================================================== */ /* Calendar */ /* ============================================================================== */ @@ -3233,6 +3323,8 @@ img.datecallink { padding-left: 2px !important; padding-right: 2px !important; } .ui-datepicker-trigger { vertical-align: middle; cursor: pointer; + padding-left: 2px; + padding-right: 2px; } .bodyline { @@ -3371,6 +3463,9 @@ a.websitebuttonsitepreview img { width: 26px; display: inline-block; } +a.websitebuttonsitepreviewdisabled img { + opacity: 0.2; +} .websitehelp { vertical-align: middle; float: right; @@ -3382,6 +3477,10 @@ a.websitebuttonsitepreview img { /* Module agenda */ /* ============================================================================== */ +.dayevent .tagtr:first-of-type { + height: 24px; +} + .agendacell { height: 60px; } table.cal_month { border-spacing: 0px; } table.cal_month td:first-child { border-left: 0px; } @@ -3406,7 +3505,7 @@ table.cal_month td:last-child { border-right: 0px; } .cal_today_peruser_impair { background: #F8F8F0; } .peruser_busy { background: #CC8888; } .peruser_notbusy { background: #EEDDDD; opacity: 0.5; } -table.cal_event { border: none; border-collapse: collapse; margin-bottom: 1px; -webkit-border-radius: 6px; border-radius: 6px; min-height: 20px; } +table.cal_event { border: none; border-collapse: collapse; margin-bottom: 1px; min-height: 20px; } table.cal_event td { border: none; padding-: 2px; padding-: 2px; padding-top: 0px; padding-bottom: 0px; } table.cal_event td.cal_event { padding: 4px 4px !important; } table.cal_event td.cal_event_right { padding: 4px 4px !important; } @@ -3449,21 +3548,6 @@ table.cal_event td.cal_event_right { padding: 4px 4px !important; } cursor:pointer; } -/* ============================================================================== */ -/* Gantt -/* ============================================================================== */ - -div.gTaskInfo { - background: #f0f0f0 !important; -} -.gtaskblue { - background: rgb(108,152,185) !important; -} -td.gtaskname { - overflow: hidden; - text-overflow: ellipsis; -} - /* ============================================================================== */ /* jQuery - jeditable */ @@ -3701,6 +3785,34 @@ a.cke_dialog_ui_button_ok span { } +/* ============================================================================== */ +/* ACE editor */ +/* ============================================================================== */ +.ace_editor { + border: 1px solid #ddd; + margin: 0; +} +.aceeditorstatusbar { + margin: 0; + padding: 0; + left: 0; + right: 0; + bottom: 0; + height: 20px; + background-color: #ebebeb; + color: #666; +} +.ace_status-indicator { + color: gray; + position: relative; + right: 0; + border-left: 1px solid; +} +pre#editfilecontentaceeditorid { + margin-top: 5px; +} + + /* ============================================================================== */ /* File upload */ /* ============================================================================== */ @@ -3744,6 +3856,58 @@ a.cke_dialog_ui_button_ok span { } +/* ============================================================================== */ +/* Comments */ +/* ============================================================================== */ + +#comment div { + box-sizing:border-box; +} +#comment .comment { + border-radius:7px; + margin-bottom:10px; + overflow:hidden; +} +#comment .comment-table { + display:table; + height:100%; +} +#comment .comment-cell { + display:table-cell; +} +#comment .comment-info { + font-size:0.8em; + border-right:1px solid #dedede; + margin-right:10px; + width:160px; + text-align:center; + background:rgba(255,255,255,0.5); + vertical-align:middle; + padding:10px 2px; +} +#comment .comment-info a { + color:inherit; +} +#comment .comment-right { + vertical-align:top; +} +#comment .comment-description { + padding:10px; + vertical-align:top; +} +#comment .comment-delete { + width: 100px; + text-align:center; + vertical-align:middle; +} +#comment .comment-delete:hover { + background:rgba(250,20,20,0.8); +} +#comment textarea { + width: 100%; +} + + /* ============================================================================== */ /* JSGantt */ @@ -3753,6 +3917,44 @@ div.scroll2 { width: px !important; } +.gtaskname div, .gtaskname { + font-size: unset !important; +} +div.gantt, .gtaskheading, .gmajorheading, .gminorheading, .gminorheadingwkend { + font-size: unset !important; + font-weight: normal !important; + color: #000 !important; +} +div.gTaskInfo { + background: #f0f0f0 !important; +} +.gtaskblue { + background: rgb(108,152,185) !important; +} +.gtaskgreen { + background: rgb(160,173,58) !important; +} +td.gtaskname { + overflow: hidden; + text-overflow: ellipsis; +} +td.gminorheadingwkend { + color: #888 !important; +} +td.gminorheading { + color: #666 !important; +} +.gtaskname div, .gtaskname { + min-width: 200px !important; + max-width: 200px !important; + width: 200px !important; +} +.gpccomplete div, .gpccomplete { + min-width: 40px !important; + max-width: 40px !important; + width: 40px !important; +} + /* ============================================================================== */ /* jFileTree */ @@ -3867,6 +4069,12 @@ div#ecm-layout-center { padding-left: 10px !important; padding-right: 10px !important; } +.jnotify-container .jnotify-notification .jnotify-message { + font-weight: normal; +} +.jnotify-container .jnotify-notification-warning .jnotify-close, .jnotify-container .jnotify-notification-warning .jnotify-message { + color: #a28918 !important; +} /* use or not ? */ div.jnotify-background { @@ -3987,6 +4195,9 @@ div.dataTables_length select { /* Select2 */ /* ============================================================================== */ +.select2-container--default .select2-selection--single .select2-selection__rendered { + color: unset; +} .select2-default { color: #999 !important; /*opacity: 0.2;*/ @@ -4025,10 +4236,39 @@ div.dataTables_length select { .select2-drop.select2-drop-above { box-shadow: none !important; } +.select2-container--open .select2-dropdown--above { + border-bottom: solid 1px rgba(0,0,0,.2); +} .select2-drop.select2-drop-above.select2-drop-active { border-top: 1px solid #ccc; border-bottom: solid 1px rgba(0,0,0,.2); } +.select2-container--default .select2-selection--single +{ + outline: none; + border-top: none; + border-left: none; + border-right: none; + border-bottom: solid 1px rgba(0,0,0,.2); + -webkit-box-shadow: none !important; + box-shadow: none !important; + border-radius: 0 !important; +} +.select2-container--default .select2-selection--multiple { + border: solid 1px rgba(0,0,0,.2); + border-radius: 0 !important; +} +.select2-search__field +{ + outline: none; + border-top: none !important; + border-left: none !important; + border-right: none !important; + border-bottom: solid 1px rgba(0,0,0,.2) !important; + -webkit-box-shadow: none !important; + box-shadow: none !important; + border-radius: 0 !important; +} .select2-container-active .select2-choice, .select2-container-active .select2-choices { outline: none; @@ -4094,9 +4334,6 @@ a span.select2-chosen .select2-results { max-height: 400px; } -.css-searchselectcombo ul.select2-results { - max-height: none; -} .select2-container.select2-container-disabled .select2-choice, .select2-container-multi.select2-container-disabled .select2-choices { background-color: #FFFFFF; background-image: none; @@ -4118,13 +4355,22 @@ a span.select2-chosen border-left: none; } - +.select2-container--default .select2-results>.select2-results__options{ + max-height: 400px; +} /* Special case for the select2 add widget */ #addbox .select2-container .select2-choice > .select2-chosen, #actionbookmark .select2-container .select2-choice > .select2-chosen { - text-align: left; + text-align: ; opacity: 0.4; } +span#select2-boxbookmark-container, span#select2-boxcombo-container { + text-align: ; + opacity: 0.5; +} +.select2-container .select2-selection--single .select2-selection__rendered { + padding-left: 6px; +} /* Style used before the select2 js is executed on boxcombo */ #boxbookmark.boxcombo, #boxcombo.boxcombo { text-align: left; @@ -4226,7 +4472,7 @@ dl.dropdown { } .dropdown ul { margin: -1px 0 0 0; - text-align: left; + text-align: ; } .dropdown dd { position:relative; @@ -4245,7 +4491,7 @@ dl.dropdown { background-color: #FFF; border: 1px solid #888; display:none; - right:0px; /* pop is align on right */ + :0px; /* pop is align on right */ padding: 2px 15px 2px 5px; position:absolute; top:2px; @@ -4262,7 +4508,7 @@ dl.dropdown { padding: 2px; } .dropdown dd ul li input[type="checkbox"] { - margin-right: 3px; + margin-: 3px; } .dropdown dd ul li a, .dropdown dd ul li span { padding: 3px; @@ -4695,21 +4941,24 @@ div.tabsElem a.tab { } div.login_block { browser->layout == 'phone' && ((GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))) { ?> + /* Style when phone layout or when using the menuhider */ display: none; padding-top: 20px; padding-left: 20px; padding-right: 20px; + padding-bottom: 16px; - padding-top: 10px; + padding-top: 5px; padding-left: 5px; padding-right: 5px; + padding-bottom: 5px; top: inherit !important; left: 0 !important; text-align: center; vertical-align: middle; background: #FFF; - height: 42px; + height: 50px; z-index: 202; min-width: 190px; diff --git a/htdocs/theme/md/ckeditor/config.js b/htdocs/theme/md/ckeditor/config.js index e0374f6b271..b70e371fcfb 100644 --- a/htdocs/theme/md/ckeditor/config.js +++ b/htdocs/theme/md/ckeditor/config.js @@ -34,8 +34,8 @@ CKEDITOR.editorConfig = function( config ) [ ['Templates','NewPage'], ['Save'], - ['Source','Maximize','Preview'], - ['PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'], // 'Cut','Copy','Paste','-', are useless, can be done with right click, even on smarpthone + ['Maximize','Preview'], + ['PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'], // 'Cut','Copy','Paste','-', are useless, can be done with right click, even on smarpthone ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['CreateDiv','ShowBlocks'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], @@ -46,51 +46,57 @@ CKEDITOR.editorConfig = function( config ) ['Link','Unlink','Anchor'], ['Image','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe'], ['Styles','Format','Font','FontSize'], - ['TextColor','BGColor'] + ['TextColor','BGColor'], + ['Source'] ]; // Used for mailing fields config.toolbar_dolibarr_mailings = [ - ['Source','Maximize','Preview'], - ['SpellChecker', 'Scayt'], // 'Cut','Copy','Paste','-', are useless, can be done with right click, even on smarpthone + ['Maximize','Preview'], + ['SpellChecker', 'Scayt'], ['Undo','Redo','-','Find','Replace'], + ['CreateDiv','ShowBlocks'], ['Format','Font','FontSize'], ['Bold','Italic','Underline','Strike','Subscript','Superscript','-','TextColor','RemoveFormat'], - ['NumberedList','BulletedList','Outdent','Indent','CreateDiv'], + ['NumberedList','BulletedList','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], - ['Link','Unlink','Anchor','Image','Table','HorizontalRule','SpecialChar'] + ['Link','Unlink','Anchor','Image','Table','HorizontalRule','SpecialChar'], + ['Source'] ]; // Used for notes fields config.toolbar_dolibarr_notes = [ - ['Source','Maximize'], + ['Maximize'], ['SpellChecker', 'Scayt'], // 'Cut','Copy','Paste','-', are useless, can be done with right click, even on smarpthone ['Undo','Redo','-','Find','Replace'], ['Format','Font','FontSize'], ['Bold','Italic','Underline','Strike','Subscript','Superscript','-','TextColor','RemoveFormat'], ['NumberedList','BulletedList','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], - ['Link','Unlink','Image','Table','HorizontalRule','SpecialChar'] + ['Link','Unlink','Image','Table','HorizontalRule','SpecialChar'], + ['Source'] ]; // Used for details lines config.toolbar_dolibarr_details = [ - ['Source','Maximize'], + ['Maximize'], ['SpellChecker', 'Scayt'], // 'Cut','Copy','Paste','-', are useless, can be done with right click, even on smarpthone ['Format','Font','FontSize'], - ['Bold','Italic','Underline','Strike','-','TextColor','RemoveFormat'], // ,'Subscript','Superscript' useless + ['Bold','Italic','Underline','Strike','-','TextColor','RemoveFormat'], // ,'Subscript','Superscript' useless ['NumberedList','BulletedList','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], - ['Link','Unlink','SpecialChar'] + ['Link','Unlink','SpecialChar'], + ['Source'] ]; // Used for mailing fields config.toolbar_dolibarr_readonly = [ - ['Source','Maximize'], - ['Find'] + ['Maximize'], + ['Find'], + ['Source'] ]; }; diff --git a/htdocs/theme/md/img/object_phoning_mobile.png b/htdocs/theme/md/img/object_phoning_mobile.png new file mode 100644 index 00000000000..c94fd72ae14 Binary files /dev/null and b/htdocs/theme/md/img/object_phoning_mobile.png differ diff --git a/htdocs/theme/md/img/object_website.png b/htdocs/theme/md/img/object_website.png new file mode 100644 index 00000000000..4c4a2e48c29 Binary files /dev/null and b/htdocs/theme/md/img/object_website.png differ diff --git a/htdocs/theme/md/img/off.png b/htdocs/theme/md/img/off.png deleted file mode 100644 index 9bab123aca7..00000000000 Binary files a/htdocs/theme/md/img/off.png and /dev/null differ diff --git a/htdocs/theme/md/img/on.png b/htdocs/theme/md/img/on.png deleted file mode 100644 index 7d0344d4dbb..00000000000 Binary files a/htdocs/theme/md/img/on.png and /dev/null differ diff --git a/htdocs/theme/md/img/working2.gif b/htdocs/theme/md/img/working2.gif deleted file mode 100644 index bf0fc8f2167..00000000000 Binary files a/htdocs/theme/md/img/working2.gif and /dev/null differ diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php index f4966a105b7..7e785373a75 100644 --- a/htdocs/theme/md/style.css.php +++ b/htdocs/theme/md/style.css.php @@ -48,6 +48,7 @@ $colorbacklineimpair2='255,255,255'; // line impair $colorbacklinepair1='250,250,250'; // line pair $colorbacklinepair2='248,248,248'; // line pair $colorbacklinepairhover='244,244,244'; // line pair +$colorbacklinebreak='214,218,220'; $colorbackbody='248,248,248'; $colortexttitlenotab='90,90,90'; $colortexttitle='20,20,20'; @@ -107,8 +108,10 @@ $borderwith=2; // Case of option always editable if (! isset($conf->global->THEME_ELDY_BACKBODY)) $conf->global->THEME_ELDY_BACKBODY=$colorbackbody; if (! isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) $conf->global->THEME_ELDY_TOPMENU_BACK1=$colorbackhmenu1; +if (! isset($conf->global->THEME_ELDY_VERMENU_BACK1)) $conf->global->THEME_ELDY_VERMENU_BACK1=$colorbackvmenu1; if (! isset($conf->global->THEME_ELDY_BACKTITLE1)) $conf->global->THEME_ELDY_BACKTITLE1=$colorbacktitle1; if (! isset($conf->global->THEME_ELDY_USE_HOVER)) $conf->global->THEME_ELDY_USE_HOVER==$colorbacklinepairhover; +if (! isset($conf->global->THEME_ELDY_LINEBREAK)) $conf->global->THEME_ELDY_LINEBREAK=$colorbacklinebreak; if (! isset($conf->global->THEME_ELDY_TEXTTITLENOTAB)) $conf->global->THEME_ELDY_TEXTTITLENOTAB=$colortexttitlenotab; if (! isset($conf->global->THEME_ELDY_TEXTLINK)) $conf->global->THEME_ELDY_TEXTLINK=$colortextlink; @@ -136,6 +139,7 @@ $colorbacklineimpair1=empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty( $colorbacklineimpair2=empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_LINEIMPAIR2) ?$colorbacklineimpair2:$conf->global->THEME_ELDY_LINEIMPAIR2):(empty($user->conf->THEME_ELDY_LINEIMPAIR2)?$colorbacklineimpair2:$user->conf->THEME_ELDY_LINEIMPAIR2); $colorbacklinepair1 =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_LINEPAIR1) ?$colorbacklinepair1:$conf->global->THEME_ELDY_LINEPAIR1) :(empty($user->conf->THEME_ELDY_LINEPAIR1)?$colorbacklinepair1:$user->conf->THEME_ELDY_LINEPAIR1); $colorbacklinepair2 =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_LINEPAIR2) ?$colorbacklinepair2:$conf->global->THEME_ELDY_LINEPAIR2) :(empty($user->conf->THEME_ELDY_LINEPAIR2)?$colorbacklinepair2:$user->conf->THEME_ELDY_LINEPAIR2); +$colorbacklinebreak =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_LINEBREAK) ?$colorbacklinebreak:$conf->global->THEME_ELDY_LINEBREAK) :(empty($user->conf->THEME_ELDY_LINEBREAK)?$colorbacklinebreak:$user->conf->THEME_ELDY_LINEBREAK); $colorbackbody =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_BACKBODY) ?$colorbackbody:$conf->global->THEME_ELDY_BACKBODY) :(empty($user->conf->THEME_ELDY_BACKBODY)?$colorbackbody:$user->conf->THEME_ELDY_BACKBODY); $colortexttitlenotab =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_TEXTTITLENOTAB)?$colortexttitlenotab:$conf->global->THEME_ELDY_TEXTTITLENOTAB) :(empty($user->conf->THEME_ELDY_TEXTTITLENOTAB)?$colortexttitlenotab:$user->conf->THEME_ELDY_TEXTTITLENOTAB); $colortexttitle =empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED)?(empty($conf->global->THEME_ELDY_TEXTTITLE) ?$colortext:$conf->global->THEME_ELDY_TEXTTITLE) :(empty($user->conf->THEME_ELDY_TEXTTITLE)?$colortexttitle:$user->conf->THEME_ELDY_TEXTTITLE); @@ -340,17 +344,72 @@ input.smallpadd { /* Used for timesheet input */ input.buttongen { vertical-align: middle; } +input.buttonpayment { + min-width: 290px; + margin-bottom: 15px; + background-image: none; + line-height: 24px; + padding: 8px; + background: none; + padding-left: 30px; + text-align: ; + border: 2px solid #666666; +} +input.buttonpaymentcb { + background-image: url(); + background-size: 26px; + background-repeat: no-repeat; + background-position: 5px 5px; +} +input.buttonpaymentcheque { + background-image: url(); + background-repeat: no-repeat; + background-position: 8px 7px; +} +input.buttonpaymentcb { + background-image: url(); + background-size: 24px; + background-repeat: no-repeat; + background-position: 5px 4px; +} +input.buttonpaymentcheque { + background-image: url(); + background-repeat: no-repeat; + background-position: 5px 4px; +} +input.buttonpaymentpaypal { + background-image: url(); + background-repeat: no-repeat; + background-position: 8px 7px; +} +input.buttonpaymentpaybox { + background-image: url(); + background-repeat: no-repeat; + background-position: 8px 7px; +} +input.buttonpaymentstripe { + background-image: url(); + background-repeat: no-repeat; + background-position: 8px 7px; +} +/* Used for timesheets */ span.timesheetalreadyrecorded input { border: none; border-bottom: solid 1px rgba(0,0,0,0.1); margin-right: 1px !important; } +td.onholidaymorning, td.onholidayafternoon { + background-color: #fdf6f2; +} +td.onholidayallday { + background-color: #f4eede; +} select.flat, form.flat select { font-weight: normal; } .optionblue { - color: rgb() !important; + color: rgb(); } .select2-results .select2-highlighted.optionblue { color: #FFF !important; @@ -398,7 +457,8 @@ input:-webkit-autofill { ::-moz-placeholder { color:#bbb; } /* firefox 19+ */ :-ms-input-placeholder { color:#ccc; } /* ie */ input:-moz-placeholder { color:#ccc; } - +input[name=weight], input[name=volume], input[name=surface], input[name=sizeheight], select[name=incoterm_id] { margin-right: 6px; } +input[name=surface] { margin-right: 4px; } fieldset { border: 1px solid #AAAAAA !important; } .legendforfieldsetstep { padding-bottom: 10px; } @@ -527,6 +587,9 @@ textarea.centpercent { .right { text-align: ; } +.justify { + text-align: justify; +} .nowrap { white-space: ; } @@ -557,6 +620,9 @@ textarea.centpercent { .cursormove { cursor: move; } +.cursornotallowed { + cursor: not-allowed; +} .badge { display: inline-block; min-width: 10px; @@ -604,6 +670,10 @@ div.myavailability { padding-top: 4px; padding-bottom: 4px; } +.paddingtopbottom { + padding-top: 10px; + padding-bottom: 10px; +} .checkallactions { /*vertical-align: text-bottom; margin-top: 6px;*/ @@ -638,8 +708,8 @@ div.myavailability { text-overflow: ellipsis; white-space: nowrap; } -.tdoverflowmax200 { /* For tdoverflow, the max-midth become a minimum ! */ - max-width: 200px; +.tdoverflowmax150 { /* For tdoverflow, the max-midth become a minimum ! */ + max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -680,7 +750,9 @@ div.myavailability { margin-top: 6px; margin-bottom: 12px; } - +#builddoc_form ~ .showlinkedobjectblock { + margin-top: 20px; +} /* For the long description of module */ .moduledesclong p img,.moduledesclong p a img { @@ -739,6 +811,13 @@ div.fiche>form>div.div-table-responsive { align-self: flex-start; } +select.selectarrowonleft { + direction: rtl; +} +select.selectarrowonleft option { + direction: ltr; +} + /* ============================================================================== */ /* Styles to hide objects */ @@ -773,6 +852,7 @@ div.fiche>form>div.div-table-responsive { .maxwidth50 { max-width: 50px; } .maxwidth75 { max-width: 75px; } .maxwidth100 { max-width: 100px; } +.maxwidth125 { max-width: 125px; } .maxwidth150 { max-width: 150px; } .maxwidth200 { max-width: 200px; } .maxwidth300 { max-width: 300px; } @@ -815,9 +895,21 @@ div.fiche>form>div.div-table-responsive { .minwidth500imp { min-width: 100px !important; } } +/* Force values for small screen 767 */ +@media only screen and (max-width: 767px) +{ + body { + font-size: px; + } +} + /* Force values for small screen 570 */ @media only screen and (max-width: 570px) { + body { + font-size: px; + } + .divmainbodylarge { margin-left: 20px; margin-right: 20px; } .tdoverflowonsmartphone { @@ -1029,6 +1121,10 @@ div.login_block { top: auto; z-index: 90; } + +div.backgroundsemitransparent { + background:rgba(255,255,255,0.6); +} div.login_block { /* position: initial !important;*/ display: none; @@ -1058,6 +1154,9 @@ div.fiche { dol_hide_leftmenu) && ! empty($conf->dol_hide_topmenu)) print 'margin-top: 4px;'; ?> margin-bottom: 15px; } +body.onlinepaymentbody div.fiche { /* For online payment page */ + margin: 20px !important; +} div.fichecenter { width: 100%; clear: both; /* This is to have div fichecenter that are true rectangles */ @@ -1181,6 +1280,10 @@ div.attacharea { padding-top: 18px; padding-bottom: 10px; } +div.attachareaformuserfileecm { + padding-top: 0; + padding-bottom: 0; +} div.arearef { padding-top: 2px; padding-bottom: 5px; @@ -1196,6 +1299,9 @@ div.heightref { div.divphotoref { padding-right: 20px; } +div.paginationref { + padding-bottom: 10px; +} div.statusref { float: right; padding-left: 12px; @@ -1442,6 +1548,10 @@ div.mainmenu.home{ background-position-x: center; } +div.mainmenu.billing { + background-image: url(); +} + div.mainmenu.accountancy { background-image: url(); } @@ -1503,7 +1613,7 @@ div.mainmenu.tools { background-image: url(); } -div.mainmenu.websites { +div.mainmenu.website { background-image: url(); } @@ -1527,7 +1637,7 @@ $mainmenuusedarray=array_unique(explode(',',$mainmenuused)); $generic=1; // Put here list of menu entries when the div.mainmenu.menuentry was previously defined -$divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','ftp','holiday','hrm','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','stripe','webservices','websites'); +$divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','ftp','holiday','hrm','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','stripe','webservices','website'); // Put here list of menu entries we are sure we don't want $divnotrequired=array('multicurrency','salaries','margin','opensurvey','paybox','expensereport','incoterm','prelevement','propal','workflow','notification','supplier_proposal','cron','product','productbatch','expedition'); foreach($mainmenuusedarray as $val) @@ -1960,25 +2070,8 @@ td.ecmroot { } .largebutton { - /*background-image: -o-linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - background-image: -moz-linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - background-image: -webkit-linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - background-image: -ms-linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - background-image: linear-gradient(bottom, rgba(200,200,200,0.1) 0%, rgba(255,255,255,0.3) 120%) !important; - - background: #FFF; - background-repeat: repeat-x !important; - */ - border-top: 1px solid #CCC !important; - - /*-moz-border-radius: 2px 2px 2px 2px !important; - -webkit-border-radius: 2px 2px 2px 2px !important; - border-radius: 2px 2px 2px 2px !important; - -moz-box-shadow: 2px 2px 4px #f4f4f4; - -webkit-box-shadow: 2px 2px 4px #f4f4f4; - box-shadow: 2px 2px 4px #f4f4f4;*/ - - padding: 10px 4px 14px 4px !important; + /* border-top: 1px solid #CCC !important; */ + padding: 0px 4px 14px 4px !important; min-height: 32px; } @@ -2006,8 +2099,12 @@ div.tabs { clear:both; height:100%; } -div.tabsElem { margin-top: 6px; } /* To avoid overlap of tabs when not browser */ - +div.tabsElem { + margin-top: 6px; +} /* To avoid overlap of tabs when not browser */ +div.tabsElem a { + font-weight: normal !important; +} div.tabBar { color: #; padding-top: 16px; @@ -2372,6 +2469,10 @@ td.border, div.tagtable div div.border { .ficheaddleft table.noborder { margin: 0px 0px 0px 0px; } +.liste_titre_bydiv { + border-right: 1px solid #ccc; + border-left: 1px solid #ccc; +} table.liste, table.noborder, table.formdoc, div.noborder { width: 100%; @@ -2386,6 +2487,9 @@ table.liste, table.noborder, table.formdoc, div.noborder { border-bottom-color: #BBB; border-bottom-style: solid; + border-right: 1px solid #ccc; + border-left: 1px solid #ccc; + margin: 0px 0px 8px 0px; -moz-border-radius: 0.1em; @@ -2691,6 +2795,9 @@ td.evenodd, tr.nohoverpair td { background-color: # !important; background: # !important; } +.trforbreak td { + background-color: # !important; +} table.dataTable td { padding: 5px 2px 5px 3px !important; @@ -2741,7 +2848,7 @@ div.liste_titre_bydiv { border-collapse: collapse; display: table; padding: 2px 0px 2px 0; - width: 100%; + width: calc(100% - 1px); } tr.liste_titre, tr.liste_titre_sel, form.liste_titre, form.liste_titre_sel, table.dataTable.tr { @@ -2762,7 +2869,7 @@ tr.liste_titre th, tr.liste_titre td, th.liste_titre border-bottom: 1px solid #aaa; } /* TODO Once title line is moved under title search, make border bottom of all th black and force to whit when it's first tr */ -tr:first-child th.liste_titre { +tr:first-child th.liste_titre, tr:first-child th.liste_titre_sel { border-bottom: 1px solid #FFF ! important; } tr.liste_titre th, th.liste_titre, tr.liste_titre td, td.liste_titre, form.liste_titre div, div.liste_titre @@ -2809,16 +2916,21 @@ input.liste_titre { border: 0px; } -.noborder tr.liste_total, .noborder tr.liste_total td, tr.liste_total, form.liste_total { - /* height: 32px; */ -} -.noborder tr.liste_total td, tr.liste_total td, form.liste_total div { - /* border-top: 1px solid #f4f4f4; */ +.noborder tr.liste_total td, tr.liste_total td, form.liste_total div, .noborder tr.liste_total_wrap td, tr.liste_total_wrap td, form.liste_total_wrap div { color: #332266; font-weight: normal; - white-space: nowrap; padding: 4px; } +.noborder tr.liste_total td, tr.liste_total td, form.liste_total div { + white-space: nowrap; + line-height: 1.5em; +} +} +.noborder tr.liste_total_wrap td, tr.liste_total_wrap td, form.liste_total_wrap div { + white-space: normal; +} + + tr.liste_sub_total, tr.liste_sub_total td { border-bottom: 2px solid #aaa; } @@ -3068,11 +3180,12 @@ div.warning { color: #302020; padding: 0.3em 0.3em 0.3em 0.3em; margin: 0.5em 0em 0.5em 0em; - border: 1px solid #e0d0b0; + /* border: 1px solid #e0d0b0; */ + border: 2px solid #805000 -moz-border-radius:3px; -webkit-border-radius: 3px; border-radius: 3px; - background: #EFDF9A; + /* background: #EFDF9A; */ text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); } @@ -3186,8 +3299,8 @@ div.titre { dol_optimize_smallscreen)?'':'margin-top: 4px;'); ?> } -#dolpaymenttable { width: 600px; font-size: 13px; } -#tablepublicpayment { border: 1px solid #CCCCCC !important; width: 100%; } +#dolpaymenttable { min-width: 320px; font-size: 16px; } /* Width must have min to make stripe input area visible */ +#tablepublicpayment { border: 1px solid #CCCCCC !important; width: 100%; padding: 20px; } #tablepublicpayment .CTableRow1 { background-color: #F0F0F0 !important; } #tablepublicpayment tr.liste_total { border-bottom: 1px solid #CCCCCC !important; } #tablepublicpayment tr.liste_total td { border-top: none; } @@ -3274,33 +3387,29 @@ table.valid { /* Tooltips */ /* ============================================================================== */ -#tooltip { -position: absolute; -width: px; -border-top: solid 1px #BBBBBB; -border-: solid 1px #BBBBBB; -border-: solid 1px #444444; -border-bottom: solid 1px #444444; -padding: 2px; -z-index: 3000; -background-color: #EFCFAA; -opacity: 1; --moz-border-radius:0px; --webkit-border-radius: 0px; -border-radius: 0px; +/* For tooltip using dialog */ +.ui-dialog.highlight.ui-widget.ui-widget-content.ui-front { + z-index: 3000; } -#tiptip_content { --moz-border-radius:0px; --webkit-border-radius: 0px; -border-radius: 0px; -background-color: rgb(255,255,255); -/* background-color: rgb(252,248,246); - background-color: rgba(252,248,246,0.95);*/ - line-height: 1.4em; - min-width: 200px; +div.ui-tooltip { + max-width: px !important; } +.mytooltip { + width: px; + border-top: solid 1px #BBBBBB; + border-: solid 1px #BBBBBB; + border-: solid 1px #444444; + border-bottom: solid 1px #444444; + padding: 5px 20px; + border-radius: 0; + box-shadow: 0 0 4px grey; + margin: 2px; + font-stretch: condensed; +} + + /* ============================================================================== */ /* Calendar */ /* ============================================================================== */ @@ -3310,6 +3419,8 @@ img.datecallink { padding-left: 2px !important; padding-right: 2px !important; } .ui-datepicker-trigger { vertical-align: middle; cursor: pointer; + padding-left: 2px; + padding-right: 2px; } .bodyline { @@ -3447,6 +3558,9 @@ a.websitebuttonsitepreview img { width: 26px; display: inline-block; } +a.websitebuttonsitepreviewdisabled img { + opacity: 0.2; +} .websiteiframenoborder { border: 0px; } @@ -3460,6 +3574,9 @@ a.websitebuttonsitepreview img { /* Module agenda */ /* ============================================================================== */ +.dayevent .tagtr:first-of-type { + height: 24px; +} .agendacell { height: 60px; } table.cal_month { border-spacing: 0px; } table.cal_month td:first-child { border-left: 0px; } @@ -3777,6 +3894,33 @@ a.cke_dialog_ui_button_ok span { } +/* ============================================================================== */ +/* ACE editor */ +/* ============================================================================== */ +.ace_editor { + border: 1px solid #ddd; + margin: 0; +} +.aceeditorstatusbar { + margin: 0; + padding: 0; + left: 0; + right: 0; + bottom: 0; + height: 20px; + color: #666; +} +.ace_status-indicator { + color: gray; + position: relative; + right: 0; + border-left: 1px solid; +} +pre#editfilecontentaceeditorid { + margin-top: 5px; +} + + /* ============================================================================== */ /* File upload */ /* ============================================================================== */ @@ -3947,6 +4091,12 @@ div#ecm-layout-center { padding-left: 10px !important; padding-right: 10px !important; } +.jnotify-container .jnotify-notification .jnotify-message { + font-weight: normal; +} +.jnotify-container .jnotify-notification-warning .jnotify-close, .jnotify-container .jnotify-notification-warning .jnotify-message { + color: #a28918 !important; +} /* use or not ? */ div.jnotify-background { @@ -4068,6 +4218,9 @@ div.dataTables_length select { /* Select2 */ /* ============================================================================== */ +.select2-container--default .select2-selection--single .select2-selection__rendered { + color: unset; +} .select2-container .select2-choice { border-bottom: 1px solid #ccc; } @@ -4103,10 +4256,39 @@ div.dataTables_length select { .select2-drop.select2-drop-above { box-shadow: none !important; } +.select2-container--open .select2-dropdown--above { + border-bottom: solid 1px rgba(0,0,0,.2); +} .select2-drop.select2-drop-above.select2-drop-active { border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; } +.select2-container--default .select2-selection--single +{ + outline: none; + border-top: none; + border-left: none; + border-right: none; + border-bottom: solid 1px rgba(0,0,0,.2); + -webkit-box-shadow: none !important; + box-shadow: none !important; + border-radius: 0 !important; +} +.select2-container--default .select2-selection--multiple { + border: solid 1px rgba(0,0,0,.2); + border-radius: 0 !important; +} +.select2-search__field +{ + outline: none; + border-top: none !important; + border-left: none !important; + border-right: none !important; + border-bottom: solid 1px rgba(0,0,0,.2) !important; + -webkit-box-shadow: none !important; + box-shadow: none !important; + border-radius: 0 !important; +} .select2-container-active .select2-choice, .select2-container-active .select2-choices { outline: none; @@ -4172,9 +4354,6 @@ a span.select2-chosen .select2-results { max-height: 400px; } -.css-searchselectcombo ul.select2-results { - max-height: none; -} .select2-container.select2-container-disabled .select2-choice, .select2-container-multi.select2-container-disabled .select2-choices { background-color: #FFFFFF; background-image: none; @@ -4195,14 +4374,24 @@ a span.select2-chosen border-top: none; border-left: 1px solid #ddd; } +.select2-container--default .select2-results>.select2-results__options{ + max-height: 400px; +} /* Special case for the select2 add widget */ #addbox .select2-container .select2-choice > .select2-chosen, #actionbookmark .select2-container .select2-choice > .select2-chosen { - text-align: left; + text-align: ;; opacity: 0.3; } +span#select2-boxbookmark-container, span#select2-boxcombo-container { + text-align: ; + opacity: 0.5; +} +.select2-container .select2-selection--single .select2-selection__rendered { + padding-left: 6px; +} /* Style used before the select2 js is executed on boxcombo */ #boxbookmark.boxcombo, #boxcombo.boxcombo { text-align: left; diff --git a/htdocs/user/admin/group_extrafields.php b/htdocs/user/admin/group_extrafields.php index 8dad702935f..0f11c3cd141 100644 --- a/htdocs/user/admin/group_extrafields.php +++ b/htdocs/user/admin/group_extrafields.php @@ -38,7 +38,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/user/admin/user_extrafields.php b/htdocs/user/admin/user_extrafields.php index 28bf22da654..b38f64c4600 100644 --- a/htdocs/user/admin/user_extrafields.php +++ b/htdocs/user/admin/user_extrafields.php @@ -37,7 +37,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/user/agenda_extsites.php b/htdocs/user/agenda_extsites.php index 255b476eb61..5b9e62c21df 100644 --- a/htdocs/user/agenda_extsites.php +++ b/htdocs/user/agenda_extsites.php @@ -68,7 +68,8 @@ if (($object->id != $user->id) && (! $user->rights->user->user->lire)) accessforbidden(); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('usercard','globalcard')); +$contextpage=array('usercard','useragenda','globalcard'); +$hookmanager->initHooks($contextpage); /* * Actions diff --git a/htdocs/user/bank.php b/htdocs/user/bank.php index b71a5ccdf18..0f26169adf3 100644 --- a/htdocs/user/bank.php +++ b/htdocs/user/bank.php @@ -30,12 +30,19 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/userbankaccount.class.php'; +if (! empty($conf->holiday->enabled)) require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; +if (! empty($conf->expensereport->enabled)) require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +if (! empty($conf->salaries->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; $langs->load("companies"); $langs->load("commercial"); $langs->load("banks"); $langs->load("bills"); +$langs->load("trips"); +$langs->load("holiday"); +$langs->load("salaries"); $id = GETPOST('id','int'); $bankid = GETPOST('bankid','int'); @@ -198,7 +205,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco dol_banner_tab($object,'id',$linkback,$user->rights->user->user->lire || $user->admin); - print '
    '; + print '
    '; print '
    '; @@ -282,7 +289,178 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco print '
    '.$langs->trans("RIBControlError").'
    '; } - print "
    "; + print '
    '; + + // Nbre max d'elements des petites listes + $MAXLIST=$conf->global->MAIN_SIZE_SHORTLIST_LIMIT; + + /* + * Last salaries + */ + if (! empty($conf->salaries->enabled) && + ($user->rights->salaries->read || ($user->rights->salaries->read && $object->id == $user->id)) + ) + { + $salary = new PaymentSalary($db); + + $sql = "SELECT ps.rowid, ps.datesp, ps.dateep, ps.amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as ps"; + $sql.= " WHERE ps.fk_user = ".$object->id; + $sql.= " AND ps.entity = ".$conf->entity; + $sql.= " ORDER BY ps.datesp DESC"; + + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + + print ''; + + print ''; + print ''; + print ''; + + $i = 0; + while ($i < $num && $i < $MAXLIST) + { + $objp = $db->fetch_object($resql); + + print ''; + print '\n"; + print '\n"; + print ''; + $i++; + } + $db->free($resql); + + if ($num <= 0) print '
    '; + print '
    '.$langs->trans("LastSalaries",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllSalaries").' '.$num.'
    '; + $salary->id = $objp->rowid; + $salary->ref = $objp->rowid; + + print $salary->getNomUrl(1); + print ''.dol_print_date($db->jdate($objp->datesp),'day')."'.dol_print_date($db->jdate($objp->dateep),'day')."'.price($objp->amount).'
    '.$langs->trans("None").''; + print "
    "; + } + else + { + dol_print_error($db); + } + } + + /* + * Last holidays + */ + if (! empty($conf->holiday->enabled) && + ($user->rights->holiday->read_all || ($user->rights->holiday->read && $object->id == $user->id)) + ) + { + $holiday = new Holiday($db); + + $sql = "SELECT h.rowid, h.statut, h.fk_type, h.date_debut, h.date_fin, h.halfday"; + $sql.= " FROM ".MAIN_DB_PREFIX."holiday as h"; + $sql.= " WHERE h.fk_user = ".$object->id; + $sql.= " AND h.entity = ".$conf->entity; + $sql.= " ORDER BY h.date_debut DESC"; + + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + + print ''; + + print ''; + print ''; + print ''; + + $i = 0; + while ($i < $num && $i < $MAXLIST) + { + $objp = $db->fetch_object($resql); + + print ''; + print '\n"; + print ''; + print ''; + $i++; + } + $db->free($resql); + + if ($num <= 0) print '
    '; + print '
    '.$langs->trans("LastHolidays",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllHolidays").' '.$num.'
    '; + $holiday->id = $objp->rowid; + $holiday->ref = $objp->rowid; + $holiday->fk_type = $objp->fk_type; + $nbopenedday=num_open_day($db->jdate($objp->date_debut), $db->jdate($objp->date_fin), 0, 1, $objp->halfday); + + print $holiday->getNomUrl(1); + print ''.dol_print_date($db->jdate($objp->date_debut),'day')."'.$nbopenedday.' '.$langs->trans('DurationDays').''.$holiday->LibStatut($objp->statut,5).'
    '.$langs->trans("None").''; + print "
    "; + } + else + { + dol_print_error($db); + } + } + + /* + * Last expense report + */ + if (! empty($conf->expensereport->enabled) && + ($user->rights->expensereport->readall || ($user->rights->expensereport->lire && $object->id == $user->id)) + ) + { + $exp = new ExpenseReport($db); + + $sql = "SELECT e.rowid, e.ref, e.fk_statut, e.date_debut, e.total_ttc"; + $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as e"; + $sql.= " WHERE e.fk_user_author = ".$object->id; + $sql.= " AND e.entity = ".$conf->entity; + $sql.= " ORDER BY e.date_debut DESC"; + + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + + print ''; + + print ''; + print ''; + print ''; + + $i = 0; + while ($i < $num && $i < $MAXLIST) + { + $objp = $db->fetch_object($resql); + + print ''; + print '\n"; + print ''; + print ''; + $i++; + } + $db->free($resql); + + if ($num <= 0) print '
    '; + print '
    '.$langs->trans("LastExpenseReports",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllExpenseReports").' '.$num.'
    '; + $exp->id = $objp->rowid; + $exp->ref = $objp->ref; + $exp->fk_type = $objp->fk_type; + + print $exp->getNomUrl(1); + print ''.dol_print_date($db->jdate($objp->date_debut),'day')."'.price($objp->total_ttc).''.$exp->LibStatut($objp->fk_statut,5).'
    '.$langs->trans("None").''; + print "
    "; + } + else + { + dol_print_error($db); + } + } + + print '
    '; + print '
    '; dol_fiche_end(); diff --git a/htdocs/user/card.php b/htdocs/user/card.php index 846c9dffc9a..5532bb8137b 100644 --- a/htdocs/user/card.php +++ b/htdocs/user/card.php @@ -45,23 +45,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; if (! empty($conf->ldap->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; if (! empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -if (! empty($conf->multicompany->enabled)) dol_include_once('/multicompany/class/actions_multicompany.class.php'); if (! empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $id = GETPOST('id','int'); -$action = GETPOST('action','alpha'); +$action = GETPOST('action','aZ09'); $mode = GETPOST('mode','alpha'); -$confirm = GETPOST('confirm','alpha'); +$confirm = GETPOST('confirm','alpha'); $subaction = GETPOST('subaction','alpha'); $group = GETPOST("group","int",3); -$cancel = GETPOST('cancel'); - -// Users/Groups management only in master entity if transverse mode -if (($action == 'create' || $action == 'adduserldap') && ! empty($conf->multicompany->enabled) && $conf->entity > 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) -{ - accessforbidden(); -} +$cancel = GETPOST('cancel','alpha'); // Define value to know what current user can do on users $canadduser=(! empty($user->admin) || $user->rights->user->user->creer); @@ -72,17 +64,17 @@ $canreadgroup=$canreaduser; $caneditgroup=$canedituser; if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { - $canreadgroup=(! empty($user->admin) || $user->rights->user->group_advance->read); - $caneditgroup=(! empty($user->admin) || $user->rights->user->group_advance->write); + $canreadgroup=(! empty($user->admin) || $user->rights->user->group_advance->read); + $caneditgroup=(! empty($user->admin) || $user->rights->user->group_advance->write); } // Define value to know what current user can do on properties of edited user if ($id) { - // $user est le user qui edite, $id est l'id de l'utilisateur edite - $caneditfield=((($user->id == $id) && $user->rights->user->self->creer) - || (($user->id != $id) && $user->rights->user->user->creer)); - $caneditpassword=((($user->id == $id) && $user->rights->user->self->password) - || (($user->id != $id) && $user->rights->user->user->password)); + // $user est le user qui edite, $id est l'id de l'utilisateur edite + $caneditfield=((($user->id == $id) && $user->rights->user->self->creer) + || (($user->id != $id) && $user->rights->user->user->creer)); + $caneditpassword=((($user->id == $id) && $user->rights->user->self->password) + || (($user->id != $id) && $user->rights->user->user->password)); } // Security check @@ -108,7 +100,8 @@ $extrafields = new ExtraFields($db); $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array -$hookmanager->initHooks(array('usercard','globalcard')); +$contextpage=array('usercard','globalcard'); +$hookmanager->initHooks($contextpage); @@ -116,7 +109,7 @@ $hookmanager->initHooks(array('usercard','globalcard')); * Actions */ -$parameters=array('id'=>$socid); +$parameters=array('id' => $id, 'socid' => $socid, 'group' => $group, 'caneditgroup' => $caneditgroup); $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'); @@ -197,6 +190,8 @@ if (empty($reshook)) { $object->login = GETPOST("login", 'alpha'); $object->api_key = GETPOST("api_key", 'alpha'); $object->gender = GETPOST("gender", 'alpha'); + $birth = dol_mktime(0, 0, 0, GETPOST('birthmonth'), GETPOST('birthday'), GETPOST('birthyear')); + $object->birth = $birth; $object->admin = GETPOST("admin", 'alpha'); $object->address = GETPOST('address', 'alpha'); $object->zip = GETPOST('zipcode', 'alpha'); @@ -214,7 +209,7 @@ if (empty($reshook)) { $object->note = GETPOST("note"); $object->ldap_sid = GETPOST("ldap_sid"); $object->fk_user = GETPOST("fk_user") > 0 ? GETPOST("fk_user") : 0; - $object->employee = GETPOST('employee'); + $object->employee = GETPOST('employee'); $object->thm = GETPOST("thm") != '' ? GETPOST("thm") : ''; $object->tjm = GETPOST("tjm") != '' ? GETPOST("tjm") : ''; @@ -246,7 +241,7 @@ if (empty($reshook)) { } } else { $object->entity = ($entity == '' ? 1 : $entity); - /*if ($user->admin && $user->entity == 0 && GETPOST("admin",'alpha')) + /*if ($user->admin && $user->entity == 0 && GETPOST("admin",'alpha')) { }*/ } @@ -258,9 +253,9 @@ if (empty($reshook)) { if (GETPOST('password')) { $object->setPassword($user, GETPOST('password')); } - if (! empty($conf->categorie->enabled)) { + if (! empty($conf->categorie->enabled)) { // Categories association - $usercats = GETPOST( 'usercats', 'array' ); + $usercats = GETPOST('usercats', 'array'); $object->setCategories($usercats); } $db->commit(); @@ -279,7 +274,7 @@ if (empty($reshook)) { } // Action add usergroup - if (($action == 'addgroup' || $action == 'removegroup') && $caneditfield) + if (($action == 'addgroup' || $action == 'removegroup') && $caneditgroup) { if ($group) { @@ -289,10 +284,10 @@ if (empty($reshook)) { $object->fetch($id); if ($action == 'addgroup') { - $object->SetInGroup($group, (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) ? GETPOST('entity', 'int') : $editgroup->entity)); + $result = $object->SetInGroup($group, $editgroup->entity); } if ($action == 'removegroup') { - $object->RemoveFromGroup($group, (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) ? GETPOST('entity', 'int') : $editgroup->entity)); + $result = $object->RemoveFromGroup($group, $editgroup->entity); } if ($result > 0) { @@ -337,6 +332,8 @@ if (empty($reshook)) { $object->firstname = GETPOST("firstname", 'alpha'); $object->login = GETPOST("login", 'alpha'); $object->gender = GETPOST("gender", 'alpha'); + $birth = dol_mktime(0, 0, 0, GETPOST('birthmonth'), GETPOST('birthday'), GETPOST('birthyear')); + $object->birth = $birth; $object->pass = GETPOST("password"); $object->api_key = (GETPOST("api_key", 'alpha')) ? GETPOST("api_key", 'alpha') : $object->api_key; if (! empty($user->admin)) $object->admin = GETPOST("admin"); // admin flag can only be set/unset by an admin user. A test is also done later when forging sql request @@ -461,8 +458,8 @@ if (empty($reshook)) { if (!$result > 0) { setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors'); } else { - // Create thumbs - $object->addThumbs($newfile); + // Create thumbs + $object->addThumbs($newfile); } } else { $error ++; @@ -472,12 +469,12 @@ if (empty($reshook)) { } } - if (! $error && ! count($object->errors)) - { - // Then we add the associated categories - $categories = GETPOST( 'usercats', 'array' ); - $object->setCategories($categories); - } + if (! $error && ! count($object->errors)) + { + // Then we add the associated categories + $categories = GETPOST('usercats', 'array'); + $object->setCategories($categories); + } if (!$error && !count($object->errors)) { setEventMessages($langs->trans("UserModified"), null, 'mesgs'); @@ -492,123 +489,123 @@ if (empty($reshook)) { } } else { - $db->rollback(); + $db->rollback(); } - } - } + } + } else { - if ($caneditpassword) // Case we can edit only password - { - dol_syslog("Not allowed to change fields, only password"); + if ($caneditpassword) // Case we can edit only password + { + dol_syslog("Not allowed to change fields, only password"); - $object->fetch($id); + $object->fetch($id); - $object->oldcopy = clone $object; + $object->oldcopy = clone $object; - $ret = $object->setPassword($user, GETPOST("password")); - if ($ret < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $ret = $object->setPassword($user, GETPOST("password")); + if ($ret < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } } // Change password with a new generated one - if ((($action == 'confirm_password' && $confirm == 'yes') - || ($action == 'confirm_passwordsend' && $confirm == 'yes')) && $caneditpassword - ) { - $object->fetch($id); + if ((($action == 'confirm_password' && $confirm == 'yes') + || ($action == 'confirm_passwordsend' && $confirm == 'yes')) && $caneditpassword + ) { + $object->fetch($id); - $newpassword = $object->setPassword($user, ''); - if ($newpassword < 0) { - // Echec - setEventMessages($langs->trans("ErrorFailedToSetNewPassword"), null, 'errors'); - } else { - // Succes - if ($action == 'confirm_passwordsend' && $confirm == 'yes') { - if ($object->send_password($user, $newpassword) > 0) - { - setEventMessages($langs->trans("PasswordChangedAndSentTo", $object->email), null, 'mesgs'); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - else - { - setEventMessages($langs->trans("PasswordChangedTo", $newpassword), null, 'warnings'); - } - } - } + $newpassword = $object->setPassword($user, ''); + if ($newpassword < 0) { + // Echec + setEventMessages($langs->trans("ErrorFailedToSetNewPassword"), null, 'errors'); + } else { + // Succes + if ($action == 'confirm_passwordsend' && $confirm == 'yes') { + if ($object->send_password($user, $newpassword) > 0) + { + setEventMessages($langs->trans("PasswordChangedAndSentTo", $object->email), null, 'mesgs'); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + else + { + setEventMessages($langs->trans("PasswordChangedTo", $newpassword), null, 'warnings'); + } + } + } // Action initialisation donnees depuis record LDAP - if ($action == 'adduserldap') { - $selecteduser = $_POST['users']; + if ($action == 'adduserldap') { + $selecteduser = $_POST['users']; - $required_fields = array( - $conf->global->LDAP_KEY_USERS, - $conf->global->LDAP_FIELD_NAME, - $conf->global->LDAP_FIELD_FIRSTNAME, - $conf->global->LDAP_FIELD_LOGIN, - $conf->global->LDAP_FIELD_LOGIN_SAMBA, - $conf->global->LDAP_FIELD_PASSWORD, - $conf->global->LDAP_FIELD_PASSWORD_CRYPTED, - $conf->global->LDAP_FIELD_PHONE, - $conf->global->LDAP_FIELD_FAX, - $conf->global->LDAP_FIELD_MOBILE, - $conf->global->LDAP_FIELD_SKYPE, - $conf->global->LDAP_FIELD_MAIL, - $conf->global->LDAP_FIELD_TITLE, - $conf->global->LDAP_FIELD_DESCRIPTION, - $conf->global->LDAP_FIELD_SID - ); + $required_fields = array( + $conf->global->LDAP_KEY_USERS, + $conf->global->LDAP_FIELD_NAME, + $conf->global->LDAP_FIELD_FIRSTNAME, + $conf->global->LDAP_FIELD_LOGIN, + $conf->global->LDAP_FIELD_LOGIN_SAMBA, + $conf->global->LDAP_FIELD_PASSWORD, + $conf->global->LDAP_FIELD_PASSWORD_CRYPTED, + $conf->global->LDAP_FIELD_PHONE, + $conf->global->LDAP_FIELD_FAX, + $conf->global->LDAP_FIELD_MOBILE, + $conf->global->LDAP_FIELD_SKYPE, + $conf->global->LDAP_FIELD_MAIL, + $conf->global->LDAP_FIELD_TITLE, + $conf->global->LDAP_FIELD_DESCRIPTION, + $conf->global->LDAP_FIELD_SID + ); - $ldap = new Ldap(); - $result = $ldap->connect_bind(); - if ($result >= 0) { - // Remove from required_fields all entries not configured in LDAP (empty) and duplicated - $required_fields = array_unique(array_values(array_filter($required_fields, "dol_validElement"))); + $ldap = new Ldap(); + $result = $ldap->connect_bind(); + if ($result >= 0) { + // Remove from required_fields all entries not configured in LDAP (empty) and duplicated + $required_fields = array_unique(array_values(array_filter($required_fields, "dol_validElement"))); - $ldapusers = $ldap->getRecords($selecteduser, $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields); - //print_r($ldapusers); + $ldapusers = $ldap->getRecords($selecteduser, $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields); + //print_r($ldapusers); - if (is_array($ldapusers)) { - foreach ($ldapusers as $key => $attribute) { - $ldap_lastname = $attribute[$conf->global->LDAP_FIELD_NAME]; - $ldap_firstname = $attribute[$conf->global->LDAP_FIELD_FIRSTNAME]; - $ldap_login = $attribute[$conf->global->LDAP_FIELD_LOGIN]; - $ldap_loginsmb = $attribute[$conf->global->LDAP_FIELD_LOGIN_SAMBA]; - $ldap_pass = $attribute[$conf->global->LDAP_FIELD_PASSWORD]; - $ldap_pass_crypted = $attribute[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED]; - $ldap_phone = $attribute[$conf->global->LDAP_FIELD_PHONE]; - $ldap_fax = $attribute[$conf->global->LDAP_FIELD_FAX]; - $ldap_mobile = $attribute[$conf->global->LDAP_FIELD_MOBILE]; - $ldap_skype = $attribute[$conf->global->LDAP_FIELD_SKYPE]; - $ldap_mail = $attribute[$conf->global->LDAP_FIELD_MAIL]; - $ldap_sid = $attribute[$conf->global->LDAP_FIELD_SID]; - } - } - } - else - { - setEventMessages($ldap->error, $ldap->errors, 'errors'); - } - } + if (is_array($ldapusers)) { + foreach ($ldapusers as $key => $attribute) { + $ldap_lastname = $attribute[$conf->global->LDAP_FIELD_NAME]; + $ldap_firstname = $attribute[$conf->global->LDAP_FIELD_FIRSTNAME]; + $ldap_login = $attribute[$conf->global->LDAP_FIELD_LOGIN]; + $ldap_loginsmb = $attribute[$conf->global->LDAP_FIELD_LOGIN_SAMBA]; + $ldap_pass = $attribute[$conf->global->LDAP_FIELD_PASSWORD]; + $ldap_pass_crypted = $attribute[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED]; + $ldap_phone = $attribute[$conf->global->LDAP_FIELD_PHONE]; + $ldap_fax = $attribute[$conf->global->LDAP_FIELD_FAX]; + $ldap_mobile = $attribute[$conf->global->LDAP_FIELD_MOBILE]; + $ldap_skype = $attribute[$conf->global->LDAP_FIELD_SKYPE]; + $ldap_mail = $attribute[$conf->global->LDAP_FIELD_MAIL]; + $ldap_sid = $attribute[$conf->global->LDAP_FIELD_SID]; + } + } + } + else + { + setEventMessages($ldap->error, $ldap->errors, 'errors'); + } + } - // Actions to send emails - $trigger_name='USER_SENTBYMAIL'; - $paramname='id'; // Name of param key to open the card - $mode='emailfromuser'; - $trackid='use'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + // Actions to send emails + $trigger_name='USER_SENTBYMAIL'; + $paramname='id'; // Name of param key to open the card + $mode='emailfromuser'; + $trackid='use'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - // Actions to build doc - $upload_dir = $conf->user->dir_output; - $permissioncreate=$user->rights->user->user->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + // Actions to build doc + $upload_dir = $conf->user->dir_output; + $permissioncreate=$user->rights->user->user->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; } @@ -625,32 +622,32 @@ llxHeader('',$langs->trans("UserCard")); if ($action == 'create' || $action == 'adduserldap') { - /* ************************************************************************** */ - /* */ - /* Affichage fiche en mode creation */ - /* */ - /* ************************************************************************** */ + /* ************************************************************************** */ + /* */ + /* Affichage fiche en mode creation */ + /* */ + /* ************************************************************************** */ - print load_fiche_titre($langs->trans("NewUser")); + print load_fiche_titre($langs->trans("NewUser")); - print $langs->trans("CreateInternalUserDesc")."
    \n"; - print "
    "; + print $langs->trans("CreateInternalUserDesc")."
    \n"; + print "
    "; - if (! empty($conf->ldap->enabled) && (isset($conf->global->LDAP_SYNCHRO_ACTIVE) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')) - { - /* + if (! empty($conf->ldap->enabled) && (isset($conf->global->LDAP_SYNCHRO_ACTIVE) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')) + { + /* * Affiche formulaire d'ajout d'un compte depuis LDAP * si on est en synchro LDAP vers Dolibarr */ - $ldap = new Ldap(); - $result = $ldap->connect_bind(); - if ($result >= 0) - { - $required_fields=array( + $ldap = new Ldap(); + $result = $ldap->connect_bind(); + if ($result >= 0) + { + $required_fields=array( $conf->global->LDAP_KEY_USERS, - $conf->global->LDAP_FIELD_FULLNAME, + $conf->global->LDAP_FIELD_FULLNAME, $conf->global->LDAP_FIELD_NAME, $conf->global->LDAP_FIELD_FIRSTNAME, $conf->global->LDAP_FIELD_LOGIN, @@ -664,211 +661,219 @@ if ($action == 'create' || $action == 'adduserldap') $conf->global->LDAP_FIELD_MAIL, $conf->global->LDAP_FIELD_TITLE, $conf->global->LDAP_FIELD_DESCRIPTION, - $conf->global->LDAP_FIELD_SID - ); + $conf->global->LDAP_FIELD_SID + ); - // Remove from required_fields all entries not configured in LDAP (empty) and duplicated - $required_fields=array_unique(array_values(array_filter($required_fields, "dol_validElement"))); + // Remove from required_fields all entries not configured in LDAP (empty) and duplicated + $required_fields=array_unique(array_values(array_filter($required_fields, "dol_validElement"))); - // Get from LDAP database an array of results - $ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 1); + // Get from LDAP database an array of results + $ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 1); - if (is_array($ldapusers)) - { - $liste=array(); - foreach ($ldapusers as $key => $ldapuser) - { - // Define the label string for this user - $label=''; - foreach ($required_fields as $value) - { - if ($value) - { - $label.=$value."=".$ldapuser[$value]." "; - } - } - $liste[$key] = $label; - } + if (is_array($ldapusers)) + { + $liste=array(); + foreach ($ldapusers as $key => $ldapuser) + { + // Define the label string for this user + $label=''; + foreach ($required_fields as $value) + { + if ($value) + { + $label.=$value."=".$ldapuser[$value]." "; + } + } + $liste[$key] = $label; + } - } - else - { - setEventMessages($ldap->error, $ldap->errors, 'errors'); - } - } - else - { - setEventMessages($ldap->error, $ldap->errors, 'errors'); - } + } + else + { + setEventMessages($ldap->error, $ldap->errors, 'errors'); + } + } + else + { + setEventMessages($ldap->error, $ldap->errors, 'errors'); + } - // If user list is full, we show drop-down list - print "\n\n\n"; + // If user list is full, we show drop-down list + print "\n\n\n"; - print '
    '; - print ''; - print ''; - print ''; - print '
    '; - print $langs->trans("LDAPUsers"); - print ''; - print ''; - if (is_array($liste) && count($liste)) - { - print $form->selectarray('users', $liste, '', 1); - } - print ''; - print ''; - print '
    '; - print '
    '; + print '
    '; + print ''; + print ''; + print ''; + print '
    '; + print $langs->trans("LDAPUsers"); + print ''; + print ''; + if (is_array($liste) && count($liste)) + { + print $form->selectarray('users', $liste, '', 1); + print ajax_combobox('users'); + } + print ''; + print ''; + print '
    '; + print '
    '; - print "\n\n\n"; - print '
    '; - } + print "\n\n\n"; + print '
    '; + } - print '
    '; - print ''; - print ''; - if (! empty($ldap_sid)) print ''; - print ''; + print ''; + print ''; + print ''; + if (! empty($ldap_sid)) print ''; + print ''; - dol_fiche_head('', '', '', 0, ''); + dol_fiche_head('', '', '', 0, ''); - print dol_set_focus('#lastname'); + print dol_set_focus('#lastname'); - print ''; + print '
    '; - // Lastname - print ''; - print ''; - print ''; + // Lastname + print ''; + print ''; + print ''; - // Firstname - print ''; - print ''; + // Firstname + print ''; + print ''; // Employee - $defaultemployee=1; - print ''; - print ''; + $defaultemployee=1; + print ''; + print ''; - // Position/Job - print ''; - print ''; + // Position/Job + print ''; + print ''; - // Gender - print ''; - print ''; + // Gender + print ''; + print ''; - // Login - print ''; - print ''; + // Date employment + print ''; + print ''; + print "\n"; - $generated_password=''; - if (empty($ldap_sid)) // ldap_sid is for activedirectory - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $generated_password=getRandomPassword(false); - } - $password=$generated_password; + // Login + print ''; + print ''; - // Password - print ''; - print ''; + $generated_password=''; + if (empty($ldap_sid)) // ldap_sid is for activedirectory + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $generated_password=getRandomPassword(false); + } + $password=$generated_password; - if(! empty($conf->api->enabled)) - { - // API key - $generated_api_key = ''; - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $generated_password=getRandomPassword(false); - print ''; - print ''; - } - else - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - // PARTIAL WORKAROUND - $generated_fake_api_key=getRandomPassword(false); - print ''; - } + // Password + print ''; + print ''; - // Administrator - if (! empty($user->admin)) - { - print ''; - print ''; + print ''; + } + else + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + // PARTIAL WORKAROUND + $generated_fake_api_key=getRandomPassword(false); + print ''; + } - if (! empty($conf->multicompany->enabled) && ! $user->entity && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if (! empty($conf->use_javascript_ajax)) - { - print ''; - } - $checked=(GETPOST('superadmin', 'int')?' checked':''); - $disabled=(GETPOST('superadmin', 'int')?'':' disabled'); - print ' '.$langs->trans("SuperAdministrator"); - } - print "\n"; - } + } + $checked=(GETPOST('superadmin', 'int')?' checked':''); + $disabled=(GETPOST('superadmin', 'int')?'':' disabled'); + print ' '.$langs->trans("SuperAdministrator"); + } + print "\n"; + } - // Type - print ''; - print ''; + // Type + print ''; + print ''; - // Address - print ''; + // Address + print ''; print ''; + print $object->address; + print ''; - // Zip - print ''; + // Zip + print ''; // Town print ''; + print $formcompany->select_ziptown($object->town,'town',array('zipcode','selectcountry_id','state_id')); + print ''; - // Country - print ''; + // Country + print ''; - // State - if (empty($conf->global->USER_DISABLE_STATE)) - { - print ''; - } + // State + if (empty($conf->global->USER_DISABLE_STATE)) + { + print ''; + } - // Tel - print ''; - print ''; + // Tel + print ''; + print ''; - // Tel portable - print ''; - print ''; + // Tel portable + print ''; + print ''; - // Fax - print ''; - print ''; + // Fax + print ''; + print ''; - // Skype - if (! empty($conf->skype->enabled)) - { - print ''; - print ''; - } + // Skype + if (! empty($conf->skype->enabled)) + { + print ''; + print ''; + } - // EMail - print 'global->USER_MAIL_REQUIRED)?' class="fieldrequired"':'').'>'.$langs->trans("EMail").''; - print ''; + // EMail + print 'global->USER_MAIL_REQUIRED)?' class="fieldrequired"':'').'>'.$langs->trans("EMail").''; + print ''; - // Accountancy code - if ($conf->accounting->enabled) - { - print ''; - print ''; - } + // Accountancy code + if ($conf->accounting->enabled) + { + print ''; + print ''; + } - // TODO Move this into tab RH (HierarchicalResponsible must be on both tab) + // TODO Move this into tab RH (HierarchicalResponsible must be on both tab) - // Hierarchy - print ''; - print ''; - print "\n"; + // Hierarchy + print ''; + print ''; + print "\n"; - if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) - || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) + if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) + || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) { $langs->load("salaries"); - // THM - print ''; - print ''; - print "\n"; + print ''; + print ''; + print "\n"; - // TJM - print ''; - print ''; - print "\n"; + print ''; + print ''; + print "\n"; - // Salary - print ''; - print ''; - print "\n"; + // Salary + print ''; + print ''; + print "\n"; } - // Weeklyhours - print ''; - print ''; - print "\n"; + // Weeklyhours + print ''; + print ''; + print "\n"; - // Date employment - print ''; - print ''; + print ''; - print "\n"; + print "\n"; // User color if (! empty($conf->agenda->enabled)) @@ -1112,108 +1117,108 @@ if ($action == 'create' || $action == 'adduserldap') } */ - // Other attributes - $parameters=array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"'); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) - { - print $object->showOptionals($extrafields,'edit'); - } + // Other attributes + $parameters=array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"'); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (empty($reshook) && ! empty($extrafields->attribute_label)) + { + print $object->showOptionals($extrafields,'edit'); + } - // Note - print '\n"; + // Note + print '\n"; - // Signature - print ''; - print ''; + // Signature + print ''; + print ''; - print "
    '.$langs->trans("Lastname").''; - if (! empty($ldap_lastname)) - { - print ''; - print $ldap_lastname; - } - else - { - print ''; - } - print '
    '.$langs->trans("Lastname").''; + if (! empty($ldap_lastname)) + { + print ''; + print $ldap_lastname; + } + else + { + print ''; + } + print '
    '.$langs->trans("Firstname").''; - if (! empty($ldap_firstname)) - { - print ''; - print $ldap_firstname; - } - else - { - print ''; - } - print '
    '.$langs->trans("Firstname").''; + if (! empty($ldap_firstname)) + { + print ''; + print $ldap_firstname; + } + else + { + print ''; + } + print '
    '.$langs->trans('Employee').''; - print $form->selectyesno("employee",(GETPOST('employee')!=''?GETPOST('employee'):$defaultemployee),1); - print '
    '.$langs->trans('Employee').''; + print $form->selectyesno("employee",(GETPOST('employee')!=''?GETPOST('employee'):$defaultemployee),1); + print '
    '.$langs->trans("PostOrFunction").''; - print ''; - print '
    '.$langs->trans("PostOrFunction").''; + print ''; + print '
    '.$langs->trans("Gender").''; - $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); - print $form->selectarray('gender', $arraygender, GETPOST('gender'), 1); - print '
    '.$langs->trans("Gender").''; + $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); + print $form->selectarray('gender', $arraygender, GETPOST('gender'), 1); + print '
    '.$langs->trans("Login").''; - if (! empty($ldap_login)) - { - print ''; - print $ldap_login; - } - elseif (! empty($ldap_loginsmb)) - { - print ''; - print $ldap_loginsmb; - } - else - { - print ''; - } - print '
    '.$langs->trans("DateToBirth").''; + echo $form->select_date(GETPOST('birth'),'birth',0,0,1,'createuser',1,0,1); + print '
    '.$langs->trans("Login").''; + if (! empty($ldap_login)) + { + print ''; + print $ldap_login; + } + elseif (! empty($ldap_loginsmb)) + { + print ''; + print $ldap_loginsmb; + } + else + { + print ''; + } + print '
    '.$langs->trans("Password").''; - if (! empty($ldap_sid)) - { - print 'Mot de passe du domaine'; - } - else - { - if (! empty($ldap_pass)) - { - print ''; - print preg_replace('/./i','*',$ldap_pass); - } - else - { - // We do not use a field password but a field text to show new password to use. - print ''; - } - } - print '
    '.$langs->trans("ApiKey").''; - print ''; - if (! empty($conf->use_javascript_ajax)) - print ' '.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_api_key" class="linkobject"'); - print '
    '.$langs->trans("Password").''; + if (! empty($ldap_sid)) + { + print 'Mot de passe du domaine'; + } + else + { + if (! empty($ldap_pass)) + { + print ''; + print preg_replace('/./i','*',$ldap_pass); + } + else + { + // We do not use a field password but a field text to show new password to use. + print ''; + } + } + print '
    '.$langs->trans("Administrator").''; - print $form->selectyesno('admin',GETPOST('admin'),1); + if(! empty($conf->api->enabled)) + { + // API key + $generated_api_key = ''; + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $generated_password=getRandomPassword(false); + print '
    '.$langs->trans("ApiKey").''; + print ''; + if (! empty($conf->use_javascript_ajax)) + print ' '.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_api_key" class="linkobject"'); + print '
    '.$langs->trans("Type").''; - print $form->textwithpicto($langs->trans("Internal"),$langs->trans("InternalExternalDesc"), 1, 'help', '', 0, 2); - print '
    '.$langs->trans("Type").''; + print $form->textwithpicto($langs->trans("Internal"),$langs->trans("InternalExternalDesc"), 1, 'help', '', 0, 2); + print '
    '.fieldLabel('Address','address').'
    '.fieldLabel('Address','address').'
    '.fieldLabel('Zip','zipcode').''; - print $formcompany->select_ziptown($object->zip,'zipcode',array('town','selectcountry_id','state_id'),6); - print '
    '.fieldLabel('Zip','zipcode').''; + print $formcompany->select_ziptown($object->zip,'zipcode',array('town','selectcountry_id','state_id'),6); + print '
    '.fieldLabel('Town','town').''; - print $formcompany->select_ziptown($object->town,'town',array('zipcode','selectcountry_id','state_id')); - print '
    '.fieldLabel('Country','selectcountry_id').''; - print $form->select_country((GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id)); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - print '
    '.fieldLabel('Country','selectcountry_id').''; + print $form->select_country((GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id)); + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + print '
    '.fieldLabel('State','state_id').''; - print $formcompany->select_state($object->state_id,$object->country_code, 'state_id'); - print '
    '.fieldLabel('State','state_id').''; + print $formcompany->select_state($object->state_id,$object->country_code, 'state_id'); + print '
    '.$langs->trans("PhonePro").''; - if (! empty($ldap_phone)) - { - print ''; - print $ldap_phone; - } - else - { - print ''; - } - print '
    '.$langs->trans("PhonePro").''; + if (! empty($ldap_phone)) + { + print ''; + print $ldap_phone; + } + else + { + print ''; + } + print '
    '.$langs->trans("PhoneMobile").''; - if (! empty($ldap_mobile)) - { - print ''; - print $ldap_mobile; - } - else - { - print ''; - } - print '
    '.$langs->trans("PhoneMobile").''; + if (! empty($ldap_mobile)) + { + print ''; + print $ldap_mobile; + } + else + { + print ''; + } + print '
    '.$langs->trans("Fax").''; - if (! empty($ldap_fax)) - { - print ''; - print $ldap_fax; - } - else - { - print ''; - } - print '
    '.$langs->trans("Fax").''; + if (! empty($ldap_fax)) + { + print ''; + print $ldap_fax; + } + else + { + print ''; + } + print '
    '.$langs->trans("Skype").''; - if (! empty($ldap_skype)) - { - print ''; - print $ldap_skype; - } - else - { - print ''; - } - print '
    '.$langs->trans("Skype").''; + if (! empty($ldap_skype)) + { + print ''; + print $ldap_skype; + } + else + { + print ''; + } + print '
    '; - if (! empty($ldap_mail)) - { - print ''; - print $ldap_mail; - } - else - { - print ''; - } - print '
    '; + if (! empty($ldap_mail)) + { + print ''; + print $ldap_mail; + } + else + { + print ''; + } + print '
    '.$langs->trans("AccountancyCode").''; - print ''; - print '
    '.$langs->trans("AccountancyCode").''; + print ''; + print '
    '.$langs->trans("HierarchicalResponsible").''; - print $form->select_dolusers($object->fk_user, 'fk_user', 1, array($object->id), 0, '', 0, $conf->entity, 0, 0, '', 0, '', 'maxwidth300'); - print '
    '.$langs->trans("HierarchicalResponsible").''; + print $form->select_dolusers($object->fk_user, 'fk_user', 1, array($object->id), 0, '', 0, $conf->entity, 0, 0, '', 0, '', 'maxwidth300'); + print '
    '; + // THM + print '
    '; $text=$langs->trans("THM"); print $form->textwithpicto($text, $langs->trans("THMDescription"), 1, 'help', 'classthm'); - print ''; - print ''; - print '
    '; + print ''; + print '
    '; + // TJM + print '
    '; $text=$langs->trans("TJM"); print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classtjm'); - print ''; - print ''; - print '
    '; + print ''; + print '
    '.$langs->trans("Salary").''; - print ''; - print '
    '.$langs->trans("Salary").''; + print ''; + print '
    '.$langs->trans("WeeklyHours").''; - print ''; - print '
    '.$langs->trans("WeeklyHours").''; + print ''; + print '
    '.$langs->trans("DateEmployment").''; + // Date employment + print '
    '.$langs->trans("DateEmployment").''; echo $form->select_date(GETPOST('dateemployment'),'dateemployment',0,0,1,'form'.'dateemployment',1,0,1); print '
    '; - print $langs->trans("Note"); - print ''; - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('note','','',120,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_3,'90%'); - $doleditor->Create(); - print "
    '; + print $langs->trans("Note"); + print ''; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor('note','','',120,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_3,'90%'); + $doleditor->Create(); + print "
    '.$langs->trans("Signature").''; - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('signature',GETPOST('signature'),'',138,'dolibarr_mailings','In',true,true,empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1,ROWS_4,'90%'); - print $doleditor->Create(1); - print '
    '.$langs->trans("Signature").''; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor('signature',GETPOST('signature'),'',138,'dolibarr_mailings','In',true,true,empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1,ROWS_4,'90%'); + print $doleditor->Create(1); + print '
    \n"; + print "\n"; dol_fiche_end(); - print '
    '; - print ''; - //print '     '; - //print ''; - print '
    '; + print '
    '; + print ''; + //print '     '; + //print ''; + print '
    '; - print "
    "; + print ""; } else { - /* ************************************************************************** */ - /* */ - /* View and edition */ - /* */ - /* ************************************************************************** */ + /* ************************************************************************** */ + /* */ + /* View and edition */ + /* */ + /* ************************************************************************** */ - if ($id > 0) - { - $object->fetch($id, '', '', 1); - if ($res < 0) { dol_print_error($db,$object->error); exit; } - $res=$object->fetch_optionals($object->id,$extralabels); + if ($id > 0) + { + $object->fetch($id, '', '', 1); + if ($res < 0) { dol_print_error($db,$object->error); exit; } + $res=$object->fetch_optionals($object->id,$extralabels); // Check if user has rights $object->getrights(); if (empty($object->nb_rights) && $object->statut != 0) setEventMessages($langs->trans('UserHasNoPermissions'), null, 'warnings'); - // Connexion ldap - // pour recuperer passDoNotExpire et userChangePassNextLogon - if (! empty($conf->ldap->enabled) && ! empty($object->ldap_sid)) - { - $ldap = new Ldap(); - $result=$ldap->connect_bind(); - if ($result > 0) - { - $userSearchFilter = '('.$conf->global->LDAP_FILTER_CONNECTION.'('.$ldap->getUserIdentifier().'='.$object->login.'))'; - $entries = $ldap->fetch($object->login,$userSearchFilter); - if (! $entries) - { - setEventMessages($ldap->error, $ldap->errors, 'errors'); - } + // Connexion ldap + // pour recuperer passDoNotExpire et userChangePassNextLogon + if (! empty($conf->ldap->enabled) && ! empty($object->ldap_sid)) + { + $ldap = new Ldap(); + $result=$ldap->connect_bind(); + if ($result > 0) + { + $userSearchFilter = '('.$conf->global->LDAP_FILTER_CONNECTION.'('.$ldap->getUserIdentifier().'='.$object->login.'))'; + $entries = $ldap->fetch($object->login,$userSearchFilter); + if (! $entries) + { + setEventMessages($ldap->error, $ldap->errors, 'errors'); + } - $passDoNotExpire = 0; - $userChangePassNextLogon = 0; - $userDisabled = 0; - $statutUACF = ''; + $passDoNotExpire = 0; + $userChangePassNextLogon = 0; + $userDisabled = 0; + $statutUACF = ''; - // Check options of user account - if (count($ldap->uacf) > 0) - { - foreach ($ldap->uacf as $key => $statut) - { - if ($key == 65536) - { - $passDoNotExpire = 1; - $statutUACF = $statut; - } - } - } - else - { - $userDisabled = 1; - $statutUACF = "ACCOUNTDISABLE"; - } + // Check options of user account + if (count($ldap->uacf) > 0) + { + foreach ($ldap->uacf as $key => $statut) + { + if ($key == 65536) + { + $passDoNotExpire = 1; + $statutUACF = $statut; + } + } + } + else + { + $userDisabled = 1; + $statutUACF = "ACCOUNTDISABLE"; + } - if ($ldap->pwdlastset == 0) - { - $userChangePassNextLogon = 1; - } - } - } + if ($ldap->pwdlastset == 0) + { + $userChangePassNextLogon = 1; + } + } + } - // Show tabs + // Show tabs if ($mode == 'employee') // For HRM module development { $title = $langs->trans("Employee"); @@ -1229,285 +1234,292 @@ else } } - $head = user_prepare_head($object); + $head = user_prepare_head($object); - /* + /* * Confirmation reinitialisation mot de passe */ - if ($action == 'password') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("ReinitPassword"),$langs->trans("ConfirmReinitPassword",$object->login),"confirm_password", '', 0, 1); - } + if ($action == 'password') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("ReinitPassword"),$langs->trans("ConfirmReinitPassword",$object->login),"confirm_password", '', 0, 1); + } - /* + /* * Confirmation envoi mot de passe */ - if ($action == 'passwordsend') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("SendNewPassword"),$langs->trans("ConfirmSendNewPassword",$object->login),"confirm_passwordsend", '', 0, 1); - } + if ($action == 'passwordsend') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("SendNewPassword"),$langs->trans("ConfirmSendNewPassword",$object->login),"confirm_passwordsend", '', 0, 1); + } - /* + /* * Confirm deactivation */ - if ($action == 'disable') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("DisableAUser"),$langs->trans("ConfirmDisableUser",$object->login),"confirm_disable", '', 0, 1); - } + if ($action == 'disable') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("DisableAUser"),$langs->trans("ConfirmDisableUser",$object->login),"confirm_disable", '', 0, 1); + } - /* + /* * Confirm activation */ - if ($action == 'enable') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("EnableAUser"),$langs->trans("ConfirmEnableUser",$object->login),"confirm_enable", '', 0, 1); - } + if ($action == 'enable') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("EnableAUser"),$langs->trans("ConfirmEnableUser",$object->login),"confirm_enable", '', 0, 1); + } - /* + /* * Confirmation suppression */ - if ($action == 'delete') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("DeleteAUser"),$langs->trans("ConfirmDeleteUser",$object->login),"confirm_delete", '', 0, 1); - } + if ($action == 'delete') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("DeleteAUser"),$langs->trans("ConfirmDeleteUser",$object->login),"confirm_delete", '', 0, 1); + } - /* + /* * Fiche en mode visu */ - if ($action != 'edit') - { + if ($action != 'edit') + { dol_fiche_head($head, 'user', $title, -1, 'user'); - dol_banner_tab($object,'id',$linkback,$user->rights->user->user->lire || $user->admin); + dol_banner_tab($object,'id',$linkback,$user->rights->user->user->lire || $user->admin); - print '
    '; - print '
    '; + print '
    '; + print '
    '; - print '
    '; - print ''; + print '
    '; + print '
    '; - // Login - print ''; - if (! empty($object->ldap_sid) && $object->statut==0) - { - print ''; - } - else - { - print ''; - } - print ''."\n"; + // Login + print ''; + if (! empty($object->ldap_sid) && $object->statut==0) + { + print ''; + } + else + { + print ''; + } + print ''."\n"; - // Password - print ''; - if (! empty($object->ldap_sid)) - { - if ($passDoNotExpire) - { - print ''; - } - else if($userChangePassNextLogon) - { - print ''; - } - else if($userDisabled) - { - print ''; - } - else - { - print ''; - } - } - else - { - print '"; - } - print ''."\n"; + // Password + print ''; + if (! empty($object->ldap_sid)) + { + if ($passDoNotExpire) + { + print ''; + } + else if($userChangePassNextLogon) + { + print ''; + } + else if($userDisabled) + { + print ''; + } + else + { + print ''; + } + } + else + { + print '"; + } + print ''."\n"; - // Employee - print ''."\n"; + // Employee + print ''."\n"; - // Position/Job - print ''; - print ''; - print ''."\n"; + // Position/Job + print ''; + print ''; + print ''."\n"; - // Gender - print ''; - print ''; + // Gender + print ''; + print ''; - // API key - if(! empty($conf->api->enabled) && $user->admin) { - print ''; - print ''; - } + // Date of birth + print ''; + print ''; + print "\n"; - // Administrator - print ''."\n"; + // API key + if(! empty($conf->api->enabled) && $user->admin) { + print ''; + print ''; + } - // Type - print ''."\n"; + + // Type + print ''."\n"; + if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; + print ''."\n"; - // Ldap sid - if ($object->ldap_sid) - { - print ''."\n"; - } + // Ldap sid + if ($object->ldap_sid) + { + print ''."\n"; + } - // Accountancy code - if ($conf->accounting->enabled) - { - print ''; - print ''; - } + // Accountancy code + if ($conf->accounting->enabled) + { + print ''; + print ''; + } - // TODO Move this into tab RH, visible when salarie or RH is visible (HierarchicalResponsible must be on both tab) + // TODO Move this into tab RH, visible when salarie or RH is visible (HierarchicalResponsible must be on both tab) - // Hierarchy - print ''; - print ''; - print "\n"; + // Hierarchy + print ''; + print ''; + print "\n"; //$childids = $user->getAllChildIds(1); - if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) - || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) - { + if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) + || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) + { // Even a superior can't see this info of its subordinates wihtout $user->rights->salaries->read and $user->rights->hrm->employee->read (setting/viewing is reserverd to HR people). // However, he can see the valuation of timesheet of its subordinates even without these permissions. - $langs->load("salaries"); + $langs->load("salaries"); - // THM - print ''; - print ''; - print "\n"; + // THM + print ''; + print ''; + print "\n"; - // TJM - print ''; - print ''; - print "\n"; + // TJM + print ''; + print ''; + print "\n"; - // Salary - print ''; - print ''; - print "\n"; - } + // Salary + print ''; + print ''; + print "\n"; + } - // Weeklyhours - print ''; - print ''; + print ''; - print "\n"; + print ''; + print "\n"; - // Date employment - print ''; - print ''; + print ''; - print "\n"; + print ''; + print "\n"; - print '
    '.$langs->trans("Login").''.$langs->trans("LoginAccountDisableInDolibarr").''.$object->login.'
    '.$langs->trans("Login").''.$langs->trans("LoginAccountDisableInDolibarr").''.$object->login.'
    '.$langs->trans("Password").''.$langs->trans("LdapUacf_".$statutUACF).''.$langs->trans("UserMustChangePassNextLogon",$ldap->domainFQDN).''.$langs->trans("LdapUacf_".$statutUACF,$ldap->domainFQDN).''.$langs->trans("DomainPassword").''; - if ($object->pass) print preg_replace('/./i','*',$object->pass); - else - { - if ($user->admin) print $langs->trans("Crypted").': '.$object->pass_indatabase_crypted; - else print $langs->trans("Hidden"); - } - print "
    '.$langs->trans("Password").''.$langs->trans("LdapUacf_".$statutUACF).''.$langs->trans("UserMustChangePassNextLogon",$ldap->domainFQDN).''.$langs->trans("LdapUacf_".$statutUACF,$ldap->domainFQDN).''.$langs->trans("DomainPassword").''; + if ($object->pass) print preg_replace('/./i','*',$object->pass); + else + { + if ($user->admin) print $langs->trans("Crypted").': '.$object->pass_indatabase_crypted; + else print $langs->trans("Hidden"); + } + print "
    '.$langs->trans("Employee").''; - print yn($object->employee); - print '
    '.$langs->trans("Employee").''; + print yn($object->employee); + print '
    '.$langs->trans("PostOrFunction").''.$object->job.'
    '.$langs->trans("PostOrFunction").''.$object->job.'
    '.$langs->trans("Gender").''; - if ($object->gender) print $langs->trans("Gender".$object->gender); - print '
    '.$langs->trans("Gender").''; + if ($object->gender) print $langs->trans("Gender".$object->gender); + print '
    '.$langs->trans("ApiKey").''; - if (! empty($object->api_key)) print preg_replace('/./','*',$object->api_key); - print '
    '.$langs->trans("DateToBirth").''; + print dol_print_date($object->birth, 'day'); + print '
    '.$langs->trans("Administrator").''; - if (! empty($conf->multicompany->enabled) && $object->admin && ! $object->entity) - { - print $form->textwithpicto(yn($object->admin),$langs->trans("SuperAdministratorDesc"),1,"superadmin"); - } - else if ($object->admin) - { - print $form->textwithpicto(yn($object->admin),$langs->trans("AdministratorDesc"),1,"admin"); - } - else - { - print yn($object->admin); - } - print '
    '.$langs->trans("ApiKey").''; + if (! empty($object->api_key)) print preg_replace('/./','*',$object->api_key); + print '
    '; - $text=$langs->trans("Type"); - print $form->textwithpicto($text, $langs->trans("InternalExternalDesc")); - print ''; - $type=$langs->trans("Internal"); - if ($object->societe_id > 0) $type=$langs->trans("External"); + // Administrator + print '
    '.$langs->trans("Administrator").''; + if (! empty($conf->multicompany->enabled) && $object->admin && ! $object->entity) + { + print $form->textwithpicto(yn($object->admin),$langs->trans("SuperAdministratorDesc"),1,"superadmin"); + } + else if ($object->admin) + { + print $form->textwithpicto(yn($object->admin),$langs->trans("AdministratorDesc"),1,"admin"); + } + else + { + print yn($object->admin); + } + print '
    '; + $text=$langs->trans("Type"); + print $form->textwithpicto($text, $langs->trans("InternalExternalDesc")); + print ''; + $type=$langs->trans("Internal"); + if ($object->societe_id > 0) $type=$langs->trans("External"); print $type; - if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; - print '
    '.$langs->trans("Type").''; - print $langs->trans("DomainUser",$ldap->domainFQDN); - print '
    '.$langs->trans("Type").''; + print $langs->trans("DomainUser",$ldap->domainFQDN); + print '
    '.$langs->trans("AccountancyCode").''.$object->accountancy_code.'
    '.$langs->trans("AccountancyCode").''.$object->accountancy_code.'
    '.$langs->trans("HierarchicalResponsible").''; - if (empty($object->fk_user)) print $langs->trans("None"); - else { - $huser=new User($db); - $huser->fetch($object->fk_user); - print $huser->getNomUrl(1); - } - print '
    '.$langs->trans("HierarchicalResponsible").''; + if (empty($object->fk_user)) print $langs->trans("None"); + else { + $huser=new User($db); + $huser->fetch($object->fk_user); + print $huser->getNomUrl(1); + } + print '
    '; - $text=$langs->trans("THM"); - print $form->textwithpicto($text, $langs->trans("THMDescription"), 1, 'help', 'classthm'); - print ''; - print ($object->thm!=''?price($object->thm,'',$langs,1,-1,-1,$conf->currency):''); - print '
    '; + $text=$langs->trans("THM"); + print $form->textwithpicto($text, $langs->trans("THMDescription"), 1, 'help', 'classthm'); + print ''; + print ($object->thm!=''?price($object->thm,'',$langs,1,-1,-1,$conf->currency):''); + print '
    '; - $text=$langs->trans("TJM"); - print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classtjm'); - print ''; - print ($object->tjm!=''?price($object->tjm,'',$langs,1,-1,-1,$conf->currency):''); - print '
    '; + $text=$langs->trans("TJM"); + print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classtjm'); + print ''; + print ($object->tjm!=''?price($object->tjm,'',$langs,1,-1,-1,$conf->currency):''); + print '
    '.$langs->trans("Salary").''; - print ($object->salary!=''?price($object->salary,'',$langs,1,-1,-1,$conf->currency):''); - print '
    '.$langs->trans("Salary").''; + print ($object->salary!=''?price($object->salary,'',$langs,1,-1,-1,$conf->currency):''); + print '
    '.$langs->trans("WeeklyHours").''; + // Weeklyhours + print '
    '.$langs->trans("WeeklyHours").''; print price2num($object->weeklyhours); - print '
    '.$langs->trans("DateEmployment").''; + // Date employment + print '
    '.$langs->trans("DateEmployment").''; print dol_print_date($object->dateemployment); - print '
    '; + print ''; - print '
    '; - print '
    '; + print '
    '; + print '
    '; - print '
    '; - print ''; + print '
    '; + print '
    '; - // Color user - if (! empty($conf->agenda->enabled)) - { - print ''; - print ''; - print "\n"; - } + // Color user + if (! empty($conf->agenda->enabled)) + { + print ''; + print ''; + print "\n"; + } - // Categories - if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) - { + // Categories + if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) + { print ''; print ''; - } + } - if (isset($conf->file->main_authentication) && preg_match('/openid/',$conf->file->main_authentication) && ! empty($conf->global->MAIN_OPENIDURL_PERUSER)) - { - print ''; - print ''; - print "\n"; - } + if (isset($conf->file->main_authentication) && preg_match('/openid/',$conf->file->main_authentication) && ! empty($conf->global->MAIN_OPENIDURL_PERUSER)) + { + print ''; + print ''; + print "\n"; + } - print ''; - print ''; - print "\n"; + print ''; + print ''; + print "\n"; - print ''; - print ''; - print "\n"; + print ''; + print ''; + print "\n"; - // Multicompany - // This is now done with hook formObjectOptions (included into /core/tpl/extrafields_view.tpl.php) - /* + // Multicompany + // This is now done with hook formObjectOptions (included into /core/tpl/extrafields_view.tpl.php) + /* if (! empty($conf->multicompany->enabled) && is_object($mc)) { if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity) @@ -1523,540 +1535,440 @@ else } }*/ - // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - // Company / Contact - if (! empty($conf->societe->enabled)) - { - print ''; - print ''; - print ''."\n"; - } + // Company / Contact + if (! empty($conf->societe->enabled)) + { + print ''; + print ''; + print ''."\n"; + } - // Module Adherent - if (! empty($conf->adherent->enabled)) - { - $langs->load("members"); - print ''; - print ''; - print ''."\n"; - } + // Module Adherent + if (! empty($conf->adherent->enabled)) + { + $langs->load("members"); + print ''; + print ''; + print ''."\n"; + } - // Signature - print '\n"; + // Signature + print '\n"; - print "
    '.$langs->trans("ColorUser").''; - print $formother->showColor($object->color, ''); - print '
    '.$langs->trans("ColorUser").''; + print $formother->showColor($object->color, ''); + print '
    ' . $langs->trans( "Categories" ) . ''; print $form->showCategories( $object->id, 'user', 1 ); print '
    '.$langs->trans("OpenIDURL").''.$object->openid.'
    '.$langs->trans("OpenIDURL").''.$object->openid.'
    '.$langs->trans("LastConnexion").''.dol_print_date($object->datelastlogin,"dayhour").'
    '.$langs->trans("LastConnexion").''.dol_print_date($object->datelastlogin,"dayhour").'
    '.$langs->trans("PreviousConnexion").''.dol_print_date($object->datepreviouslogin,"dayhour").'
    '.$langs->trans("PreviousConnexion").''.dol_print_date($object->datepreviouslogin,"dayhour").'
    '.$langs->trans("LinkToCompanyContact").''; - if (isset($object->socid) && $object->socid > 0) - { - $societe = new Societe($db); - $societe->fetch($object->socid); - print $societe->getNomUrl(1,''); - } - else - { - print $langs->trans("ThisUserIsNot"); - } - if (! empty($object->contactid)) - { - $contact = new Contact($db); - $contact->fetch($object->contactid); - if ($object->socid > 0) print ' / '; - else print '
    '; - print ''.img_object($langs->trans("ShowContact"),'contact').' '.dol_trunc($contact->getFullName($langs),32).''; - } - print '
    '.$langs->trans("LinkToCompanyContact").''; + if (isset($object->socid) && $object->socid > 0) + { + $societe = new Societe($db); + $societe->fetch($object->socid); + print $societe->getNomUrl(1,''); + } + else + { + print $langs->trans("ThisUserIsNot"); + } + if (! empty($object->contactid)) + { + $contact = new Contact($db); + $contact->fetch($object->contactid); + if ($object->socid > 0) print ' / '; + else print '
    '; + print ''.img_object($langs->trans("ShowContact"),'contact').' '.dol_trunc($contact->getFullName($langs),32).''; + } + print '
    '.$langs->trans("LinkedToDolibarrMember").''; - if ($object->fk_member) - { - $adh=new Adherent($db); - $adh->fetch($object->fk_member); - $adh->ref=$adh->getFullname($langs); // Force to show login instead of id - print $adh->getNomUrl(1); - } - else - { - print $langs->trans("UserNotLinkedToMember"); - } - print '
    '.$langs->trans("LinkedToDolibarrMember").''; + if ($object->fk_member) + { + $adh=new Adherent($db); + $adh->fetch($object->fk_member); + $adh->ref=$adh->getFullname($langs); // Force to show login instead of id + print $adh->getNomUrl(1); + } + else + { + print $langs->trans("UserNotLinkedToMember"); + } + print '
    '.$langs->trans('Signature').''; - print dol_htmlentitiesbr($object->signature); - print "
    '.$langs->trans('Signature').''; + print dol_htmlentitiesbr($object->signature); + print "
    \n"; + print "\n"; print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; - dol_fiche_end(); + dol_fiche_end(); - /* + /* * Buttons actions */ - print '
    '; + print '
    '; - if (! empty($object->email)) - { - $langs->load("mails"); - print ''; - } - else - { - $langs->load("mails"); - print ''; - } + if (! empty($object->email)) + { + $langs->load("mails"); + print ''; + } + else + { + $langs->load("mails"); + print ''; + } - if ($caneditfield && (empty($conf->multicompany->enabled) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { - if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) - { - print ''; - } - else - { - print ''; - } - } - elseif ($caneditpassword && ! $object->ldap_sid && - (empty($conf->multicompany->enabled) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { - print ''; - } + if ($caneditfield && (empty($conf->multicompany->enabled) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + { + if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) + { + print ''; + } + else + { + print ''; + } + } + elseif ($caneditpassword && ! $object->ldap_sid && + (empty($conf->multicompany->enabled) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + { + print ''; + } - // Si on a un gestionnaire de generation de mot de passe actif - if ($conf->global->USER_PASSWORD_GENERATED != 'none') - { + // Si on a un gestionnaire de generation de mot de passe actif + if ($conf->global->USER_PASSWORD_GENERATED != 'none') + { if ($object->statut == 0) { - print ''; + print ''; + } + elseif (($user->id != $id && $caneditpassword) && $object->login && !$object->ldap_sid && + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + { + print ''; } - elseif (($user->id != $id && $caneditpassword) && $object->login && !$object->ldap_sid && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { - print ''; - } if ($object->statut == 0) { - print ''; + print ''; } - else if (($user->id != $id && $caneditpassword) && $object->login && !$object->ldap_sid && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { - if ($object->email) print ''; - else print ''; - } - } + else if (($user->id != $id && $caneditpassword) && $object->login && !$object->ldap_sid && + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + { + if ($object->email) print ''; + else print ''; + } + } - // Activer - if ($user->id <> $id && $candisableuser && $object->statut == 0 && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { - print ''; - } - // Desactiver - if ($user->id <> $id && $candisableuser && $object->statut == 1 && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { - print ''; - } - // Delete - if ($user->id <> $id && $candisableuser && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) - { - if ($user->admin || ! $object->admin) // If user edited is admin, delete is possible on for an admin - { - print ''; - } - else - { - print ''; - } - } + // Activer + if ($user->id <> $id && $candisableuser && $object->statut == 0 && + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + { + print ''; + } + // Desactiver + if ($user->id <> $id && $candisableuser && $object->statut == 1 && + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + { + print ''; + } + // Delete + if ($user->id <> $id && $candisableuser && + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + { + if ($user->admin || ! $object->admin) // If user edited is admin, delete is possible on for an admin + { + print ''; + } + else + { + print ''; + } + } - print "
    \n"; + print "
    \n"; - //Select mail models is same action as presend - if (GETPOST('modelselected')) { - $action = 'presend'; - } - if ($action == 'presend') - { - // Show email form + //Select mail models is same action as presend + if (GETPOST('modelselected')) $action = 'presend'; - // By default if $action=='presend' - $titreform='SendMail'; - $topicmail=1; - $action='send'; - $modelmail='user'; + // Presend form + $modelmail='user'; + $defaulttopic='Information'; + $diroutput = $conf->user->dir_output; + $trackid = 'user'.$object->id; - print '
    '; - print '
    '; - print load_fiche_titre($langs->trans($titreform)); + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - dol_fiche_head(); - - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - //if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - // $newlang = $object->thirdparty->default_lang; - - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - $formmail->trackid='thi'.$object->id; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'thi'.$object->id); - } - $formmail->withfrom=1; - $formmail->withtopic=$topicmail; - $formmail->withto=GETPOST('sendto')?GETPOST('sendto'):$object->email; - $formmail->withtofree=1; - $formmail->withtocc=1; - $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withfile=2; - $formmail->withbody=1; - $formmail->withdeliveryreceipt=1; - $formmail->withcancel=1; - // Tableau des substitutions - $formmail->setSubstitFromObject($object); - $formmail->substit['__LASTNAME__']=$object->lastname; - $formmail->substit['__FIRSTNAME__']=$object->firstname; - - // Tableau des parametres complementaires du post - $formmail->param['action']=$action; - $formmail->param['models']=$modelmail; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['socid']=$object->id; - $formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id; - - // Init list of files - if (GETPOST("mode")=='init') - { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file,basename($file),dol_mimetype($file)); - } - print $formmail->get_form(); - - dol_fiche_end(); - } - - if (GETPOST('action','aZ09') != 'presend' && GETPOST('action','aZ09') != 'send') - { - /* + if ($action != 'presend' && $action != 'send') + { + /* * List of groups of user */ - if ($canreadgroup) - { - print load_fiche_titre($langs->trans("ListOfGroupsForUser"),'',''); + if ($canreadgroup) + { + print load_fiche_titre($langs->trans("ListOfGroupsForUser"),'',''); - // On selectionne les groupes auquel fait parti le user - $exclude = array(); + // On selectionne les groupes auquel fait parti le user + $exclude = array(); - $usergroup=new UserGroup($db); - $groupslist = $usergroup->listGroupsForUser($object->id); + $usergroup=new UserGroup($db); + $groupslist = $usergroup->listGroupsForUser($object->id); - if (! empty($groupslist)) - { - if (! (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))) - { - foreach($groupslist as $groupforuser) - { - $exclude[]=$groupforuser->id; - } - } - } + if (! empty($groupslist)) + { + foreach($groupslist as $groupforuser) + { + $exclude[]=$groupforuser->id; + } + } - if ($caneditgroup) - { - print '
    '."\n"; - print ''; - print ''; - } + if ($caneditgroup) + { + print ''."\n"; + print ''; + print ''; + } - print ''."\n"; - print ''."\n"; - if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity) - { - print ''; - } - print ''; - print "'."\n"; + print '
    '.$langs->trans("Groups").''.$langs->trans("Entity").''; - if ($caneditgroup) - { - // Users/Groups management only in master entity if transverse mode - if (! empty($conf->multicompany->enabled) && $conf->entity > 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) - { - // nothing - } - else - { - print $form->select_dolgroups('', 'group', 1, $exclude, 0, '', '', $object->entity); - print '   '; - // Multicompany - if (! empty($conf->multicompany->enabled)) - { - if ($conf->entity == 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) - { - print ''.$langs->trans("Entity").'".$mc->select_entities($conf->entity); - } - else - { - print ''; - } - } - else - { - print ''; - } - print ''; - } - } - print '
    '."\n"; - /* - * Groups assigned to user - */ - if (! empty($groupslist)) - { - foreach($groupslist as $group) - { + // Other form for add user to group + $parameters=array('caneditgroup' => $caneditgroup, 'groupslist' => $groupslist, 'exclude' => $exclude); + $reshook=$hookmanager->executeHooks('formAddUserToGroup',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (empty($reshook)) + { + print ''."\n"; + print ''."\n"; - print ''; - print ''; - if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity) - { - print '\n"; - } - } - else - { - print ''; - } + /* + * Groups assigned to user + */ + if (! empty($groupslist)) + { + foreach($groupslist as $group) + { + print ''; + print ''; + print '\n"; + } + } + else + { + print ''; + } + } - print "
    '.$langs->trans("Groups").''; + if ($caneditgroup) + { + print $form->select_dolgroups('', 'group', 1, $exclude, 0, '', '', $object->entity); + print '   '; + print ''; + print ''; + } + print '
    '; - if ($caneditgroup) - { - print ''.img_object($langs->trans("ShowGroup"),"group").' '.$group->name.''; - } - else - { - print img_object($langs->trans("ShowGroup"),"group").' '.$group->name; - } - print ''; - if (! empty($group->usergroup_entity)) - { - $nb=0; - foreach($group->usergroup_entity as $group_entity) - { - $mc->getInfo($group_entity); - print ($nb > 0 ? ', ' : '').$mc->label; - print ''; - print img_delete($langs->trans("RemoveFromGroup")); - print ''; - $nb++; - } - } - } - print ''; - if ($caneditgroup && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - print ''; - print img_delete($langs->trans("RemoveFromGroup")); - print ''; - } - else - { - print " "; - } - print "
    '.$langs->trans("None").'
    '; + if ($caneditgroup) + { + print ''.img_object($langs->trans("ShowGroup"),"group").' '.$group->name.''; + } + else + { + print img_object($langs->trans("ShowGroup"),"group").' '.$group->name; + } + print ''; + if ($caneditgroup) + { + print ''; + print img_delete($langs->trans("RemoveFromGroup")); + print ''; + } + else + { + print " "; + } + print "
    '.$langs->trans("None").'
    "; + print ""; - if ($caneditgroup) - { - print '
    '; - } - print "
    "; - } - } - } + if ($caneditgroup) + { + print ''; + } + print "
    "; + } + } + } - /* + /* * Fiche en mode edition */ - if ($action == 'edit' && ($canedituser || $caneditfield || $caneditpassword || ($user->id == $object->id))) - { - print '
    '; - print ''; - print ''; - print ''; + if ($action == 'edit' && ($canedituser || $caneditfield || $caneditpassword || ($user->id == $object->id))) + { + print ''; + print ''; + print ''; + print ''; - dol_fiche_head($head, 'user', $title, 0, 'user'); + dol_fiche_head($head, 'user', $title, 0, 'user'); - print ''; + print '
    '; - // Ref/ID + // Ref/ID if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } - // Lastname - print ""; - print ''; - print ''; - print ''; - - // Firstname - print "".''; - print ''; - - // Employee - print ''; - print ''; - - // Position/Job - print ''; - print '"; + print ''; + print ''; + print ''; + } + else + { + print ''; + print $object->lastname; + } + print ''; + print ''; - // Gender - print ''; - print ''; + // Firstname + print "".''; + print ''; - // Login - print "".''; - print ''; - print ''; + // Employee + print ''; + print ''; - // Pass - print ''; - print '\n"; + // Position/Job + print ''; + print ''; - // API key - if(! empty($conf->api->enabled) && $user->admin) - { - print ''; - print ''; - } + // Gender + print ''; + print ''; - // Administrator - print ''; - if ($object->socid > 0) - { - $langs->load("admin"); - print ''; - } - else - { - print ''; + print ''; + print "\n"; - if (! empty($conf->multicompany->enabled) && ! $user->entity && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if ($conf->use_javascript_ajax) - { - print ''; - } + } - $checked=(($object->admin && ! $object->entity) ? ' checked' : ''); - print ' '.$langs->trans("SuperAdministrator"); - } - } - else - { - $yn = yn($object->admin); - print ''; - print ''; - if (! empty($conf->multicompany->enabled) && empty($object->entity)) print $form->textwithpicto($yn,$langs->trans("DontDowngradeSuperAdmin"),1,'warning'); - else print $yn; - } - print ''; - } + $checked=(($object->admin && ! $object->entity) ? ' checked' : ''); + print ' '.$langs->trans("SuperAdministrator"); + } + } + else + { + $yn = yn($object->admin); + print ''; + print ''; + if (! empty($conf->multicompany->enabled) && empty($object->entity)) print $form->textwithpicto($yn,$langs->trans("DontDowngradeSuperAdmin"),1,'warning'); + else print $yn; + } + print ''; + } - // Type - print ''; - print ''; + print ''; + if ($object->contact_id) $type=$object->contact_id; + print $form->selectcontacts(0,$type,'contactid',2,'','',1,'',false,1); + if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; + } + print ''; // Address - print ''; - print ''; + print ''; + print ''; - // Zip - print ''; + // Zip + print ''; // Town print ''; + print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id')); + print ''; - // Country - print ''; + // Country + print ''; - // State - if (empty($conf->global->USER_DISABLE_STATE)) - { - print ''; - } + // State + if (empty($conf->global->USER_DISABLE_STATE)) + { + print ''; + } - // Tel pro - print "".''; - print ''; + // Tel pro + print "".''; + print ''; - // Tel mobile - print "".''; - print ''; + // Tel mobile + print "".''; + print ''; - // Fax - print "".''; - print ''; + // Fax + print "".''; + print ''; - // Skype - if (! empty($conf->skype->enabled)) - { - print ''; - print ''; - } + // Skype + if (! empty($conf->skype->enabled)) + { + print ''; + print ''; + } - // EMail - print "".'global->USER_MAIL_REQUIRED)?' class="fieldrequired"':'').'>'.$langs->trans("EMail").''; - print ''; + // EMail + print "".'global->USER_MAIL_REQUIRED)?' class="fieldrequired"':'').'>'.$langs->trans("EMail").''; + print ''; - // OpenID url - if (isset($conf->file->main_authentication) && preg_match('/openid/',$conf->file->main_authentication) && ! empty($conf->global->MAIN_OPENIDURL_PERUSER)) - { - print "".''; - print ''; - } + // OpenID url + if (isset($conf->file->main_authentication) && preg_match('/openid/',$conf->file->main_authentication) && ! empty($conf->global->MAIN_OPENIDURL_PERUSER)) + { + print "".''; + print ''; + } - // Accountancy code - if ($conf->accounting->enabled) - { - print ""; - print ''; - print ''; - print ""; - } + // Accountancy code + if ($conf->accounting->enabled) + { + print ""; + print ''; + print ''; + print ""; + } - // TODO Move this into tab RH (HierarchicalResponsible must be on both tab) + // TODO Move this into tab RH (HierarchicalResponsible must be on both tab) - // Hierarchy - print ''; - print ''; - print "\n"; + // Hierarchy + print ''; + print ''; + print "\n"; - if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) - || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) - { - $langs->load("salaries"); + if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) + || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) + { + $langs->load("salaries"); - // THM - print ''; - print ''; - print "\n"; + // THM + print ''; + print ''; + print "\n"; - // TJM - print ''; - print ''; - print "\n"; + // TJM + print ''; + print ''; + print "\n"; - // Salary - print ''; - print ''; - print "\n"; - } + // Salary + print ''; + print ''; + print "\n"; + } - // Weeklyhours - print ''; - print ''; - print "\n"; + // Weeklyhours + print ''; + print ''; + print "\n"; - // Date employment - print ''; - print ''; + print ''; - print "\n"; + print "\n"; - // User color - if (! empty($conf->agenda->enabled)) - { - print ''; - print ''; - } + // User color + if (! empty($conf->agenda->enabled)) + { + print ''; + print ''; + } - // Photo - print ''; - print ''; - print ''; - print ''; + // Photo + print ''; + print ''; + print ''; + print ''; - // Categories - if (!empty( $conf->categorie->enabled ) && !empty( $user->rights->categorie->lire )) - { - print ''; - print '"; - } + // Categories + if (!empty( $conf->categorie->enabled ) && !empty( $user->rights->categorie->lire )) + { + print ''; + print '"; + } - // Status - print ''; - print ''; + // Status + print ''; + print ''; - // Company / Contact - if (! empty($conf->societe->enabled)) - { - print ''; - print ''; - print "\n"; - } + // Company / Contact + if (! empty($conf->societe->enabled)) + { + print ''; + print ''; + print "\n"; + } - // Module Adherent - if (! empty($conf->adherent->enabled)) - { - $langs->load("members"); - print ''; - print ''; - print "\n"; - } + // Module Adherent + if (! empty($conf->adherent->enabled)) + { + $langs->load("members"); + print ''; + print ''; + print "\n"; + } - // Multicompany - // This is now done with hook formObjectOptions - /* + // Multicompany + // This is now done with hook formObjectOptions + /* // TODO check if user not linked with the current entity before change entity (thirdparty, invoice, etc.) !! if (! empty($conf->multicompany->enabled) && is_object($mc)) { @@ -2436,82 +2348,82 @@ else } */ - // Other attributes - $parameters=array('colspan' => ' colspan="2"'); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) - { - print $object->showOptionals($extrafields,'edit'); - } + // Other attributes + $parameters=array('colspan' => ' colspan="2"'); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (empty($reshook) && ! empty($extrafields->attribute_label)) + { + print $object->showOptionals($extrafields,'edit'); + } - // Signature - print "".''; - print ''; + // Signature + print "".''; + print ''; - print '
    '.$langs->trans("Ref").''; - print $object->id; - print '
    '.$langs->trans("Ref").''; + print $object->id; + print '
    '.$langs->trans("Lastname").''; - if ($caneditfield && !$object->ldap_sid) - { - print ''; - } - else - { - print ''; - print $object->lastname; - } - print '
    '.$langs->trans("Firstname").''; - if ($caneditfield && !$object->ldap_sid) - { - print ''; - } - else - { - print ''; - print $object->firstname; - } - print '
    '.fieldLabel('Employee','employee',0).''; - print $form->selectyesno("employee",$object->employee,1); - print '
    '.$langs->trans("PostOrFunction").''; - if ($caneditfield) - { - print ''; - } - else + // Lastname + print "
    '.$langs->trans("Lastname").''; + if ($caneditfield && !$object->ldap_sid) { - print ''; - print $object->job; - } - print '
    '.$langs->trans("Gender").''; - $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); - print $form->selectarray('gender', $arraygender, GETPOST('gender')?GETPOST('gender'):$object->gender, 1); - print '
    '.$langs->trans("Firstname").''; + if ($caneditfield && !$object->ldap_sid) + { + print ''; + } + else + { + print ''; + print $object->firstname; + } + print '
    '.$langs->trans("Login").''; - if ($user->admin && !$object->ldap_sid) - { - print ''; - } - else - { - print ''; - print $object->login; - } - print '
    '.fieldLabel('Employee','employee',0).''; + print $form->selectyesno("employee",$object->employee,1); + print '
    '.$langs->trans("Password").''; - if ($object->ldap_sid) - { - $text=$langs->trans("DomainPassword"); - } - else if ($caneditpassword) - { - $text=''; - if ($dolibarr_main_authentication && $dolibarr_main_authentication == 'http') - { - $text=$form->textwithpicto($text,$langs->trans("DolibarrInHttpAuthenticationSoPasswordUseless",$dolibarr_main_authentication),1,'warning'); - } - } - else - { - $text=preg_replace('/./i','*',$object->pass); - } - print $text; - print "
    '.$langs->trans("PostOrFunction").''; + if ($caneditfield) + { + print ''; + } + else + { + print ''; + print $object->job; + } + print '
    '.$langs->trans("ApiKey").''; - print ''; - if (! empty($conf->use_javascript_ajax)) - print ' '.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_api_key" class="linkobject"'); - print '
    '.$langs->trans("Gender").''; + $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); + print $form->selectarray('gender', $arraygender, GETPOST('gender')?GETPOST('gender'):$object->gender, 1); + print '
    '.$langs->trans("Administrator").''; - print ''.yn($object->admin); - print ' ('.$langs->trans("ExternalUser").')'; - print '
    '; - $nbAdmin = $user->getNbOfUsers('active','',1); - $nbSuperAdmin = $user->getNbOfUsers('active','superadmin',1); - //var_dump($nbAdmin); - //var_dump($nbSuperAdmin); - if ($user->admin // Need to be admin to allow downgrade of an admin - && ($user->id != $object->id) // Don't downgrade ourself - && ( - (empty($conf->multicompany->enabled) && $nbAdmin >= 1) - || (! empty($conf->multicompany->enabled) && ($object->entity > 0 || $nbSuperAdmin > 1)) // Don't downgrade a superadmin if alone - ) - ) - { - print $form->selectyesno('admin',$object->admin,1); + // Date birth + print '
    '.$langs->trans("DateToBirth").''; + echo $form->select_date(GETPOST('birth')?GETPOST('birth'):$object->birth,'birth',0,0,1,'updateuser',1,0,1); + print '
    '.$langs->trans("Type").''; - if ($user->id == $object->id || ! $user->admin) - { - $type=$langs->trans("Internal"); - if ($object->socid) $type=$langs->trans("External"); - print $form->textwithpicto($type,$langs->trans("InternalExternalDesc")); - if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; - } - else + // Type + print '
    '.$langs->trans("Type").''; + if ($user->id == $object->id || ! $user->admin) + { + $type=$langs->trans("Internal"); + if ($object->socid) $type=$langs->trans("External"); + print $form->textwithpicto($type,$langs->trans("InternalExternalDesc")); + if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; + } + else { $type=0; - if ($object->contact_id) $type=$object->contact_id; - print $form->selectcontacts(0,$type,'contactid',2,'','',1,'',false,1); - if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; - } - print '
    '.fieldLabel('Address','address').'
    '.fieldLabel('Address','address').'
    '.fieldLabel('Zip','zipcode').''; - print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6); - print '
    '.fieldLabel('Zip','zipcode').''; + print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6); + print '
    '.fieldLabel('Town','town').''; - print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id')); - print '
    '.fieldLabel('Country','selectcounty_id').''; - print $form->select_country((GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id),'country_id'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - print '
    '.fieldLabel('Country','selectcounty_id').''; + print $form->select_country((GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id),'country_id'); + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + print '
    '.fieldLabel('State','state_id').''; - print $formcompany->select_state($object->state_id,$object->country_code, 'state_id'); - print '
    '.fieldLabel('State','state_id').''; + print $formcompany->select_state($object->state_id,$object->country_code, 'state_id'); + print '
    '.$langs->trans("PhonePro").''; - if ($caneditfield && empty($object->ldap_sid)) - { - print ''; - } - else - { - print ''; - print $object->office_phone; - } - print '
    '.$langs->trans("PhonePro").''; + if ($caneditfield && empty($object->ldap_sid)) + { + print ''; + } + else + { + print ''; + print $object->office_phone; + } + print '
    '.$langs->trans("PhoneMobile").''; - if ($caneditfield && empty($object->ldap_sid)) - { - print ''; - } - else - { - print ''; - print $object->user_mobile; - } - print '
    '.$langs->trans("PhoneMobile").''; + if ($caneditfield && empty($object->ldap_sid)) + { + print ''; + } + else + { + print ''; + print $object->user_mobile; + } + print '
    '.$langs->trans("Fax").''; - if ($caneditfield && empty($object->ldap_sid)) - { - print ''; - } - else - { - print ''; - print $object->office_fax; - } - print '
    '.$langs->trans("Fax").''; + if ($caneditfield && empty($object->ldap_sid)) + { + print ''; + } + else + { + print ''; + print $object->office_fax; + } + print '
    '.$langs->trans("Skype").''; - if ($caneditfield && empty($object->ldap_sid)) - { - print ''; - } - else - { - print ''; - print $object->skype; - } - print '
    '.$langs->trans("Skype").''; + if ($caneditfield && empty($object->ldap_sid)) + { + print ''; + } + else + { + print ''; + print $object->skype; + } + print '
    '; - if ($caneditfield && empty($object->ldap_sid)) - { - print ''; - } - else - { - print ''; - print $object->email; - } - print '
    '; + if ($caneditfield && empty($object->ldap_sid)) + { + print ''; + } + else + { + print ''; + print $object->email; + } + print '
    '.$langs->trans("OpenIDURL").''; - if ($caneditfield) - { - print ''; - } - else - { - print ''; - print $object->openid; - } - print '
    '.$langs->trans("OpenIDURL").''; + if ($caneditfield) + { + print ''; + } + else + { + print ''; + print $object->openid; + } + print '
    '.$langs->trans("AccountancyCode").''; - if ($caneditfield) - { - print ''; - } - else - { - print ''; - print $object->accountancy_code; - } - print '
    '.$langs->trans("AccountancyCode").''; + if ($caneditfield) + { + print ''; + } + else + { + print ''; + print $object->accountancy_code; + } + print '
    '.$langs->trans("HierarchicalResponsible").''; - if ($caneditfield) - { - print $form->select_dolusers($object->fk_user, 'fk_user', 1, array($object->id), 0, '', 0, $object->entity, 0, 0, '', 0, '', 'maxwidth300'); - } - else - { - print ''; - $huser=new User($db); - $huser->fetch($object->fk_user); - print $huser->getNomUrl(1); - } - print '
    '.$langs->trans("HierarchicalResponsible").''; + if ($caneditfield) + { + print $form->select_dolusers($object->fk_user, 'fk_user', 1, array($object->id), 0, '', 0, $object->entity, 0, 0, '', 0, '', 'maxwidth300'); + } + else + { + print ''; + $huser=new User($db); + $huser->fetch($object->fk_user); + print $huser->getNomUrl(1); + } + print '
    '; - $text=$langs->trans("THM"); - print $form->textwithpicto($text, $langs->trans("THMDescription"), 1, 'help', 'classthm'); - print ''; - print ''; - print '
    '; + $text=$langs->trans("THM"); + print $form->textwithpicto($text, $langs->trans("THMDescription"), 1, 'help', 'classthm'); + print ''; + print ''; + print '
    '; - $text=$langs->trans("TJM"); - print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classthm'); - print ''; - print ''; - print '
    '; + $text=$langs->trans("TJM"); + print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classthm'); + print ''; + print ''; + print '
    '.$langs->trans("Salary").''; - print ''; - print '
    '.$langs->trans("Salary").''; + print ''; + print '
    '.$langs->trans("WeeklyHours").''; - print ''; - print '
    '.$langs->trans("WeeklyHours").''; + print ''; + print '
    '.$langs->trans("DateEmployment").''; + // Date employment + print '
    '.$langs->trans("DateEmployment").''; echo $form->select_date(GETPOST('dateemployment')?GETPOST('dateemployment'):$object->dateemployment,'dateemployment',0,0,1,'form'.'dateemployment',1,0,1); print '
    '.$langs->trans("ColorUser").''; - print $formother->selectColor(GETPOST('color')?GETPOST('color'):$object->color, 'color', null, 1, '', 'hideifnotset'); - print '
    '.$langs->trans("ColorUser").''; + print $formother->selectColor(GETPOST('color')?GETPOST('color'):$object->color, 'color', null, 1, '', 'hideifnotset'); + print '
    '.$langs->trans("Photo").''; - print $form->showphoto('userphoto',$object,60,0,$caneditfield,'photowithmargin','small'); - print '
    '.$langs->trans("Photo").''; + print $form->showphoto('userphoto',$object,60,0,$caneditfield,'photowithmargin','small'); + print '
    ' . fieldLabel( 'Categories', 'usercats' ) . ''; - $cate_arbo = $form->select_all_categories( Categorie::TYPE_CONTACT, null, null, null, null, 1 ); - $c = new Categorie( $db ); - $cats = $c->containing($object->id, Categorie::TYPE_USER); - foreach ($cats as $cat) { - $arrayselected[] = $cat->id; - } - print $form->multiselectarray( 'usercats', $cate_arbo, $arrayselected, '', 0, '', 0, '90%' ); - print "
    ' . fieldLabel( 'Categories', 'usercats' ) . ''; + $cate_arbo = $form->select_all_categories( Categorie::TYPE_CONTACT, null, null, null, null, 1 ); + $c = new Categorie( $db ); + $cats = $c->containing($object->id, Categorie::TYPE_USER); + foreach ($cats as $cat) { + $arrayselected[] = $cat->id; + } + print $form->multiselectarray( 'usercats', $cate_arbo, $arrayselected, '', 0, '', 0, '90%' ); + print "
    '.$langs->trans("Status").''; - print $object->getLibStatut(4); - print '
    '.$langs->trans("Status").''; + print $object->getLibStatut(4); + print '
    '.$langs->trans("LinkToCompanyContact").''; - if ($object->socid > 0) - { - $societe = new Societe($db); - $societe->fetch($object->socid); - print $societe->getNomUrl(1,''); - if ($object->contactid) - { - $contact = new Contact($db); - $contact->fetch($object->contactid); - print ' / '.img_object($langs->trans("ShowContact"),'contact').' '.dol_trunc($contact->getFullName($langs),32).''; - } - } - else - { - print $langs->trans("ThisUserIsNot"); - } - print ' ('.$langs->trans("UseTypeFieldToChange").')'; - print '
    '.$langs->trans("LinkToCompanyContact").''; + if ($object->socid > 0) + { + $societe = new Societe($db); + $societe->fetch($object->socid); + print $societe->getNomUrl(1,''); + if ($object->contactid) + { + $contact = new Contact($db); + $contact->fetch($object->contactid); + print ' / '.img_object($langs->trans("ShowContact"),'contact').' '.dol_trunc($contact->getFullName($langs),32).''; + } + } + else + { + print $langs->trans("ThisUserIsNot"); + } + print ' ('.$langs->trans("UseTypeFieldToChange").')'; + print '
    '.$langs->trans("LinkedToDolibarrMember").''; - if ($object->fk_member) - { - $adh=new Adherent($db); - $adh->fetch($object->fk_member); - $adh->ref=$adh->login; // Force to show login instead of id - print $adh->getNomUrl(1); - } - else - { - print $langs->trans("UserNotLinkedToMember"); - } - print '
    '.$langs->trans("LinkedToDolibarrMember").''; + if ($object->fk_member) + { + $adh=new Adherent($db); + $adh->fetch($object->fk_member); + $adh->ref=$adh->login; // Force to show login instead of id + print $adh->getNomUrl(1); + } + else + { + print $langs->trans("UserNotLinkedToMember"); + } + print '
    '.$langs->trans("Signature").''; - if ($caneditfield) - { - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('signature',$object->signature,'',138,'dolibarr_mailings','In',false,true,empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1,ROWS_4,'90%'); - print $doleditor->Create(1); - } - else - { - print dol_htmlentitiesbr($object->signature); - } - print '
    '.$langs->trans("Signature").''; + if ($caneditfield) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor('signature',$object->signature,'',138,'dolibarr_mailings','In',false,true,empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1,ROWS_4,'90%'); + print $doleditor->Create(1); + } + else + { + print dol_htmlentitiesbr($object->signature); + } + print '
    '; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print '
    '; - print ''; - print '     '; - print ''; - print '
    '; + print '
    '; + print ''; + print '     '; + print ''; + print '
    '; - print '
    '; - } + print ''; + } - if ($action != 'edit') - { - print '
    '; - /* + if ($action != 'edit' && $action != 'presend') + { + print '
    '; + /* * Documents generes */ - $filename = dol_sanitizeFileName($object->ref); - $filedir = $conf->user->dir_output . "/" . dol_sanitizeFileName($object->ref); - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->user->user->lire; - $delallowed = $user->rights->user->user->creer; + $filename = dol_sanitizeFileName($object->ref); + $filedir = $conf->user->dir_output . "/" . dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $genallowed = $user->rights->user->user->lire; + $delallowed = $user->rights->user->user->creer; - print $formfile->showdocuments('user', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); - $somethingshown = $formfile->numoffiles; + print $formfile->showdocuments('user', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); + $somethingshown = $formfile->numoffiles; - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, null); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, null); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
    '; + 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, 'user', $socid); + // List of actions on element + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'user', $socid, 1); - print '
    '; - } + print '
    '; + } if (! empty($conf->ldap->enabled) && ! empty($object->ldap_sid)) $ldap->close(); - } + } } if (! empty($conf->api->enabled) && ! empty($conf->use_javascript_ajax)) { - print "\n".''; + print ''; } llxFooter(); diff --git a/htdocs/user/class/api_users.class.php b/htdocs/user/class/api_users.class.php index f119fa36ffa..ceade000872 100644 --- a/htdocs/user/class/api_users.class.php +++ b/htdocs/user/class/api_users.class.php @@ -22,14 +22,14 @@ use Luracast\Restler\RestException; /** * API class for users * - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} */ class Users extends DolibarrApi { /** * - * @var array $FIELDS Mandatory fields, checked when create and update object + * @var array $FIELDS Mandatory fields, checked when create and update object */ static $FIELDS = array( 'login' @@ -49,7 +49,7 @@ class Users extends DolibarrApi $this->useraccount = new User($this->db); } - + /** * List Users * @@ -63,24 +63,24 @@ class Users extends DolibarrApi * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" * @return array Array of User objects */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $user_ids = 0, $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '') { global $db, $conf; - + $obj_ret = array(); - + if(! DolibarrApiAccess::$user->rights->user->user->lire) { throw new RestException(401, "You are not allowed to read list of users"); } - + // case of external user, $societe param is ignored and replaced by user's socid //$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $societe; - + $sql = "SELECT t.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."user as t"; $sql.= ' WHERE t.entity IN ('.getEntity('user').')'; if ($user_ids) $sql.=" AND t.rowid IN (".$user_ids.")"; // Add sql filters - if ($sqlfilters) + if ($sqlfilters) { if (! DolibarrApi::_checkFilters($sqlfilters)) { @@ -89,7 +89,7 @@ class Users extends DolibarrApi $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - + $sql.= $db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) @@ -97,12 +97,12 @@ class Users extends DolibarrApi $page = 0; } $offset = $limit * $page; - + $sql.= $db->plimit($limit + 1, $offset); } - + $result = $db->query($sql); - + if ($result) { $num = $db->num_rows($result); @@ -125,7 +125,7 @@ class Users extends DolibarrApi } return $obj_ret; } - + /** * Get properties of an user object * @@ -133,7 +133,7 @@ class Users extends DolibarrApi * * @param int $id ID of user * @return array|mixed data without useless information - * + * * @throws RestException */ function get($id) { @@ -154,8 +154,8 @@ class Users extends DolibarrApi return $this->_cleanObjectDatas($this->useraccount); } - - + + /** * Create user account * @@ -185,14 +185,14 @@ class Users extends DolibarrApi } return $this->useraccount->id; } - - + + /** * Update account * * @param int $id Id of account to update - * @param array $request_data Datas - * @return int + * @param array $request_data Datas + * @return int */ function put($id, $request_data = NULL) { //if (!DolibarrApiAccess::$user->rights->user->user->creer) { @@ -228,7 +228,7 @@ class Users extends DolibarrApi * @param int $id User ID * @param int $group Group ID * @return int 1 if success - * + * * @url GET {id}/setGroup/{group} */ function setGroup($id, $group) { @@ -240,18 +240,18 @@ class Users extends DolibarrApi { throw new RestException(404, 'User not found'); } - + if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) { throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login); } - + $result = $this->useraccount->SetInGroup($group,1); if (! ($result > 0)) { throw new RestException(500, $this->useraccount->error); } - + return 1; } @@ -286,25 +286,25 @@ class Users extends DolibarrApi * @return array Array of cleaned object properties */ function _cleanObjectDatas($object) { - + $object = parent::_cleanObjectDatas($object); - + unset($object->default_values); 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; - } - + } + /** * Validate fields before create or update object - * + * * @param array|null $data Data to validate * @return array * @throws RestException diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php index 77ee103db63..b9e7378bd31 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -40,29 +40,30 @@ class User extends CommonObject { public $element='user'; public $table_element='user'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $id=0; public $ldap_sid; public $search_sid; public $employee; public $gender; + public $birth; public $email; public $skype; public $job; public $signature; public $address; - public $zip; - public $town; - public $state_id; - public $state_code; - public $state; + public $zip; + public $town; + public $state_id; + public $state_code; + public $state; public $office_phone; public $office_fax; public $user_mobile; public $admin; public $login; - public $api_key; + public $api_key; public $entity; //! Clear password in memory @@ -130,7 +131,8 @@ class User extends CommonObject public $dateemployment; // Define date of employment by company - + public $default_c_exp_tax_cat; + public $default_range; /** * Constructor de la classe @@ -161,7 +163,8 @@ class User extends CommonObject } /** - * Load a user from database with its id or ref (login) + * Load a user from database with its id or ref (login). + * This function does not load permissions, only user properties. Use getrights() for this just after the fetch. * * @param int $id If defined, id to used for search * @param string $login If defined, login to used for search @@ -178,7 +181,7 @@ class User extends CommonObject $login=trim($login); // Get user - $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.email, u.job, u.skype, u.signature, u.office_phone, u.office_fax, u.user_mobile,"; + $sql = "SELECT u.rowid, u.lastname, u.firstname, u.employee, u.gender, u.birth, u.email, u.job, u.skype, u.signature, u.office_phone, u.office_fax, u.user_mobile,"; $sql.= " u.address, u.zip, u.town, u.fk_state as state_id, u.fk_country as country_id,"; $sql.= " u.admin, u.login, u.note,"; $sql.= " u.pass, u.pass_crypted, u.pass_temp, u.api_key,"; @@ -199,22 +202,23 @@ class User extends CommonObject $sql.= " u.color,"; $sql.= " u.dateemployment,"; $sql.= " u.ref_int, u.ref_ext,"; - $sql.= " c.code as country_code, c.label as country,"; - $sql.= " d.code_departement as state_code, d.nom as state"; + $sql.= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode + $sql.= " c.code as country_code, c.label as country,"; + $sql.= " d.code_departement as state_code, d.nom as state"; $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON u.fk_country = c.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as d ON u.fk_state = d.rowid"; if ($entity < 0) { - if ((empty($conf->multicompany->enabled) || empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) && (! empty($user->entity))) - { - $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; - } - else - { - $sql.= " WHERE u.entity IS NOT NULL"; // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database - } + if ((empty($conf->multicompany->enabled) || empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) && (! empty($user->entity))) + { + $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; + } + else + { + $sql.= " WHERE u.entity IS NOT NULL"; // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database + } } else // The fetch was forced on an entity { @@ -237,7 +241,7 @@ class User extends CommonObject $sql.= " AND u.rowid = ".$id; } $sql.= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities - + $result = $this->db->query($sql); if ($result) { @@ -258,23 +262,24 @@ class User extends CommonObject $this->login = $obj->login; $this->gender = $obj->gender; + $this->birth = $this->db->jdate($obj->birth); $this->pass_indatabase = $obj->pass; $this->pass_indatabase_crypted = $obj->pass_crypted; $this->pass = $obj->pass; $this->pass_temp = $obj->pass_temp; - $this->api_key = $obj->api_key; + $this->api_key = $obj->api_key; - $this->address = $obj->address; - $this->zip = $obj->zip; - $this->town = $obj->town; + $this->address = $obj->address; + $this->zip = $obj->zip; + $this->town = $obj->town; - $this->country_id = $obj->country_id; - $this->country_code = $obj->country_id?$obj->country_code:''; - //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):''; + $this->country_id = $obj->country_id; + $this->country_code = $obj->country_id?$obj->country_code:''; + //$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):''; - $this->state_id = $obj->state_id; - $this->state_code = $obj->state_code; - $this->state = ($obj->state!='-'?$obj->state:''); + $this->state_id = $obj->state_id; + $this->state_code = $obj->state_code; + $this->state = ($obj->state!='-'?$obj->state:''); $this->office_phone = $obj->office_phone; $this->office_fax = $obj->office_fax; @@ -311,6 +316,9 @@ class User extends CommonObject $this->fk_member = $obj->fk_member; $this->fk_user = $obj->fk_user; + $this->default_range = $obj->default_range; + $this->default_c_exp_tax_cat = $obj->default_c_exp_tax_cat; + // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled, // in such case, this admin user must be admin for ALL entities. if (empty($conf->multicompany->enabled) && $this->admin && $this->entity == 1) $this->entity = 0; @@ -342,7 +350,7 @@ class User extends CommonObject // To get back the global configuration unique to the user if ($loadpersonalconf) { - // Load user->conf for user + // Load user->conf for user $sql = "SELECT param, value FROM ".MAIN_DB_PREFIX."user_param"; $sql.= " WHERE fk_user = ".$this->id; $sql.= " AND entity = ".$conf->entity; @@ -375,14 +383,35 @@ class User extends CommonObject $resql = $this->db->query($sql); if ($resql) { - while ($obj = $this->db->fetch_object($resql)) - { - if (! empty($obj->page) && ! empty($obj->type) && ! empty($obj->param)) - { - $this->default_values[$obj->page][$obj->type][$obj->param]=$obj->value; - } - } - $this->db->free($resql); + while ($obj = $this->db->fetch_object($resql)) + { + if (! empty($obj->page) && ! empty($obj->type) && ! empty($obj->param)) + { + // $obj->page is relative URL with or without params + // $obj->type can be 'filters', 'sortorder', 'createform', ... + // $obj->param is key or param + $pagewithoutquerystring=$obj->page; + $pagequeries=''; + if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) // There is query param + { + $pagewithoutquerystring=$reg[1]; + $pagequeries=$reg[2]; + } + $this->default_values[$pagewithoutquerystring][$obj->type][$pagequeries?$pagequeries:'_noquery_'][$obj->param]=$obj->value; + //if ($pagequeries) $this->default_values[$pagewithoutquerystring][$obj->type.'_queries']=$pagequeries; + } + } + // Sort by key, so _noquery_ is last + if(!empty($this->default_values)) { + foreach($this->default_values as $a => $b) + { + foreach($b as $c => $d) + { + krsort($this->default_values[$a][$c]); + } + } + } + $this->db->free($resql); } else { @@ -397,12 +426,13 @@ class User extends CommonObject /** * Add a right to the user * - * @param int $rid id du droit a ajouter - * @param string $allmodule Ajouter tous les droits du module allmodule - * @param string $allperms Ajouter tous les droits du module allmodule, perms allperms + * @param int $rid id of permission to add + * @param string $allmodule Add all permissions of module $allmodule + * @param string $allperms Add all permissions of module $allmodule, subperms $allperms only * @param int $entity Entity to use - * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers * @return int > 0 if OK, < 0 if KO + * @see clearrights, delrights, getrights */ function addrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0) { @@ -447,8 +477,11 @@ class User extends CommonObject // On a pas demande un droit en particulier mais une liste de droits // sur la base d'un nom de module de de perms // Where pour la liste des droits a ajouter - if (! empty($allmodule)) $whereforadd="module='".$this->db->escape($allmodule)."'"; - if (! empty($allperms)) $whereforadd=" AND perms='".$this->db->escape($allperms)."'"; + if (! empty($allmodule)) + { + $whereforadd="module='".$this->db->escape($allmodule)."'"; + if (! empty($allperms)) $whereforadd.=" AND perms='".$this->db->escape($allperms)."'"; + } } // Ajout des droits trouves grace au critere whereforadd @@ -487,12 +520,12 @@ class User extends CommonObject if (! $error && ! $notrigger) { - $this->context = array('audit'=>$langs->trans("PermissionsAdd")); + $this->context = array('audit'=>$langs->trans("PermissionsAdd")); - // Call trigger - $result=$this->call_trigger('USER_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers } if ($error) { @@ -514,8 +547,9 @@ class User extends CommonObject * @param string $allmodule Retirer tous les droits du module allmodule * @param string $allperms Retirer tous les droits du module allmodule, perms allperms * @param int $entity Entity to use - * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers * @return int > 0 if OK, < 0 if OK + * @see clearrights, addrights, getrights */ function delrights($rid, $allmodule='', $allperms='', $entity=0, $notrigger=0) { @@ -597,12 +631,12 @@ class User extends CommonObject if (! $error && ! $notrigger) { - $this->context = array('audit'=>$langs->trans("PermissionsDelete")); + $this->context = array('audit'=>$langs->trans("PermissionsDelete")); - // Call trigger - $result=$this->call_trigger('USER_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers } if ($error) { @@ -637,7 +671,7 @@ class User extends CommonObject * * @param string $moduletag Limit permission for a particular module ('' by default means load all permissions) * @return void - * @see clearrights + * @see clearrights, delrights, addrights */ function getrights($moduletag='') { @@ -812,10 +846,10 @@ class User extends CommonObject dol_syslog(get_class($this)."::setstatus", LOG_DEBUG); if ($result) { - // Call trigger - $result=$this->call_trigger('USER_ENABLEDISABLE',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_ENABLEDISABLE',$user); + if ($result < 0) { $error++; } + // End call triggers } if ($error) @@ -898,7 +932,7 @@ class User extends CommonObject if (! $error && ! $this->db->query($sql)) { $error++; - $this->error = $this->db->lasterror(); + $this->error = $this->db->lasterror(); } // Remove group @@ -906,7 +940,7 @@ class User extends CommonObject if (! $error && ! $this->db->query($sql)) { $error++; - $this->error = $this->db->lasterror(); + $this->error = $this->db->lasterror(); } // If contact, remove link @@ -916,44 +950,44 @@ class User extends CommonObject if (! $error && ! $this->db->query($sql)) { $error++; - $this->error = $this->db->lasterror(); + $this->error = $this->db->lasterror(); } } // Remove extrafields if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used - { + { $result=$this->deleteExtraFields(); if ($result < 0) { - $error++; - dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); - } - } + $error++; + dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); + } + } // Remove user - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if (! $this->db->query($sql)) - { - $error++; - $this->error = $this->db->lasterror(); - } - } + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->id; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + if (! $this->db->query($sql)) + { + $error++; + $this->error = $this->db->lasterror(); + } + } if (! $error) { - // Call trigger - $result=$this->call_trigger('USER_DELETE',$user); - if ($result < 0) - { - $error++; - $this->db->rollback(); - return -1; - } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_DELETE',$user); + if ($result < 0) + { + $error++; + $this->db->rollback(); + return -1; + } + // End call triggers $this->db->commit(); return 1; @@ -1061,10 +1095,10 @@ class User extends CommonObject if (! $notrigger) { - // Call trigger - $result=$this->call_trigger('USER_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -1117,7 +1151,7 @@ class User extends CommonObject $this->firstname = $contact->firstname; $this->gender = $contact->gender; $this->email = $contact->email; - $this->skype = $contact->skype; + $this->skype = $contact->skype; $this->office_phone = $contact->phone_pro; $this->office_fax = $contact->fax; $this->user_mobile = $contact->phone_mobile; @@ -1126,7 +1160,7 @@ class User extends CommonObject $this->town = $contact->town; $this->state_id = $contact->state_id; $this->country_id = $contact->country_id; - $this->employee = 0; + $this->employee = 0; if (empty($login)) $login=strtolower(substr($contact->firstname, 0, 4)) . strtolower(substr($contact->lastname, 0, 4)); $this->login = $login; @@ -1148,10 +1182,10 @@ class User extends CommonObject { $this->context['createfromcontact']='createfromcontact'; - // Call trigger - $result=$this->call_trigger('USER_CREATE',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_CREATE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers $this->db->commit(); return $this->id; @@ -1315,13 +1349,14 @@ class User extends CommonObject $this->employee = $this->employee?$this->employee:0; $this->login = trim($this->login); $this->gender = trim($this->gender); + $this->birth = trim($this->birth); $this->pass = trim($this->pass); - $this->api_key = trim($this->api_key); + $this->api_key = trim($this->api_key); $this->address = $this->address?trim($this->address):trim($this->address); - $this->zip = $this->zip?trim($this->zip):trim($this->zip); - $this->town = $this->town?trim($this->town):trim($this->town); - $this->state_id = trim($this->state_id); - $this->country_id = ($this->country_id > 0)?$this->country_id:0; + $this->zip = $this->zip?trim($this->zip):trim($this->zip); + $this->town = $this->town?trim($this->town):trim($this->town); + $this->state_id = trim($this->state_id); + $this->country_id = ($this->country_id > 0)?$this->country_id:0; $this->office_phone = trim($this->office_phone); $this->office_fax = trim($this->office_fax); $this->user_mobile = trim($this->user_mobile); @@ -1361,8 +1396,9 @@ class User extends CommonObject $sql.= ", firstname = '".$this->db->escape($this->firstname)."'"; $sql.= ", employee = ".$this->employee; $sql.= ", login = '".$this->db->escape($this->login)."'"; - $sql.= ", api_key = ".($this->api_key ? "'".$this->db->escape($this->api_key)."'" : "null"); + $sql.= ", api_key = ".($this->api_key ? "'".$this->db->escape($this->api_key)."'" : "null"); $sql.= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' + $sql.= ", birth=".(strval($this->birth)!='' ? "'".$this->db->idate($this->birth)."'" : 'null'); if (! empty($user->admin)) $sql.= ", admin = ".$this->admin; // admin flag can be set/unset only by an admin user $sql.= ", address = '".$this->db->escape($this->address)."'"; $sql.= ", zip = '".$this->db->escape($this->zip)."'"; @@ -1389,6 +1425,9 @@ class User extends CommonObject if (isset($this->salaryextra) || $this->salaryextra != '') $sql.= ", salaryextra= ".($this->salaryextra != ''?"'".$this->db->escape($this->salaryextra)."'":"null"); $sql.= ", weeklyhours= ".($this->weeklyhours != ''?"'".$this->db->escape($this->weeklyhours)."'":"null"); $sql.= ", entity = '".$this->db->escape($this->entity)."'"; + $sql.= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null'); + $sql.= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null'); + $sql.= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); @@ -1412,7 +1451,7 @@ class User extends CommonObject if ($this->fk_member > 0) { dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG); - $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL where fk_member = ".$this->fk_member; + $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL where fk_member = ".$this->fk_member; $resql = $this->db->query($sql); if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -5; } } @@ -1426,7 +1465,7 @@ class User extends CommonObject { if ($this->fk_member > 0 && ! $nosyncmember) { - dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG); + dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG); require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; @@ -1441,6 +1480,7 @@ class User extends CommonObject $adh->lastname=$this->lastname; $adh->login=$this->login; $adh->gender=$this->gender; + $adh->birth=$this->birth; $adh->pass=$this->pass; @@ -1457,10 +1497,10 @@ class User extends CommonObject $adh->user_login=$this->login; $result=$adh->update($user,0,1,0); - if ($result < 0) + if ($result < 0) { - $this->error=$adh->error; - $this->errors=$adh->errors; + $this->error=$adh->error; + $this->errors=$adh->errors; dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR); $error++; } @@ -1488,10 +1528,10 @@ class User extends CommonObject if (! $error && ! $notrigger) { - // Call trigger - $result=$this->call_trigger('USER_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -1578,11 +1618,11 @@ class User extends CommonObject // Mise a jour if (! $changelater) { - if (! is_object($this->oldcopy)) $this->oldcopy = clone $this; + if (! is_object($this->oldcopy)) $this->oldcopy = clone $this; - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."user"; + $sql = "UPDATE ".MAIN_DB_PREFIX."user"; $sql.= " SET pass_crypted = '".$this->db->escape($password_crypted)."',"; $sql.= " pass_temp = null"; if (! empty($conf->global->DATABASE_PWD_ENCRYPTED)) @@ -1635,10 +1675,10 @@ class User extends CommonObject if (! $error && ! $notrigger) { - // Call trigger - $result=$this->call_trigger('USER_NEW_PASSWORD',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_NEW_PASSWORD',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers } $this->db->commit(); @@ -1646,13 +1686,13 @@ class User extends CommonObject } else { - $this->db->rollback(); + $this->db->rollback(); return 0; } } else { - $this->db->rollback(); + $this->db->rollback(); dol_print_error($this->db); return -1; } @@ -1757,19 +1797,19 @@ class User extends CommonObject dol_syslog(get_class($this)."::send_password changelater is on, url=".$url); } - $mailfile = new CMailFile( - $subject, - $this->email, - $conf->notification->email_from, - $mesg, - array(), - array(), - array(), - '', - '', - 0, - $msgishtml - ); + $mailfile = new CMailFile( + $subject, + $this->email, + $conf->notification->email_from, + $mesg, + array(), + array(), + array(), + '', + '', + 0, + $msgishtml + ); if ($mailfile->sendfile()) { @@ -1900,13 +1940,13 @@ class User extends CommonObject { if (! $error && ! $notrigger) { - $this->newgroupid=$group; // deprecated. Remove this. - $this->context = array('audit'=>$langs->trans("UserSetInGroup"), 'newgroupid'=>$group); + $this->newgroupid=$group; // deprecated. Remove this. + $this->context = array('audit'=>$langs->trans("UserSetInGroup"), 'newgroupid'=>$group); - // Call trigger - $result=$this->call_trigger('USER_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -1955,13 +1995,13 @@ class User extends CommonObject { if (! $error && ! $notrigger) { - $this->oldgroupid=$group; // deprecated. Remove this. - $this->context = array('audit'=>$langs->trans("UserRemovedFromGroup"), 'oldgroupid'=>$group); + $this->oldgroupid=$group; // deprecated. Remove this. + $this->context = array('audit'=>$langs->trans("UserRemovedFromGroup"), 'oldgroupid'=>$group); - // Call trigger - $result=$this->call_trigger('USER_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('USER_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -1993,7 +2033,7 @@ class User extends CommonObject * @param int $width Width of image * @param int $height Height of image * @param string $cssclass Force a css class - * @param string $imagesize 'mini', 'small' or '' (original) + * @param string $imagesize 'mini', 'small' or '' (original) * @return string String with URL link */ function getPhotoUrl($width, $height, $cssclass='', $imagesize='') @@ -2001,27 +2041,28 @@ class User extends CommonObject $result=''; $result.=''; - $result.=Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize); - $result.=''; + $result.=Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize); + $result.=''; - return $result; + return $result; } /** * Return a link to the user card (with optionaly the picto) * Use this->id,this->lastname, this->firstname * - * @param int $withpictoimg Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto, -1=Include photo into link, -2=Only picto photo, -3=Only photo very small) - * @param string $option On what the link point to - * @param integer $infologin Add complete info tooltip - * @param integer $notooltip 1=Disable tooltip on picto and name - * @param int $maxlen Max length of visible user name - * @param int $hidethirdpartylogo Hide logo of thirdparty if user is external user - * @param string $mode ''=Show firstname and lastname, 'firstname'=Show only firstname, 'login'=Show login - * @param string $morecss Add more css on link - * @return string String with URL + * @param int $withpictoimg Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto, -1=Include photo into link, -2=Only picto photo, -3=Only photo very small) + * @param string $option On what the link point to + * @param integer $infologin Add complete info tooltip + * @param integer $notooltip 1=Disable tooltip on picto and name + * @param int $maxlen Max length of visible user name + * @param int $hidethirdpartylogo Hide logo of thirdparty if user is external user + * @param string $mode ''=Show firstname and lastname, 'firstname'=Show only firstname, 'login'=Show login + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - function getNomUrl($withpictoimg=0, $option='', $infologin=0, $notooltip=0, $maxlen=24, $hidethirdpartylogo=0, $mode='',$morecss='') + function getNomUrl($withpictoimg=0, $option='', $infologin=0, $notooltip=0, $maxlen=24, $hidethirdpartylogo=0, $mode='',$morecss='', $save_lastsearch_value=-1) { global $langs, $conf, $db, $hookmanager; global $dolibarr_main_authentication, $dolibarr_main_demo; @@ -2029,19 +2070,19 @@ class User extends CommonObject if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) $withpictoimg=0; - $result=''; $label=''; - $link=''; $linkstart=''; $linkend=''; + $result=''; $label=''; + $link=''; $linkstart=''; $linkend=''; if (! empty($this->photo)) { - $label.= '
    '; - $label.= Form::showphoto('userphoto', $this, 80, 0, 0, 'photowithmargin photologintooltip', 'small', 0, 1); - $label.= '
    '; + $label.= '
    '; + $label.= Form::showphoto('userphoto', $this, 0, 60, 0, 'photowithmargin photologintooltip', 'small', 0, 1); // Force height to 60 so we total height of tooltip can be calculated and collision can be managed + $label.= '
    '; } $label.= '
    '; $label.= '' . $langs->trans("User") . '
    '; - $label.= '' . $langs->trans('Name') . ': ' . $this->getFullName($langs,'',''); + $label.= '' . $langs->trans('Name') . ': ' . $this->getFullName($langs,''); if (! empty($this->login)) $label.= '
    ' . $langs->trans('Login') . ': ' . $this->login; $label.= '
    ' . $langs->trans("EMail").': '.$this->email; @@ -2079,10 +2120,18 @@ class User extends CommonObject if (! empty($_SESSION["disablemodules"])) $label.= '
    '.$langs->trans("DisabledModules").':
    '.join(', ',explode(',',$_SESSION["disablemodules"])); } + $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id; + if ($option == 'leave') $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id; - if ($option == 'leave') $link.= 'executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if ($reshook > 0) $linkclose = $hookmanager->resPrint; - $link.=$linkclose.'>'; + $linkstart.=$linkclose.'>'; $linkend=''; - //if ($withpictoimg == -1) $result.='
    '; - $result.=$link; - if ($withpictoimg) - { - $paddafterimage=''; + //if ($withpictoimg == -1) $result.='
    '; + $result.=$linkstart; + if ($withpictoimg) + { + $paddafterimage=''; if (abs($withpictoimg) == 1) $paddafterimage='style="margin-right: 3px;"'; - // Only picto + // Only picto if ($withpictoimg > 0) $picto='
    '.img_object('', 'user', $paddafterimage.' '.($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).'
    '; - // Picto must be a photo + // Picto must be a photo else $picto='
    '.Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg==-3?'small':''), 'mini', 0, 1).'
    '; - $result.=$picto; + $result.=$picto; } if ($withpictoimg > -2 && $withpictoimg != 2) { @@ -2136,7 +2185,7 @@ class User extends CommonObject } /** - * Renvoie login clicable (avec eventuellement le picto) + * Return clickable link of login (eventualy with picto) * * @param int $withpicto Include picto into link * @param string $option Sur quoi pointe le lien @@ -2148,17 +2197,19 @@ class User extends CommonObject $result=''; - $link = ''; + $linkstart = ''; $linkend=''; if ($option == 'xxx') { - $link = ''; + $linkstart = ''; $linkend=''; } - if ($withpicto) $result.=($link.img_object($langs->trans("ShowUser"),'user').$linkend.' '); - $result.=$link.$this->login.$linkend; + $result.=$linkstart; + if ($withpicto) $result.=img_object($langs->trans("ShowUser"), 'user', 'class="paddingright"'); + $result.=$this->login; + $result.=$linkend; return $result; } @@ -2224,8 +2275,8 @@ class User extends CommonObject * * @param array $info Info array loaded by _load_ldap_info * @param int $mode 0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb) - * 1= - * 2=Return key only (uid=qqq) + * 1=Return parent (ou=xxx,dc=aaa,dc=bbb) + * 2=Return key only (RDN) (uid=qqq) * @return string DN */ function _load_ldap_dn($info,$mode=0) @@ -2248,40 +2299,83 @@ class User extends CommonObject global $conf,$langs; $info=array(); + $keymodified=false; // Object classes $info["objectclass"]=explode(',',$conf->global->LDAP_USER_OBJECT_CLASS); $this->fullname=$this->getFullName($langs); + // Possible LDAP KEY (constname => varname) + $ldapkey = array( + 'LDAP_FIELD_FULLNAME' => 'fullname', + 'LDAP_FIELD_NAME' => 'lastname', + 'LDAP_FIELD_FIRSTNAME' => 'firstname', + 'LDAP_FIELD_LOGIN' => 'login', + 'LDAP_FIELD_LOGIN_SAMBA' => 'login', + 'LDAP_FIELD_PHONE' => 'office_phone', + 'LDAP_FIELD_MOBILE' => 'user_mobile', + 'LDAP_FIELD_FAX' => 'office_fax', + 'LDAP_FIELD_MAIL' => 'email', + 'LDAP_FIELD_SID' => 'ldap_sid', + 'LDAP_FIELD_SKYPE' => 'skype' + ); + // Champs - if ($this->fullname && ! empty($conf->global->LDAP_FIELD_FULLNAME)) $info[$conf->global->LDAP_FIELD_FULLNAME] = $this->fullname; - if ($this->lastname && ! empty($conf->global->LDAP_FIELD_NAME)) $info[$conf->global->LDAP_FIELD_NAME] = $this->lastname; - if ($this->firstname && ! empty($conf->global->LDAP_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_FIELD_FIRSTNAME] = $this->firstname; - if ($this->login && ! empty($conf->global->LDAP_FIELD_LOGIN)) $info[$conf->global->LDAP_FIELD_LOGIN] = $this->login; - if ($this->login && ! empty($conf->global->LDAP_FIELD_LOGIN_SAMBA)) $info[$conf->global->LDAP_FIELD_LOGIN_SAMBA] = $this->login; - if ($this->pass && ! empty($conf->global->LDAP_FIELD_PASSWORD)) $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte - if ($this->pass && ! empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // md5 for OpenLdap TODO add type of encryption - if ($this->ldap_sid && ! empty($conf->global->LDAP_FIELD_SID)) $info[$conf->global->LDAP_FIELD_SID] = $this->ldap_sid; - if ($this->societe_id > 0) + foreach ($ldapkey as $constname => $varname) + { + if (! empty($this->$varname) && ! empty($conf->global->$constname)) + { + $info[$conf->global->$constname] = $this->$varname; + + // Check if it is the LDAP key and if its value has been changed + if (! empty($conf->global->LDAP_KEY_USERS) && $conf->global->LDAP_KEY_USERS == $conf->global->$constname) + { + if (! empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) $keymodified=true; // For check if LDAP key has been modified + } + } + } + if ($this->address && ! empty($conf->global->LDAP_FIELD_ADDRESS)) $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address; + if ($this->zip && ! empty($conf->global->LDAP_FIELD_ZIP)) $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip; + if ($this->town && ! empty($conf->global->LDAP_FIELD_TOWN)) $info[$conf->global->LDAP_FIELD_TOWN] = $this->town; + if ($this->note_public && ! empty($conf->global->LDAP_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_FIELD_DESCRIPTION] = $this->note_public; + if ($this->socid > 0) { $soc = new Societe($this->db); - $soc->fetch($this->societe_id); + $soc->fetch($this->socid); - $info["o"] = $soc->lastname; + $info[$conf->global->LDAP_FIELD_COMPANY] = $soc->name; if ($soc->client == 1) $info["businessCategory"] = "Customers"; if ($soc->client == 2) $info["businessCategory"] = "Prospects"; if ($soc->fournisseur == 1) $info["businessCategory"] = "Suppliers"; } - if ($this->address && ! empty($conf->global->LDAP_FIELD_ADDRESS)) $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address; - if ($this->zip && ! empty($conf->global->LDAP_FIELD_ZIP)) $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip; - if ($this->town && ! empty($conf->global->LDAP_FIELD_TOWN)) $info[$conf->global->LDAP_FIELD_TOWN] = $this->town; - if ($this->office_phone && ! empty($conf->global->LDAP_FIELD_PHONE)) $info[$conf->global->LDAP_FIELD_PHONE] = $this->office_phone; - if ($this->user_mobile && ! empty($conf->global->LDAP_FIELD_MOBILE)) $info[$conf->global->LDAP_FIELD_MOBILE] = $this->user_mobile; - if ($this->office_fax && ! empty($conf->global->LDAP_FIELD_FAX)) $info[$conf->global->LDAP_FIELD_FAX] = $this->office_fax; - if ($this->note && ! empty($conf->global->LDAP_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_FIELD_DESCRIPTION] = $this->note; - if ($this->email && ! empty($conf->global->LDAP_FIELD_MAIL)) $info[$conf->global->LDAP_FIELD_MAIL] = $this->email; - if ($this->skype && ! empty($conf->global->LDAP_FIELD_SKYPE)) $info[$conf->global->LDAP_FIELD_SKYPE] = $this->skype; + + // When password is modified + if (! empty($this->pass)) + { + if (! empty($conf->global->LDAP_FIELD_PASSWORD)) $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte + if (! empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption) + } + // Set LDAP password if possible + else if ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password + { + if (! empty($conf->global->DATABASE_PWD_ENCRYPTED)) + { + // Just for the default MD5 ! + if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) + { + if ($this->pass_indatabase_crypted && ! empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) { + $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase_crypted, 5); // Create OpenLDAP MD5 password from Dolibarr MD5 password + } + } + } + // Use $this->pass_indatabase value if exists + else if (! empty($this->pass_indatabase)) + { + if (! empty($conf->global->LDAP_FIELD_PASSWORD)) $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte + if (! empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption + } + } if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') { @@ -2335,7 +2429,7 @@ class User extends CommonObject $this->gender='man'; $this->note='This is a note'; $this->email='email@specimen.com'; - $this->skype='tom.hanson'; + $this->skype='tom.hanson'; $this->office_phone='0999999999'; $this->office_fax='0999999998'; $this->user_mobile='0999999997'; @@ -2636,8 +2730,8 @@ class User extends CommonObject $result = $this->build_path_from_id_user($key,0); // Process a branch from the root user key (this user has no parent) if ($result < 0) { - $this->error='ErrorLoopInHierarchy'; - return -1; + $this->error='ErrorLoopInHierarchy'; + return -1; } } @@ -2677,26 +2771,26 @@ class User extends CommonObject */ function getAllChildIds($addcurrentuser=0) { - $childids=array(); + $childids=array(); - if (isset($this->cache_childids[$this->id])) - { - $childids = $this->cache_childids[$this->id]; - } - else - { - // Init this->users - $this->get_full_tree(); + if (isset($this->cache_childids[$this->id])) + { + $childids = $this->cache_childids[$this->id]; + } + else + { + // Init this->users + $this->get_full_tree(); - $idtoscan=$this->id; + $idtoscan=$this->id; - dol_syslog("Build childid for id = ".$idtoscan); - foreach($this->users as $id => $val) - { - //var_dump($val['fullpath']); - if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) $childids[$val['id']]=$val['id']; - } - } + dol_syslog("Build childid for id = ".$idtoscan); + foreach($this->users as $id => $val) + { + //var_dump($val['fullpath']); + if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) $childids[$val['id']]=$val['id']; + } + } $this->cache_childids[$this->id] = $childids; if ($addcurrentuser) $childids[$this->id]=$this->id; @@ -2737,7 +2831,7 @@ class User extends CommonObject return -1; // Should not happen. Protection against looping hierarchy } $useridfound[]=$this->parentof[$cursor_user]; - $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath']; + $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath']; $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname']; $i++; $cursor_user=$this->parentof[$cursor_user]; } @@ -2767,39 +2861,39 @@ class User extends CommonObject /** - * Charge indicateurs this->nb pour le tableau de bord - * - * @return int <0 if KO, >0 if OK - */ - function load_state_board() - { - global $conf; + * Charge indicateurs this->nb pour le tableau de bord + * + * @return int <0 if KO, >0 if OK + */ + function load_state_board() + { + global $conf; - $this->nb=array(); + $this->nb=array(); - $sql = "SELECT count(u.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE u.statut > 0"; - //$sql.= " AND employee != 0"; - $sql.= " AND u.entity IN (".getEntity('user').")"; + $sql = "SELECT count(u.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; + $sql.= " WHERE u.statut > 0"; + //$sql.= " AND employee != 0"; + $sql.= " AND u.entity IN (".getEntity('user').")"; - $resql=$this->db->query($sql); - if ($resql) - { - while ($obj=$this->db->fetch_object($resql)) - { - $this->nb["users"]=$obj->nb; - } - $this->db->free($resql); - return 1; - } - else - { - dol_print_error($this->db); - $this->error=$this->db->error(); - return -1; - } - } + $resql=$this->db->query($sql); + if ($resql) + { + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["users"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } /** * Create a document onto disk according to template module. diff --git a/htdocs/user/class/userbankaccount.class.php b/htdocs/user/class/userbankaccount.class.php index 77872bf8654..77385f84179 100644 --- a/htdocs/user/class/userbankaccount.class.php +++ b/htdocs/user/class/userbankaccount.class.php @@ -58,10 +58,11 @@ class UserBankAccount extends Account /** * Create bank information record * - * @param User $user User + * @param User $user User + * @param int $notrigger 1=Disable triggers * @return int <0 if KO, >= 0 if OK */ - function create($user='') + function create(User $user=null, $notrigger=0) { $now=dol_now(); @@ -87,10 +88,11 @@ class UserBankAccount extends Account /** * Update bank account * - * @param User $user Object user - * @return int <=0 if KO, >0 if OK + * @param User $user Object user + * @param int $notrigger 1=Disable triggers + * @return int <=0 if KO, >0 if OK */ - function update($user='') + function update(User $user=null, $notrigger=0) { global $conf; diff --git a/htdocs/user/class/usergroup.class.php b/htdocs/user/class/usergroup.class.php index 5240605c25c..7c326097669 100644 --- a/htdocs/user/class/usergroup.class.php +++ b/htdocs/user/class/usergroup.class.php @@ -36,7 +36,7 @@ class UserGroup extends CommonObject { public $element='usergroup'; public $table_element='usergroup'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='group'; public $entity; // Entity of group @@ -71,11 +71,12 @@ class UserGroup extends CommonObject /** * Charge un objet group avec toutes ces caracteristiques (except ->members array) * - * @param int $id id du groupe a charger - * @param string $groupname name du groupe a charger - * @return int <0 if KO, >0 if OK + * @param int $id Id of group to load + * @param string $groupname Name of group to load + * @param boolean $load_members Load all members of the group + * @return int <0 if KO, >0 if OK */ - function fetch($id='', $groupname='') + function fetch($id='', $groupname='', $load_members = true) { global $conf; @@ -107,7 +108,8 @@ class UserGroup extends CommonObject $this->datec = $obj->datec; $this->datem = $obj->datem; - $this->members=$this->listUsersForGroup(); + if($load_members) + $this->members=$this->listUsersForGroup(); // Retreive all extrafield for group @@ -135,10 +137,11 @@ class UserGroup extends CommonObject /** * Return array of groups objects for a particular user * - * @param int $userid User id to search - * @return array Array of groups objects + * @param int $userid User id to search + * @param boolean $load_members Load all members of the group + * @return array Array of groups objects */ - function listGroupsForUser($userid) + function listGroupsForUser($userid, $load_members = true) { global $conf, $user; @@ -168,7 +171,7 @@ class UserGroup extends CommonObject if (! array_key_exists($obj->rowid, $ret)) { $newgroup=new UserGroup($this->db); - $newgroup->fetch($obj->rowid); + $newgroup->fetch($obj->rowid, '', $load_members); $ret[$obj->rowid]=$newgroup; } diff --git a/htdocs/user/clicktodial.php b/htdocs/user/clicktodial.php index 2ba3c67d0b4..64919029536 100644 --- a/htdocs/user/clicktodial.php +++ b/htdocs/user/clicktodial.php @@ -53,7 +53,7 @@ $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - if ($action == 'update' && !GETPOST('cancel')) { + if ($action == 'update' && !GETPOST('cancel','alpha')) { $edituser = new User($db); $edituser->fetch($id); diff --git a/htdocs/user/document.php b/htdocs/user/document.php index bc4727feaa8..27cf4eb757a 100644 --- a/htdocs/user/document.php +++ b/htdocs/user/document.php @@ -94,7 +94,8 @@ if ($id > 0 || ! empty($ref)) } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('usercard','globalcard')); +$contextpage=array('usercard','userdoc','globalcard'); +$hookmanager->initHooks($contextpage); /* @@ -135,7 +136,7 @@ if ($object->id) if ($user->rights->user->user->lire || $user->admin) { $linkback = ''.$langs->trans("BackToList").''; } - + dol_banner_tab($object,'id',$linkback,$user->rights->user->user->lire || $user->admin); print '
    '; @@ -163,7 +164,7 @@ if ($object->id) print ''; print '
    '; - + dol_fiche_end(); diff --git a/htdocs/user/group/card.php b/htdocs/user/group/card.php index a32db37d3fb..0e2d77f749e 100644 --- a/htdocs/user/group/card.php +++ b/htdocs/user/group/card.php @@ -29,7 +29,6 @@ require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if(! empty($conf->multicompany->enabled)) dol_include_once('/multicompany/class/actions_multicompany.class.php'); // Defini si peux lire/modifier utilisateurs et permisssions $canreadperms=($user->admin || $user->rights->user->user->lire); @@ -66,159 +65,167 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); -$hookmanager->initHooks(array('groupcard','globalcard')); +// Initialize technical object to manage hooks. Note that conf->hooks_modules contains array +$contextpage=array('groupcard','globalcard'); +$hookmanager->initHooks($contextpage); /** - * Action remove group + * Actions */ -if ($action == 'confirm_delete' && $confirm == "yes") -{ - if ($caneditperms) - { - $object->fetch($id); - $object->delete(); - header("Location: index.php"); - exit; - } - else - { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorForbidden'), null, 'errors'); - } -} -/** - * Action add group - */ -if ($action == 'add') -{ - if ($caneditperms) - { - if (! $_POST["nom"]) { - setEventMessages($langs->trans("NameNotDefined"), null, 'errors'); - $action="create"; // Go back to create page - } else { - $object->nom = trim($_POST["nom"]); // For backward compatibility - $object->name = trim($_POST["nom"]); - $object->note = trim($_POST["note"]); +$parameters=array('id' => $id, 'userid' => $userid, 'caneditperms' => $caneditperms); +$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'); - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - if ($ret < 0) $error++; +if (empty($reshook)) { - if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $object->entity = 0; - else $object->entity = $_POST["entity"]; + // Action remove group + if ($action == 'confirm_delete' && $confirm == "yes") + { + if ($caneditperms) + { + $object->fetch($id); + $object->delete(); + header("Location: index.php"); + exit; + } + else + { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorForbidden'), null, 'errors'); + } + } - $db->begin(); + // Action add group + if ($action == 'add') + { + if ($caneditperms) + { + if (! $_POST["nom"]) { + setEventMessages($langs->trans("NameNotDefined"), null, 'errors'); + $action="create"; // Go back to create page + } else { + $object->nom = trim($_POST["nom"]); // For backward compatibility + $object->name = trim($_POST["nom"]); + $object->note = trim($_POST["note"]); - $id = $object->create(); + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; - if ($id > 0) - { - $db->commit(); + if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $object->entity = 0; + else $object->entity = $_POST["entity"]; - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - $db->rollback(); + $db->begin(); - $langs->load("errors"); - setEventMessages($langs->trans("ErrorGroupAlreadyExists",$object->name), null, 'errors'); - $action="create"; // Go back to create page - } - } - } - else - { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorForbidden'), null, 'errors'); - } -} + $id = $object->create(); + + if ($id > 0) + { + $db->commit(); + + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else + { + $db->rollback(); + + $langs->load("errors"); + setEventMessages($langs->trans("ErrorGroupAlreadyExists",$object->name), null, 'errors'); + $action="create"; // Go back to create page + } + } + } + else + { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorForbidden'), null, 'errors'); + } + } + + // Add/Remove user into group + if ($action == 'adduser' || $action =='removeuser') + { + if ($caneditperms) + { + if ($userid > 0) + { + $object->fetch($id); + $object->oldcopy = clone $object; + + $edituser = new User($db); + $edituser->fetch($userid); + if ($action == 'adduser') $result=$edituser->SetInGroup($object->id,$object->entity); + if ($action == 'removeuser') $result=$edituser->RemoveFromGroup($object->id,$object->entity); + + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else + { + setEventMessages($edituser->error, $edituser->errors, 'errors'); + } + } + } + else + { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorForbidden'), null, 'errors'); + } + } + + + if ($action == 'update') + { + if ($caneditperms) + { + $db->begin(); + + $object->fetch($id); -// Add/Remove user into group -if ($action == 'adduser' || $action =='removeuser') -{ - if ($caneditperms) - { - if ($userid > 0) - { - $object->fetch($id); $object->oldcopy = clone $object; - $edituser = new User($db); - $edituser->fetch($userid); - if ($action == 'adduser') $result=$edituser->SetInGroup($object->id,(! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)?GETPOST('entity','int'):$object->entity)); - if ($action == 'removeuser') $result=$edituser->RemoveFromGroup($object->id,(! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)?GETPOST('entity','int'):$object->entity)); + $object->name = trim($_POST["group"]); + $object->nom = $object->name; // For backward compatibility + $object->note = dol_htmlcleanlastbr($_POST["note"]); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - setEventMessages($edituser->error, $edituser->errors, 'errors'); - } - } - } - else - { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorForbidden'), null, 'errors'); - } + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; + + if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $object->entity = 0; + else $object->entity = $_POST["entity"]; + + $ret=$object->update(); + + if ($ret >= 0 && ! count($object->errors)) + { + setEventMessages($langs->trans("GroupModified"), null, 'mesgs'); + $db->commit(); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); + } + } + else + { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorForbidden'), null, 'mesgs'); + } + } + + // Actions to build doc + $upload_dir = $conf->usergroup->dir_output; + $permissioncreate=$user->rights->user->user->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; } -if ($action == 'update') -{ - if ($caneditperms) - { - $db->begin(); - - $object->fetch($id); - - $object->oldcopy = clone $object; - - $object->name = trim($_POST["group"]); - $object->nom = $object->name; // For backward compatibility - $object->note = dol_htmlcleanlastbr($_POST["note"]); - - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - if ($ret < 0) $error++; - - if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $object->entity = 0; - else $object->entity = $_POST["entity"]; - - $ret=$object->update(); - - if ($ret >= 0 && ! count($object->errors)) - { - setEventMessages($langs->trans("GroupModified"), null, 'mesgs'); - $db->commit(); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - $db->rollback(); - } - } - else - { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorForbidden'), null, 'mesgs'); - } -} - -// Actions to build doc -$upload_dir = $conf->usergroup->dir_output; -$permissioncreate=$user->rights->user->user->creer; -include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - - - /* * View */ @@ -385,117 +392,87 @@ else // On selectionne les users qui ne sont pas deja dans le groupe $exclude = array(); - if (! empty($object->members)) - { - if (! (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))) - { - foreach($object->members as $useringroup) - { - $exclude[]=$useringroup->id; - } - } - } - - if ($caneditperms) - { - print '
    '."\n"; - print ''; - print ''; - print ''."\n"; - print ''."\n"; - print ''; - print "'."\n"; - print '
    '.$langs->trans("NonAffectedUsers").''; - print $form->select_dolusers('', 'user', 1, $exclude, 0, '', '', $object->entity, 0, 0, '', 0, '', 'maxwidth300'); - print '   '; - // Multicompany - if (! empty($conf->multicompany->enabled) && is_object($mc)) - { - if ($conf->entity == 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) - { - print ''.$langs->trans("Entity").'".$mc->select_entities($conf->entity); - } - else - { - print ''; - } - } - else - { - print ''; - } - print ''; - print '
    '."\n"; - print '
    '; - } - - /* - * Group members - */ - print ''; - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->multicompany->enabled) && $conf->entity == 1) - { - print ''; - } - print ''; - print ''; - print "\n"; - if (! empty($object->members)) { foreach($object->members as $useringroup) { - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->multicompany->enabled) && is_object($mc) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity) - { - print ''; - } - print ''; - print '\n"; + $exclude[]=$useringroup->id; } - } - else - { - print ''; - } - print "
    '.$langs->trans("Login").''.$langs->trans("Lastname").''.$langs->trans("Firstname").''.$langs->trans("Entity").''.$langs->trans("Status").' 
    '; - print $useringroup->getNomUrl(-1, '', 0, 0, 24, 0, 'login'); - if ($useringroup->admin && ! $useringroup->entity) print img_picto($langs->trans("SuperAdministrator"),'redstar'); - else if ($useringroup->admin) print img_picto($langs->trans("Administrator"),'star'); - print ''.$useringroup->lastname.''.$useringroup->firstname.''; - if (! empty($useringroup->usergroup_entity)) - { - $nb=0; - foreach($useringroup->usergroup_entity as $group_entity) - { - $mc->getInfo($group_entity); - print ($nb > 0 ? ', ' : '').$mc->label; - print ''; - print img_delete($langs->trans("RemoveFromGroup")); - print ''; - $nb++; - } - } - print ''.$useringroup->getLibStatut(3).''; - if (! empty($user->admin) && empty($conf->multicompany->enabled)) - { - print ''; - print img_delete($langs->trans("RemoveFromGroup")); - print ''; - } - else - { - print "-"; - } - print "
    '.$langs->trans("None").'
    "; - print "
    "; + } + + // Other form for add user to group + $parameters=array('caneditperms' => $caneditperms, 'exclude' => $exclude); + $reshook=$hookmanager->executeHooks('formAddUserToGroup',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + if (empty($reshook)) + { + if ($caneditperms) + { + print '
    '."\n"; + print ''; + print ''; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print '
    '.$langs->trans("NonAffectedUsers").''; + print $form->select_dolusers('', 'user', 1, $exclude, 0, '', '', $object->entity, 0, 0, '', 0, '', 'maxwidth300'); + print '   '; + print ''; + print ''; + print '
    '."\n"; + print '
    '; + } + + /* + * Group members + */ + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + if (! empty($object->members)) + { + foreach($object->members as $useringroup) + { + print ''; + print ''; + print ''; + print ''; + print ''; + print '\n"; + } + } + else + { + print ''; + } + print "
    '.$langs->trans("Login").''.$langs->trans("Lastname").''.$langs->trans("Firstname").''.$langs->trans("Status").' 
    '; + print $useringroup->getNomUrl(-1, '', 0, 0, 24, 0, 'login'); + if ($useringroup->admin && ! $useringroup->entity) print img_picto($langs->trans("SuperAdministrator"),'redstar'); + else if ($useringroup->admin) print img_picto($langs->trans("Administrator"),'star'); + print ''.$useringroup->lastname.''.$useringroup->firstname.''.$useringroup->getLibStatut(3).''; + if (! empty($user->admin)) + { + print ''; + print img_delete($langs->trans("RemoveFromGroup")); + print ''; + } + else + { + print "-"; + } + print "
    '.$langs->trans("None").'
    "; + } + + print "
    "; + + print '
    '; /* * Documents generes @@ -517,7 +494,7 @@ else // List of actions on element include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'usergroup', $socid); + $somethingshown = $formactions->showactions($object, 'usergroup', $socid, 1); print '
    '; diff --git a/htdocs/user/group/index.php b/htdocs/user/group/index.php index 9624e462a71..f4b962fb86f 100644 --- a/htdocs/user/group/index.php +++ b/htdocs/user/group/index.php @@ -68,8 +68,8 @@ $fieldstosearchall = array( * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters); // Note that $action and $object may have been modified by some hooks diff --git a/htdocs/user/group/ldap.php b/htdocs/user/group/ldap.php index c195136863e..ae0d974be9a 100644 --- a/htdocs/user/group/ldap.php +++ b/htdocs/user/group/ldap.php @@ -63,30 +63,31 @@ $object->getrights(); if ($action == 'dolibarr2ldap') { - $db->begin(); - $ldap=new Ldap(); $result=$ldap->connect_bind(); - $info=$object->_load_ldap_info(); - // Get a gid number for objectclass PosixGroup - if(in_array('posixGroup',$info['objectclass'])) - $info['gidNumber'] = $ldap->getNextGroupGid(); + if ($result > 0) + { + $info=$object->_load_ldap_info(); - $dn=$object->_load_ldap_dn($info); - $olddn=$dn; // We can say that old dn = dn as we force synchro + // Get a gid number for objectclass PosixGroup + if (in_array('posixGroup',$info['objectclass'])) { + $info['gidNumber'] = $ldap->getNextGroupGid('LDAP_KEY_GROUPS'); + } - $result=$ldap->update($dn,$info,$user,$olddn); + $dn=$object->_load_ldap_dn($info); + $olddn=$dn; // We can say that old dn = dn as we force synchro + + $result=$ldap->update($dn,$info,$user,$olddn); + } if ($result >= 0) { setEventMessages($langs->trans("GroupSynchronized"), null, 'mesgs'); - $db->commit(); } else { setEventMessages($ldap->error, $ldap->errors, 'errors'); - $db->rollback(); } } @@ -206,12 +207,10 @@ if ($result > 0) } else { - dol_print_error('',$ldap->error); + setEventMessages($ldap->error, $ldap->errors, 'errors'); } print ''; llxFooter(); - $db->close(); - diff --git a/htdocs/user/group/perms.php b/htdocs/user/group/perms.php index 46477879b14..836049443d3 100644 --- a/htdocs/user/group/perms.php +++ b/htdocs/user/group/perms.php @@ -38,11 +38,6 @@ $confirm=GETPOST('confirm', 'alpha'); $module=GETPOST('module', 'alpha'); $rights=GETPOST('rights', 'int'); -// Users/Groups management only in master entity if transverse mode -if (! empty($conf->multicompany->enabled) && $conf->entity > 1 && $conf->global->MULTICOMPANY_TRANSVERSE_MODE) -{ - accessforbidden(); -} // Defini si peux lire les permissions $canreadperms=($user->admin || $user->rights->user->user->lire); @@ -64,16 +59,10 @@ $object->fetch($id); $object->getrights(); $entity=$conf->entity; -if (! empty($conf->multicompany->enabled)) -{ - if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - $entity=(GETPOST('entity','int') ? GETPOST('entity','int') : $conf->entity); - else - $entity=(! empty($object->entity) ? $object->entity : $conf->entity); -} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('groupcard','globalcard')); +$contextpage=array('groupcard','globalcard'); +$hookmanager->initHooks($contextpage); /** diff --git a/htdocs/user/index.php b/htdocs/user/index.php index f9989827021..7e5820dac66 100644 --- a/htdocs/user/index.php +++ b/htdocs/user/index.php @@ -26,9 +26,6 @@ */ require '../main.inc.php'; -if (! empty($conf->multicompany->enabled)) - dol_include_once('/multicompany/class/actions_multicompany.class.php', 'ActionsMulticompany'); - if (! $user->rights->user->user->lire && ! $user->admin) accessforbidden(); @@ -75,37 +72,37 @@ $form = new Form($db); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( 'u.login'=>"Login", - 'u.lastname'=>"Lastname", - 'u.firstname'=>"Firstname", + 'u.lastname'=>"Lastname", + 'u.firstname'=>"Firstname", 'u.accountancy_code'=>"AccountancyCode", 'u.email'=>"EMail", - 'u.note'=>"Note" + 'u.note'=>"Note" ); // Definition of fields for list $arrayfields=array( - 'u.login'=>array('label'=>$langs->trans("Login"), 'checked'=>1), - 'u.lastname'=>array('label'=>$langs->trans("Lastname"), 'checked'=>1), - 'u.firstname'=>array('label'=>$langs->trans("Firstname"), 'checked'=>1), - 'u.gender'=>array('label'=>$langs->trans("Gender"), 'checked'=>0), - 'u.employee'=>array('label'=>$langs->trans("Employee"), 'checked'=>($mode=='employee'?1:0)), - 'u.accountancy_code'=>array('label'=>$langs->trans("AccountancyCode"), 'checked'=>0), - 'u.email'=>array('label'=>$langs->trans("EMail"), 'checked'=>1), - 'u.fk_soc'=>array('label'=>$langs->trans("Company"), 'checked'=>1), - 'u.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), - 'u.fk_user'=>array('label'=>$langs->trans("HierarchicalResponsible"), 'checked'=>1), - 'u.datelastlogin'=>array('label'=>$langs->trans("LastConnexion"), 'checked'=>1, 'position'=>100), - 'u.datepreviouslogin'=>array('label'=>$langs->trans("PreviousConnexion"), 'checked'=>0, 'position'=>110), - 'u.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'u.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'u.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'u.login'=>array('label'=>$langs->trans("Login"), 'checked'=>1), + 'u.lastname'=>array('label'=>$langs->trans("Lastname"), 'checked'=>1), + 'u.firstname'=>array('label'=>$langs->trans("Firstname"), 'checked'=>1), + 'u.gender'=>array('label'=>$langs->trans("Gender"), 'checked'=>0), + 'u.employee'=>array('label'=>$langs->trans("Employee"), 'checked'=>($mode=='employee'?1:0)), + 'u.accountancy_code'=>array('label'=>$langs->trans("AccountancyCode"), 'checked'=>0), + 'u.email'=>array('label'=>$langs->trans("EMail"), 'checked'=>1), + 'u.fk_soc'=>array('label'=>$langs->trans("Company"), 'checked'=>1), + 'u.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))), + 'u.fk_user'=>array('label'=>$langs->trans("HierarchicalResponsible"), 'checked'=>1), + 'u.datelastlogin'=>array('label'=>$langs->trans("LastConnexion"), 'checked'=>1, 'position'=>100), + 'u.datepreviouslogin'=>array('label'=>$langs->trans("PreviousConnexion"), 'checked'=>0, 'position'=>110), + 'u.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'u.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'u.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -135,8 +132,8 @@ if ($mode == 'employee') $search_employee=1; * Actions */ -if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters); // Note that $action and $object may have been modified by some hooks @@ -144,29 +141,29 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search_user=""; - $search_login=""; - $search_lastname=""; - $search_firstname=""; - $search_gender=""; - $search_employee=""; - $search_accountancy_code=""; - $search_email=""; - $search_statut=""; - $search_thirdparty=""; - $search_supervisor=""; - $search_datelastlogin=""; - $search_datepreviouslogin=""; - $search_date_creation=""; - $search_date_update=""; - $search_array_options=array(); - } + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_user=""; + $search_login=""; + $search_lastname=""; + $search_firstname=""; + $search_gender=""; + $search_employee=""; + $search_accountancy_code=""; + $search_email=""; + $search_statut=""; + $search_thirdparty=""; + $search_supervisor=""; + $search_datelastlogin=""; + $search_datepreviouslogin=""; + $search_date_creation=""; + $search_date_update=""; + $search_array_options=array(); + } } @@ -220,16 +217,16 @@ if ($sall) $sql.= natural_search(array_keys($fieldstos // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -241,7 +238,7 @@ $nbtotalofrecords=0; $result=$db->query($sql); if ($result) { - $nbtotalofrecords = $db->num_rows($result); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1, $offset); @@ -249,18 +246,18 @@ $sql.= $db->plimit($limit+1, $offset); $result = $db->query($sql); if (! $result) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($result); if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/user/card.php?id='.$id); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/user/card.php?id='.$id); + exit; } llxHeader('',$langs->trans("ListOfUsers")); @@ -284,9 +281,9 @@ if ($mode != '') $param.='&mode='.$mode; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } $text = $langs->trans("ListOfUsers"); @@ -305,8 +302,8 @@ print_barre_liste($text, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sorto if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } $moreforfilter=''; @@ -322,59 +319,59 @@ print ''; if (! empty($arrayfields['u.login']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.lastname']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.firstname']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.gender']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.employee']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.accountancy_code']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.email']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.fk_soc']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.entity']['checked'])) { - print ''; + print ''; } // Supervisor if (! empty($arrayfields['u.fk_user']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.datelastlogin']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['u.datepreviouslogin']['checked'])) { - print ''; + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -383,12 +380,12 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { if (! empty($arrayfields["ef.".$key]['checked'])) { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; + // Date creation + print ''; } if (! empty($arrayfields['u.tms']['checked'])) { - // Date modification - print ''; + // Date modification + print ''; } if (! empty($arrayfields['u.statut']['checked'])) { - // Status - print ''; + // Status + print ''; } // Action column print '"; - if (! empty($arrayfields['u.login']['checked'])) + print ""; + if (! empty($arrayfields['u.login']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + if (! empty($conf->multicompany->enabled) && $obj->admin && ! $obj->entity) + { + print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); + } + else if ($obj->admin) + { + print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); + } + print ''; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.lastname']['checked'])) + if (! empty($arrayfields['u.lastname']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.firstname']['checked'])) + if (! empty($arrayfields['u.firstname']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.gender']['checked'])) + if (! empty($arrayfields['u.gender']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.employee']['checked'])) + if (! empty($arrayfields['u.employee']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['u.accountancy_code']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['u.email']['checked'])) + if (! empty($arrayfields['u.email']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['u.fk_soc']['checked'])) { print "'; - if (! $i) $totalarray['nbfield']++; - } - // Multicompany enabled - if (! empty($conf->multicompany->enabled) && is_object($mc) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if (! empty($arrayfields['u.entity']['checked'])) + if ($obj->fk_soc) { - print ''; - if (! $i) $totalarray['nbfield']++; + $companystatic->id=$obj->fk_soc; + $companystatic->name=$obj->name; + $companystatic->canvas=$obj->canvas; + print $companystatic->getNomUrl(1); } - } - // Supervisor - if (! empty($arrayfields['u.fk_user']['checked'])) + else if ($obj->ldap_sid) + { + print $langs->trans("DomainUser"); + } + else + { + print $langs->trans("InternalUser"); + } + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Multicompany enabled + if (! empty($conf->multicompany->enabled) && is_object($mc) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + if (! empty($arrayfields['u.entity']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + // Supervisor + if (! empty($arrayfields['u.fk_user']['checked'])) { // Resp - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } - // Date last login - if (! empty($arrayfields['u.datelastlogin']['checked'])) + // Date last login + if (! empty($arrayfields['u.datelastlogin']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } - // Date previous login - if (! empty($arrayfields['u.datepreviouslogin']['checked'])) + // Date previous login + if (! empty($arrayfields['u.datepreviouslogin']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Extra fields @@ -635,44 +632,44 @@ while ($i < min($num,$limit)) $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['u.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['u.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['u.statut']['checked'])) - { + if (! empty($arrayfields['u.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['u.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['u.statut']['checked'])) + { $userstatic->statut=$obj->statut; - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; - print "\n"; + print "\n"; - $i++; + $i++; } $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); diff --git a/htdocs/user/ldap.php b/htdocs/user/ldap.php index 49739fa7c77..1b5f7c77b78 100644 --- a/htdocs/user/ldap.php +++ b/htdocs/user/ldap.php @@ -1,6 +1,6 @@ - * Copyright (C) 2006-2015 Regis Houssin + * Copyright (C) 2006-2017 Regis Houssin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -46,7 +46,9 @@ $object->fetch($id, '', '', 1); $object->getrights(); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('usercard','globalcard')); +$contextpage=array('usercard','userldap','globalcard'); +$hookmanager->initHooks($contextpage); + /* * Actions @@ -57,30 +59,29 @@ $parameters=array('id'=>$socid); $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)) { - if ($_GET["action"] == 'dolibarr2ldap') { - $db->begin(); +if (empty($reshook)) +{ + if ($_GET["action"] == 'dolibarr2ldap') + { + $ldap = new Ldap(); + $result = $ldap->connect_bind(); - $ldap = new Ldap(); - $result = $ldap->connect_bind(); + if ($result > 0) + { + $info = $object->_load_ldap_info(); + $dn = $object->_load_ldap_dn($info); + $olddn = $dn; // We can say that old dn = dn as we force synchro - $info = $object->_load_ldap_info(); - $dn = $object->_load_ldap_dn($info); - $olddn = $dn; // We can say that old dn = dn as we force synchro + $result = $ldap->update($dn, $info, $user, $olddn); + } - $result = $ldap->update($dn, $info, $user, $olddn); - - if ($result >= 0) - { - setEventMessages($langs->trans("UserSynchronized"), null, 'mesgs'); - $db->commit(); - } - else - { - setEventMessages($ldap->error, $ldap->errors, 'errors'); - $db->rollback(); - } - } + if ($result >= 0) { + setEventMessages($langs->trans("UserSynchronized"), null, 'mesgs'); + } + else { + setEventMessages($ldap->error, $ldap->errors, 'errors'); + } + } } /* @@ -113,25 +114,25 @@ print '
    '; - $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); - print $form->selectarray('search_gender', $arraygender, $search_gender, 1); - print ''; + $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); + print $form->selectarray('search_gender', $arraygender, $search_gender, 1); + print ''; - print $form->selectyesno('search_employee', $search_employee, 1, false, 1); - print ''; + print $form->selectyesno('search_employee', $search_employee, 1, false, 1); + print ''; - print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, array(), 0, '', 0, 0, 0, 0, '', 0, '', 'maxwidth200'); - print ''; + print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, array(), 0, '', 0, 0, 0, 0, '', 0, '', 'maxwidth200'); + print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) { - $crit=$val; + $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); $searchclass=''; if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; @@ -405,22 +402,22 @@ $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // N print $hookmanager->resPrint; if (! empty($arrayfields['u.datec']['checked'])) { - // Date creation - print ''; - print ''; + print ''; - print ''; + print ''; - print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); - print ''; + print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); + print ''; @@ -447,16 +444,16 @@ if (! empty($arrayfields['u.datepreviouslogin']['checked'])) print_liste_field_t // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -474,151 +471,151 @@ $i = 0; $totalarray=array(); while ($i < min($num,$limit)) { - $obj = $db->fetch_object($result); + $obj = $db->fetch_object($result); $userstatic->id=$obj->rowid; $userstatic->ref=$obj->label; $userstatic->login=$obj->login; $userstatic->statut=$obj->statut; - $userstatic->email=$obj->email; - $userstatic->gender=$obj->gender; - $userstatic->societe_id=$obj->fk_soc; - $userstatic->firstname=$obj->firstname; + $userstatic->email=$obj->email; + $userstatic->gender=$obj->gender; + $userstatic->societe_id=$obj->fk_soc; + $userstatic->firstname=$obj->firstname; $userstatic->lastname=$obj->lastname; $userstatic->employee=$obj->employee; $userstatic->photo=$obj->photo; $li=$userstatic->getNomUrl(-1,'',0,0,24,1,'login'); - print "
    '; + print ''; print $li; - if (! empty($conf->multicompany->enabled) && $obj->admin && ! $obj->entity) - { - print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); - } - else if ($obj->admin) - { - print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); - } - print ''.$obj->lastname.''.$obj->lastname.''.$obj->firstname.''; if ($obj->gender) print $langs->trans("Gender".$obj->gender); print ''.yn($obj->employee).''.$obj->accountancy_code.''.$obj->email.'"; - if ($obj->fk_soc) - { - $companystatic->id=$obj->fk_soc; - $companystatic->name=$obj->name; - $companystatic->canvas=$obj->canvas; - print $companystatic->getNomUrl(1); - } - else if ($obj->ldap_sid) - { - print $langs->trans("DomainUser"); - } - else - { - print $langs->trans("InternalUser"); - } - print ''; - if (! $obj->entity) - { - print $langs->trans("AllEntities"); - } - else - { - $mc->getInfo($obj->entity); - print $mc->label; - } - print ''; + if (! $obj->entity) + { + print $langs->trans("AllEntities"); + } + else + { + $mc->getInfo($obj->entity); + print $mc->label; + } + print ''; - if ($obj->login2) - { - $user2->id=$obj->id2; - $user2->login=$obj->login2; - $user2->lastname=$obj->lastname2; - $user2->firstname=$obj->firstname2; - $user2->gender=$obj->gender2; - $user2->photo=$obj->photo2; - $user2->admin=$obj->admin2; - $user2->email=$obj->email2; - $user2->socid=$obj->fk_soc2; - print $user2->getNomUrl(-1,'',0,0,24,0,''); - if (! empty($conf->multicompany->enabled) && $obj->admin2 && ! $obj->entity2) - { - print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); - } - else if ($obj->admin2) - { - print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); - } - } - print ''; + if ($obj->login2) + { + $user2->id=$obj->id2; + $user2->login=$obj->login2; + $user2->lastname=$obj->lastname2; + $user2->firstname=$obj->firstname2; + $user2->gender=$obj->gender2; + $user2->photo=$obj->photo2; + $user2->admin=$obj->admin2; + $user2->email=$obj->email2; + $user2->socid=$obj->fk_soc2; + print $user2->getNomUrl(-1,'',0,0,24,0,''); + if (! empty($conf->multicompany->enabled) && $obj->admin2 && ! $obj->entity2) + { + print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); + } + else if ($obj->admin2) + { + print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); + } + } + print ''.dol_print_date($db->jdate($obj->datelastlogin),"dayhour").''.dol_print_date($db->jdate($obj->datelastlogin),"dayhour").''.dol_print_date($db->jdate($obj->datepreviouslogin),"dayhour").''.dol_print_date($db->jdate($obj->datepreviouslogin),"dayhour").''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$userstatic->getLibStatut(3).''.$userstatic->getLibStatut(3).'
    '; print ''; if ($object->ldap_sid) { - print ''; + print ''; } else { - print ''; + print ''; } print ''; if ($conf->global->LDAP_SERVER_TYPE == "activedirectory") { - $ldap = new Ldap(); - $result = $ldap->connect_bind(); - if ($result > 0) - { - $userSID = $ldap->getObjectSid($object->login); - } - print ''; - print ''; - print "\n"; + $ldap = new Ldap(); + $result = $ldap->connect_bind(); + if ($result > 0) + { + $userSID = $ldap->getObjectSid($object->login); + } + print ''; + print ''; + print "\n"; } // LDAP DN @@ -161,7 +162,7 @@ print '
    '; if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') { - print ''.$langs->trans("ForceSynchronize").''; + print ''.$langs->trans("ForceSynchronize").''; } print "
    \n"; @@ -185,36 +186,36 @@ $ldap=new Ldap(); $result=$ldap->connect_bind(); if ($result > 0) { - $info=$object->_load_ldap_info(); - $dn=$object->_load_ldap_dn($info,1); - $search = "(".$object->_load_ldap_dn($info,2).")"; - $records = $ldap->getAttribute($dn,$search); + $info=$object->_load_ldap_info(); + $dn=$object->_load_ldap_dn($info,1); + $search = "(".$object->_load_ldap_dn($info,2).")"; + $records = $ldap->getAttribute($dn,$search); - //print_r($records); + //print_r($records); - // Affichage arbre - if ((! is_numeric($records) || $records != 0) && (! isset($records['count']) || $records['count'] > 0)) - { - if (! is_array($records)) - { - print ''; - } - else - { - $result=show_ldap_content($records,0,$records['count'],true); - } - } - else - { - print ''; - } + // Affichage arbre + if ((! is_numeric($records) || $records != 0) && (! isset($records['count']) || $records['count'] > 0)) + { + if (! is_array($records)) + { + print ''; + } + else + { + $result=show_ldap_content($records,0,$records['count'],true); + } + } + else + { + print ''; + } - $ldap->unbind(); - $ldap->close(); + $ldap->unbind(); + $ldap->close(); } else { - dol_print_error('',$ldap->error); + setEventMessages($ldap->error, $ldap->errors, 'errors'); } print '
    '.$langs->trans("Login").''.$langs->trans("LoginAccountDisableInDolibarr").''.$langs->trans("LoginAccountDisableInDolibarr").''.$object->login.''.$object->login.'
    '.$langs->trans("SID").''.$userSID.'
    '.$langs->trans("SID").''.$userSID.'
    '.$langs->trans("ErrorFailedToReadLDAP").'
    '.$langs->trans("LDAPRecordNotFound").' (dn='.$dn.' - search='.$search.')
    '.$langs->trans("ErrorFailedToReadLDAP").'
    '.$langs->trans("LDAPRecordNotFound").' (dn='.$dn.' - search='.$search.')
    '; diff --git a/htdocs/user/logout.php b/htdocs/user/logout.php index 37ff691fdcc..8aac6037f65 100644 --- a/htdocs/user/logout.php +++ b/htdocs/user/logout.php @@ -35,7 +35,8 @@ require_once '../main.inc.php'; // This can happen only with a bookmark or forged url call. if (!empty($_SESSION["dol_authmode"]) && ($_SESSION["dol_authmode"] == 'forceuser' || $_SESSION["dol_authmode"] == 'http')) { - die("Disconnection does not work when connection was made in mode ".$_SESSION["dol_authmode"]); + unset($_SESSION["dol_login"]); + die("Applicative disconnection should be useless when connection was made in mode ".$_SESSION["dol_authmode"]); } global $conf, $langs, $user; @@ -50,13 +51,6 @@ if ($result < 0) { $error++; } // Define url to go after disconnect $urlfrom=empty($_SESSION["urlfrom"])?'':$_SESSION["urlfrom"]; -// Destroy some cookies -// TODO external module -if (! empty($conf->phenix->enabled) && ! empty($conf->phenix->cookie)) -{ - setcookie($conf->phenix->cookie, '', 1, "/"); -} - // Define url to go $url=DOL_URL_ROOT."/index.php"; // By default go to login page if ($urlfrom) $url=DOL_URL_ROOT.$urlfrom; diff --git a/htdocs/user/note.php b/htdocs/user/note.php index 1734e7286d4..55dd46e1129 100644 --- a/htdocs/user/note.php +++ b/htdocs/user/note.php @@ -50,7 +50,8 @@ if ($user->id == $id) $feature2=''; // A user can always read its own card $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('usercard','globalcard')); +$contextpage=array('usercard','usernote','globalcard'); +$hookmanager->initHooks($contextpage); /* @@ -65,7 +66,7 @@ if (empty($reshook)) { if ($action == 'update' && $user->rights->user->user->creer && !$_POST["cancel"]) { $db->begin(); - $res = $object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES)); + $res = $object->update_note(dol_html_entity_decode(GETPOST('note_private','none'), ENT_QUOTES)); if ($res < 0) { $mesg = '
    '.$adh->error.'
    '; $db->rollback(); @@ -96,11 +97,11 @@ if ($id) if ($user->rights->user->user->lire || $user->admin) { $linkback = ''.$langs->trans("BackToList").''; } - + dol_banner_tab($object,'id',$linkback,$user->rights->user->user->lire || $user->admin); - + print '
    '; - + print "
    "; print ''; diff --git a/htdocs/user/param_ihm.php b/htdocs/user/param_ihm.php index 8831b56f09a..81e8996aff2 100644 --- a/htdocs/user/param_ihm.php +++ b/htdocs/user/param_ihm.php @@ -79,7 +79,8 @@ $form = new Form($db); $formadmin=new FormAdmin($db); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('usercard','globalcard')); +$contextpage=array('usercard','userihm','globalcard'); +$hookmanager->initHooks($contextpage); /* @@ -188,9 +189,9 @@ if ($action == 'edit') if ($user->rights->user->user->lire || $user->admin) { $linkback = ''.$langs->trans("BackToList").''; } - + dol_banner_tab($object,'id',$linkback,$user->rights->user->user->lire || $user->admin); - + if (! empty($conf->use_javascript_ajax)) {/* print '';*/ - } + } if (! empty($conf->use_javascript_ajax)) { print ''; } - + clearstatcache(); $var=true; @@ -245,7 +246,7 @@ if ($action == 'edit') print ''.$langs->trans("Parameter").''.$langs->trans("DefaultValue").' '.$langs->trans("PersonalValue").''; // Landing page - + print ''.$langs->trans("LandingPage").''; print ''; print (empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE); @@ -257,9 +258,9 @@ if ($action == 'edit') print $form->selectarray('MAIN_LANDING_PAGE', $tmparray, (! empty($object->conf->MAIN_LANDING_PAGE)?$object->conf->MAIN_LANDING_PAGE:''), 0, 0, 0, '', 1); //print info_admin($langs->trans("WarningYouMayLooseAccess"), 0, 0, 0); print ''; - + // Langue par defaut - + print ''.$langs->trans("Language").''; print ''; $s=picto_from_langcode($conf->global->MAIN_LANG_DEFAULT); @@ -274,7 +275,7 @@ if ($action == 'edit') print ''; // Taille max des listes - + print ''.$langs->trans("MaxSizeList").''; print ''.$conf->global->MAIN_SIZE_LISTE_LIMIT.''; print 'conf->MAIN_SIZE_LISTE_LIMIT)?" checked":""); @@ -300,18 +301,18 @@ if ($action == 'edit') else { dol_fiche_head($head, 'guisetup', $title, -1, 'user'); - + $linkback = ''.$langs->trans("BackToList").''; - + dol_banner_tab($object,'id',$linkback,$user->rights->user->user->lire || $user->admin); - + $var=true; print ''; print ''; // Landing page - + print ''; print ''; - + // Language - + print ''; print ''; - + print ''; print ''; print ''; diff --git a/htdocs/user/passwordforgotten.php b/htdocs/user/passwordforgotten.php index 9c2aabd3654..43cb5097bba 100644 --- a/htdocs/user/passwordforgotten.php +++ b/htdocs/user/passwordforgotten.php @@ -48,19 +48,19 @@ $action=GETPOST('action', 'alpha'); $mode=$dolibarr_main_authentication; if (! $mode) $mode='http'; -$username = GETPOST('username'); -$passwordhash = GETPOST('passwordhash'); -$conf->entity = (GETPOST('entity') ? GETPOST('entity') : 1); +$username = GETPOST('username','alpha'); +$passwordhash = GETPOST('passwordhash','alpha'); +$conf->entity = (GETPOST('entity','int') ? GETPOST('entity','int') : 1); // Instantiate hooks of thirdparty module only if not already define $hookmanager->initHooks(array('passwordforgottenpage')); -if (GETPOST('dol_hide_leftmenu') || ! empty($_SESSION['dol_hide_leftmenu'])) $conf->dol_hide_leftmenu=1; -if (GETPOST('dol_hide_topmenu') || ! empty($_SESSION['dol_hide_topmenu'])) $conf->dol_hide_topmenu=1; -if (GETPOST('dol_optimize_smallscreen') || ! empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen=1; -if (GETPOST('dol_no_mouse_hover') || ! empty($_SESSION['dol_no_mouse_hover'])) $conf->dol_no_mouse_hover=1; -if (GETPOST('dol_use_jmobile') || ! empty($_SESSION['dol_use_jmobile'])) $conf->dol_use_jmobile=1; +if (GETPOST('dol_hide_leftmenu','alpha') || ! empty($_SESSION['dol_hide_leftmenu'])) $conf->dol_hide_leftmenu=1; +if (GETPOST('dol_hide_topmenu','alpha') || ! empty($_SESSION['dol_hide_topmenu'])) $conf->dol_hide_topmenu=1; +if (GETPOST('dol_optimize_smallscreen','alpha') || ! empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen=1; +if (GETPOST('dol_no_mouse_hover','alpha') || ! empty($_SESSION['dol_no_mouse_hover'])) $conf->dol_no_mouse_hover=1; +if (GETPOST('dol_use_jmobile','alpha') || ! empty($_SESSION['dol_use_jmobile'])) $conf->dol_use_jmobile=1; /** diff --git a/htdocs/user/perms.php b/htdocs/user/perms.php index 6f89e49af5e..e523d01009f 100644 --- a/htdocs/user/perms.php +++ b/htdocs/user/perms.php @@ -71,16 +71,10 @@ $object->fetch($id, '', '', 1); $object->getrights(); $entity=$conf->entity; -if (! empty($conf->multicompany->enabled)) -{ - if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - $entity=(GETPOST('entity','int') ? GETPOST('entity','int') : $conf->entity); - else - $entity=(! empty($object->entity) ? $object->entity : $conf->entity); -} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('usercard','globalcard')); +$contextpage=array('usercard','userperms','globalcard'); +$hookmanager->initHooks($contextpage); /** diff --git a/htdocs/variants/admin/admin.php b/htdocs/variants/admin/admin.php index eedacb086b3..f3752469538 100644 --- a/htdocs/variants/admin/admin.php +++ b/htdocs/variants/admin/admin.php @@ -37,6 +37,12 @@ if ($_POST) { setEventMessage($langs->trans('CoreErrorMessage'), 'errors'); } + if (dolibarr_set_const($db, 'PRODUIT_ATTRIBUTES_SEPARATOR', GETPOST('PRODUIT_ATTRIBUTES_SEPARATOR'), 'chaine', 0, '', $conf->entity)) { + setEventMessage($langs->trans('RecordSaved')); + } else { + setEventMessage($langs->trans('CoreErrorMessage'), 'errors'); + } + } $title = $langs->trans('ModuleSetup').' '.$langs->trans('ProductAttributes'); @@ -55,6 +61,13 @@ print ''."\n"; print ''."\n"; print ''; +print ''; print '
    '.$langs->trans("Parameter").''.$langs->trans("DefaultValue").' '.$langs->trans("PersonalValue").'
    '.$langs->trans("LandingPage").''; print (empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE); @@ -327,9 +328,9 @@ else else print $object->conf->MAIN_LANDING_PAGE; //print $form->selectarray('MAIN_LANDING_PAGE', $tmparray, (! empty($object->conf->MAIN_LANDING_PAGE)?$object->conf->MAIN_LANDING_PAGE:''), 0, 0, 0, '', 1); print '
    '.$langs->trans("Language").''; $s=picto_from_langcode($conf->global->MAIN_LANG_DEFAULT); @@ -343,7 +344,7 @@ else print (isset($object->conf->MAIN_LANG_DEFAULT) && $object->conf->MAIN_LANG_DEFAULT=='auto'?$langs->trans("AutoDetectLang"):(! empty($object->conf->MAIN_LANG_DEFAULT)?$langs->trans("Language_".$object->conf->MAIN_LANG_DEFAULT):'')); print '
    '.$langs->trans("MaxSizeList").''.(! empty($conf->global->MAIN_SIZE_LISTE_LIMIT)?$conf->global->MAIN_SIZE_LISTE_LIMIT:' ').'conf->MAIN_SIZE_LISTE_LIMIT)?" checked":"").'> '.$langs->trans("UsePersonalValue").''.$langs->trans("Value").' 
    '.$langs->trans('HideProductCombinations').''; print $form->selectyesno("PRODUIT_ATTRIBUTES_HIDECHILD",$conf->global->PRODUIT_ATTRIBUTES_HIDECHILD,1).'
    '.$langs->trans('CombinationsSeparator').''; +if(isset($conf->global->PRODUIT_ATTRIBUTES_SEPARATOR)) { + $separator = $conf->global->PRODUIT_ATTRIBUTES_SEPARATOR; +} else { + $separator = "_"; +} +print '
    '; print '
    '; print '
    '; diff --git a/htdocs/variants/class/ProductCombination.class.php b/htdocs/variants/class/ProductCombination.class.php index d3e6964aea6..04b987192e1 100644 --- a/htdocs/variants/class/ProductCombination.class.php +++ b/htdocs/variants/class/ProductCombination.class.php @@ -476,7 +476,7 @@ WHERE c.fk_product_parent = ".(int) $productid." AND p.tosell = 1"; */ public function createProductCombination(Product $product, array $combinations, array $variations, $price_var_percent = false, $forced_pricevar = false, $forced_weightvar = false) { - global $db, $user; + global $db, $user, $conf; require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php'; require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php'; @@ -542,7 +542,11 @@ WHERE c.fk_product_parent = ".(int) $productid." AND p.tosell = 1"; $price_impact += (float) price2num($variations[$currcombattr][$currcombval]['price']); } - $newproduct->ref .= '_'.$prodattrval->ref; + if (isset($conf->global->PRODUIT_ATTRIBUTES_SEPARATOR)) { + $newproduct->ref .= $conf->global->PRODUIT_ATTRIBUTES_SEPARATOR . $prodattrval->ref; + } else { + $newproduct->ref .= '_'.$prodattrval->ref; + } //The first one should not contain a linebreak if ($newproduct->description) { @@ -660,4 +664,4 @@ WHERE c.fk_product_parent = ".(int) $productid." AND p.tosell = 1"; return 1; } -} \ No newline at end of file +} diff --git a/htdocs/variants/combinations.php b/htdocs/variants/combinations.php index 0ec1bf07b68..f5feba2e606 100644 --- a/htdocs/variants/combinations.php +++ b/htdocs/variants/combinations.php @@ -41,7 +41,7 @@ $massaction=GETPOST('massaction','alpha'); $show_files=GETPOST('show_files','int'); $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); -$cancel = GETPOST('cancel'); +$cancel = GETPOST('cancel','alpha'); // Security check $fieldvalue = (! empty($id) ? $id : $ref); diff --git a/htdocs/webservices/server_invoice.php b/htdocs/webservices/server_invoice.php index 2150017577b..c93605ab2ea 100644 --- a/htdocs/webservices/server_invoice.php +++ b/htdocs/webservices/server_invoice.php @@ -555,7 +555,7 @@ function createInvoice($authentication,$invoice) if (empty($invoice['id']) && empty($invoice['ref']) && empty($invoice['ref_ext'])) { $error++; $errorcode='KO'; $errorlabel="Invoice id or ref or ref_ext is mandatory."; } - + if (! $error) { $new_invoice=new Facture($db); @@ -568,13 +568,13 @@ function createInvoice($authentication,$invoice) $new_invoice->statut= Facture::STATUS_DRAFT; // We start with status draft $new_invoice->fk_project=$invoice['project_id']; $new_invoice->date_creation=$now; - + //take mode_reglement and cond_reglement from thirdparty $soc = new Societe($db); $res=$soc->fetch($new_invoice->socid); if ($res > 0) { $new_invoice->mode_reglement_id = ! empty($invoice['payment_mode_id'])?$invoice['payment_mode_id']:$soc->mode_reglement_id; - $new_invoice->cond_reglement_id = $soc->cond_reglement_id; + $new_invoice->cond_reglement_id = $soc->cond_reglement_id; } else $new_invoice->mode_reglement_id = $invoice['payment_mode_id']; @@ -677,12 +677,12 @@ function createInvoiceFromOrder($authentication,$id_order='', $ref_order='', $re if (empty($id_order) && empty($ref_order) && empty($ref_ext_order)) { $error++; $errorcode='KO'; $errorlabel="order id or ref or ref_ext is mandatory."; } - + ////////////////////// if (! $error) { $fuser->getrights(); - + if ($fuser->rights->commande->lire) { $order=new Commande($db); @@ -695,19 +695,19 @@ function createInvoiceFromOrder($authentication,$id_order='', $ref_order='', $re $error++; $errorcode='PERMISSION_DENIED'; $errorlabel=$order->socid.'User does not have permission for this request'; } - + if(!$error) { - + $newobject=new Facture($db); - $result = $newobject->createFromOrder($order); - + $result = $newobject->createFromOrder($order, $fuser); + if ($result < 0) { $error++; dol_syslog("Webservice server_invoice:: invoice creation from order failed", LOG_ERR); } - + } } else @@ -722,7 +722,7 @@ function createInvoiceFromOrder($authentication,$id_order='', $ref_order='', $re $errorcode='PERMISSION_DENIED'; $errorlabel='User does not have permission for this request'; } } - + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); @@ -731,7 +731,7 @@ function createInvoiceFromOrder($authentication,$id_order='', $ref_order='', $re { $objectresp= array('result'=>array('result_code'=>'OK', 'result_label'=>''),'id'=>$newobject->id,'ref'=>$newobject->ref,'ref_ext'=>$newobject->ref_ext); } - + return $objectresp; } @@ -761,20 +761,20 @@ function updateInvoice($authentication,$invoice) if (empty($invoice['id']) && empty($invoice['ref']) && empty($invoice['ref_ext'])) { $error++; $errorcode='KO'; $errorlabel="Invoice id or ref or ref_ext is mandatory."; } - + if (! $error) { $objectfound=false; - + $object=new Facture($db); $result=$object->fetch($invoice['id'],$invoice['ref'],$invoice['ref_ext'], ''); - + if (!empty($object->id)) { - + $objectfound=true; - + $db->begin(); - + if (isset($invoice['status'])) { if ($invoice['status'] == Facture::STATUS_DRAFT) @@ -784,7 +784,7 @@ function updateInvoice($authentication,$invoice) if ($invoice['status'] == Facture::STATUS_VALIDATED) { $result = $object->validate($fuser); - + if ($result >= 0) { // Define output language @@ -794,13 +794,13 @@ function updateInvoice($authentication,$invoice) } if ($invoice['status'] == Facture::STATUS_CLOSED) { - $result = $object->set_paid($fuser,$invoice->close_code,$invoice->close_note); + $result = $object->set_paid($fuser,$invoice->close_code,$invoice->close_note); } if ($invoice['status'] == Facture::STATUS_ABANDONED) $result = $object->set_canceled($fuser,$invoice->close_code,$invoice->close_note); } } - + if ((! $error) && ($objectfound)) { $db->commit(); @@ -823,12 +823,12 @@ function updateInvoice($authentication,$invoice) $errorlabel='Invoice id='.$invoice['id'].' ref='.$invoice['ref'].' ref_ext='.$invoice['ref_ext'].' cannot be found'; } } - + if ($error) { $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); } - + return $objectresp; } diff --git a/htdocs/websites/class/website.class.php b/htdocs/website/class/website.class.php similarity index 59% rename from htdocs/websites/class/website.class.php rename to htdocs/website/class/website.class.php index 1d67eb4ebb0..70162c4c863 100644 --- a/htdocs/websites/class/website.class.php +++ b/htdocs/website/class/website.class.php @@ -20,10 +20,9 @@ */ /** - * \file websites/website.class.php - * \ingroup websites - * \brief This file is an example for a CRUD class file (Create/Read/Update/Delete) - * Put some comments here + * \file website/website.class.php + * \ingroup website + * \brief File for the CRUD class of website (Create/Read/Update/Delete) */ // Put here all includes required by your class file @@ -33,9 +32,6 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; /** * Class Website - * - * Put here description of your class - * @see CommonObject */ class Website extends CommonObject { @@ -47,6 +43,14 @@ class Website extends CommonObject * @var string Name of table without prefix where object is stored */ public $table_element = 'website'; + /** + * @var array Does websiteaccount support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 1; + /** + * @var string String with name of icon for website. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'globe'; /** * @var int @@ -106,6 +110,7 @@ class Website extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $error = 0; + $now=dol_now(); // Clean parameters if (isset($this->entity)) { @@ -120,7 +125,8 @@ class Website extends CommonObject if (isset($this->status)) { $this->status = trim($this->status); } - if (empty($this->date_creation)) $this->date_creation = dol_now(); + if (empty($this->date_creation)) $this->date_creation = $now; + if (empty($this->date_modification)) $this->date_modification = $now; // Check parameters // Put here code to add control on parameters values @@ -134,16 +140,18 @@ class Website extends CommonObject $sql.= 'fk_default_home,'; $sql.= 'virtualhost,'; $sql.= 'fk_user_create,'; - $sql.= 'date_creation'; + $sql.= 'date_creation,'; + $sql.= 'tms'; $sql .= ') VALUES ('; - $sql .= ' '.(! isset($this->entity)?'NULL':$this->entity).','; + $sql .= ' '.((empty($this->entity) && $this->entity != '0')?'NULL':$this->entity).','; $sql .= ' '.(! isset($this->ref)?'NULL':"'".$this->db->escape($this->ref)."'").','; $sql .= ' '.(! isset($this->description)?'NULL':"'".$this->db->escape($this->description)."'").','; $sql .= ' '.(! isset($this->status)?'NULL':$this->status).','; $sql .= ' '.(! isset($this->fk_default_home)?'NULL':$this->fk_default_home).','; - $sql .= ' '.(! isset($this->virtualhost)?'NULL':$this->virtualhost).','; + $sql .= ' '.(! isset($this->virtualhost)?'NULL':"'".$this->db->escape($this->virtualhost)."'").","; $sql .= ' '.(! isset($this->fk_user_create)?$user->id:$this->fk_user_create).','; - $sql .= ' '.(! isset($this->date_creation) || dol_strlen($this->date_creation)==0?'NULL':"'".$this->db->idate($this->date_creation)."'"); + $sql .= ' '.(! isset($this->date_creation) || dol_strlen($this->date_creation)==0?'NULL':"'".$this->db->idate($this->date_creation)."'").","; + $sql .= ' '.(! isset($this->date_modification) || dol_strlen($this->date_modification)==0?'NULL':"'".$this->db->idate($this->date_creation)."'"); $sql .= ')'; $this->db->begin(); @@ -184,10 +192,9 @@ class Website extends CommonObject /** * Load object in memory from the database * - * @param int $id Id object - * @param string $ref Ref - * - * @return int <0 if KO, 0 if not found, >0 if OK + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK */ public function fetch($id, $ref = null) { @@ -204,7 +211,7 @@ class Website extends CommonObject $sql .= " t.fk_user_create,"; $sql .= " t.fk_user_modif,"; $sql .= " t.date_creation,"; - $sql .= " t.tms"; + $sql .= " t.tms as date_modification"; $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; if (null !== $ref) { $sql .= " WHERE t.ref = '" . $this->db->escape($ref) . "'"; @@ -229,11 +236,16 @@ class Website extends CommonObject $this->fk_user_create = $obj->fk_user_create; $this->fk_user_modif = $obj->fk_user_modif; $this->date_creation = $this->db->jdate($obj->date_creation); - $this->tms = $this->db->jdate($obj->tms); + $this->date_modification = $this->db->jdate($obj->date_modification); } $this->db->free($resql); - if ($numrows) { + if ($numrows > 0) { + // Lines + $this->fetchLines(); + } + + if ($numrows > 0) { return 1; } else { return 0; @@ -246,6 +258,21 @@ class Website extends CommonObject } } + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetchLines() + { + $this->lines=array(); + + // Load lines with object MyObjectLine + + return count($this->lines)?1:0; + } + + /** * Load object in memory from the database * @@ -273,7 +300,7 @@ class Website extends CommonObject $sql .= " t.fk_user_create,"; $sql .= " t.fk_user_modif,"; $sql .= " t.date_creation,"; - $sql .= " t.tms"; + $sql .= " t.tms as date_modification"; $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t'; // Manage filter @@ -313,7 +340,7 @@ class Website extends CommonObject $this->fk_user_create = $obj->fk_user_create; $this->fk_user_modif = $obj->fk_user_modif; $line->date_creation = $this->db->jdate($obj->date_creation); - $line->tms = $this->db->jdate($obj->tms); + $line->date_modification = $this->db->jdate($obj->date_modification); $this->records[$line->id] = $line; } @@ -369,8 +396,8 @@ class Website extends CommonObject $sql .= ' fk_default_home = '.(($this->fk_default_home > 0)?$this->fk_default_home:"null").','; $sql .= ' virtualhost = '.(($this->virtualhost != '')?"'".$this->db->escape($this->virtualhost)."'":"null").','; $sql .= ' fk_user_modif = '.(! isset($this->fk_user_modif) ? $user->id : $this->fk_user_modif).','; - $sql .= ' date_creation = '.(! isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').','; - $sql .= ' tms = '.(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : "'".$this->db->idate(dol_now())."'"); + $sql .= ' date_creation = '.(! isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null'); + $sql .= ', tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'"); $sql .= ' WHERE rowid=' . $this->id; $this->db->begin(); @@ -457,45 +484,150 @@ class Website extends CommonObject } /** - * Load an object from its id and create a new one in database + * Load an object from its id and create a new one in database. + * This copy website directories, regenerate all the pages + alias pages and recreate the medias link. * - * @param int $fromid Id of object to clone - * - * @return int New id of clone + * @param User $user User making the clone + * @param int $fromid Id of object to clone + * @param string $newref New ref + * @return mixed New object created, <0 if KO */ - public function createFromClone($fromid) + public function createFromClone($user, $fromid, $newref) { - dol_syslog(__METHOD__, LOG_DEBUG); + global $hookmanager, $langs; + global $dolibarr_main_data_root; - global $user; - $error = 0; - $object = new Website($this->db); + $error=0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + // Check no site with ref exists + if ($object->fetch(0, $newref) > 0) + { + $this->error='NewRefIsAlreadyUsed'; + return -1; + } $this->db->begin(); // Load source object $object->fetch($fromid); - // Reset object - $object->id = 0; + + $oldidforhome=$object->fk_default_home; + + $pathofwebsiteold=$dolibarr_main_data_root.'/website/'.$object->ref; + $pathofwebsitenew=$dolibarr_main_data_root.'/website/'.$newref; + dol_delete_dir_recursive($pathofwebsitenew); + + $fileindex=$pathofwebsitenew.'/index.php'; + + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); // Clear fields - // ... + $object->ref=$newref; + $object->fk_default_home=0; + $object->virtualhost=''; // Create clone + $object->context['createfromclone'] = 'createfromclone'; $result = $object->create($user); - - // Other options if ($result < 0) { $error ++; $this->errors = $object->errors; dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); } + if (! $error) + { + dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0); + + // Check symlink to medias and restore it if ko + $pathtomedias=DOL_DATA_ROOT.'/medias'; + $pathtomediasinwebsite=$pathofwebsitenew.'/medias'; + if (! is_link(dol_osencode($pathtomediasinwebsite))) + { + dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); + dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists + $result = symlink($pathtomedias, $pathtomediasinwebsite); + } + + $newidforhome=0; + + // Duplicate pages + $objectpages = new WebsitePage($this->db); + $listofpages = $objectpages->fetchAll($fromid); + foreach($listofpages as $pageid => $objectpageold) + { + // Delete old file + $filetplold=$pathofwebsitenew.'/page'.$pageid.'.tpl.php'; + dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); + dol_delete_file($filetplold); + + // Create new file + $objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id); + //print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'
    '; + if (is_object($objectpagenew) && $objectpagenew->pageurl) + { + $filealias=$pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php'; + $filetplnew=$pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php'; + + // Save page alias + $result=dolSavePageAlias($filealias, $object, $objectpagenew); + if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + + $result=dolSavePageContent($filetplnew, $object, $objectpagenew); + if (! $result) setEventMessages('Failed to write file '.$filetplnew, null, 'errors'); + + if ($pageid == $oldidforhome) + { + $newidforhome = $objectpagenew->id; + } + } + else + { + setEventMessages($objectpageold->error, $objectpageold->errors, 'errors'); + $error++; + } + } + } + + if (! $error) + { + // Restore id of home page + $object->fk_default_home = $newidforhome; + $res = $object->update($user); + if (! $res > 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } + + if (! $error) + { + dol_delete_file($fileindex); + + $filetpl=$pathofwebsitenew.'/page'.$newidforhome.'.tpl.php'; + + $indexcontent = ''."\n"; + $result = file_put_contents($fileindex, $indexcontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($fileindex, octdec($conf->global->MAIN_UMASK)); + } + } + // End if (!$error) { $this->db->commit(); - return $object->id; + return $object; } else { $this->db->rollback(); @@ -524,21 +656,23 @@ class Website extends CommonObject $result = ''; $companylink = ''; - $label = '' . $langs->trans("MyModule") . ''; + $label = '' . $langs->trans("WebSite") . ''; $label.= '
    '; - $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; + $label.= '' . $langs->trans('Nom') . ': ' . $this->ref; - $link = 'picto?$this->picto:'generic'), ($notooltip?'':'class="classfortooltip"')).$linkend); if ($withpicto != 2) $result.=' '; } - $result.= $link . $this->ref . $linkend; + $result.= $linkstart . $this->ref . $linkend; return $result; } @@ -624,5 +758,131 @@ class Website extends CommonObject } + + /** + * Generate a zip with all data of web site. + * + * @return string Path to file with zip + */ + function exportWebSite() + { + global $conf; + + $website = $this; + + dol_mkdir($conf->website->dir_temp); + $srcdir = $conf->website->dir_output.'/'.$website->ref; + $destdir = $conf->website->dir_temp.'/'.$website->ref; + + $arrayreplacement=array(); + + dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement); + + $srcdir = DOL_DATA_ROOT.'/medias/images/'.$website->ref; + $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/images/'.$website->ref; + + dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement); + + // Build sql file + dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/export'); + + $filesql = $conf->website->dir_temp.'/'.$website->ref.'/export/pages.sql'; + $fp = fopen($filesql,"w"); + + $objectpages = new WebsitePage($this->db); + $listofpages = $objectpages->fetchAll($website->id); + + // Assign ->newid and ->newfk_page + $i=1; + foreach($listofpages as $pageid => $objectpageold) + { + $objectpageold->newid=$i; + $i++; + } + $i=1; + foreach($listofpages as $pageid => $objectpageold) + { + // Search newid + $newfk_page=0; + foreach($listofpages as $pageid2 => $objectpageold2) + { + if ($pageid2 == $objectpageold->fk_page) + { + $newfk_page = $objectpageold2->newid; + break; + } + } + $objectpageold->newfk_page=$newfk_page; + $i++; + } + foreach($listofpages as $pageid => $objectpageold) + { + $line = 'INSERT INTO llx_website_page(rowid, fk_page, fk_website, pageurl, title, description, keyword, status, date_creation, tms, lang, import_key, grabbed_from, content)'; + $line.= " VALUES("; + $line.= $objectpageold->newid."+__MAXROWID__, "; + $line.= ($objectpageold->newfk_page ? $this->db->escape($objectpageold->newfk_page)."+__MAXROWID__" : "null").", "; + $line.= "__WEBSITE_ID__, "; + $line.= "'".$this->db->escape($objectpageold->pageurl)."', "; + $line.= "'".$this->db->escape($objectpageold->title)."', "; + $line.= "'".$this->db->escape($objectpageold->description)."', "; + $line.= "'".$this->db->escape($objectpageold->keyword)."', "; + $line.= "'".$this->db->escape($objectpageold->status)."', "; + $line.= "'".$this->db->idate($objectpageold->date_creation)."', "; + $line.= "'".$this->db->idate($objectpageold->date_modification)."', "; + $line.= "'".$this->db->escape($objectpageold->lang)."', "; + $line.= ($objectpageold->import_key ? "'".$this->db->escape($objectpageold->import_key)."'" : "null").", "; + $line.= "'".$this->db->escape($objectpageold->grabbed_from)."', "; + $line.= "'".$this->db->escape($objectpageold->content)."'"; + $line.= ");"; + $line.= "\n"; + fputs($fp, $line); + } + + fclose($fp); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filesql, octdec($conf->global->MAIN_UMASK)); + + // Build zip file + $filedir = $conf->website->dir_temp.'/'.$website->ref; + $fileglob = $conf->website->dir_temp.'/'.$website->ref.'/export/website_'.$website->ref.'-*.zip'; + $filename = $conf->website->dir_temp.'/'.$website->ref.'/export/website_'.$website->ref.'-'.dol_print_date(dol_now(),'dayhourlog').'.zip'; + + dol_delete_file($fileglob, 0); + dol_compress_file($filedir, $filename, 'zip'); + + return $filename; + } + + + /** + * Open a zip with all data of web site and load it into database. + * + * @param string $pathtofile Path of zip file + * @return int <0 if KO, Id of new website if OK + */ + function importWebSite($pathtofile) + { + global $conf; + + $result = 0; + + $object = new Website($this->db); + + $filename = basename($pathtofile); + if (! preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) + { + $this->errors[]='Bad format for filename '.$filename.'. Must be website_XXX-VERSION.'; + return -1; + } + + $websitecode = $reg[1]; + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."website(ref, entity, description, status) values('".$websitecode."', ".$conf->entity.", 'Portal to sell your SaaS. Do not remove this entry.', 1)"; + $resql = $this->db->query($sql); + + + return $result; + } + } diff --git a/htdocs/website/class/websiteaccount.class.php b/htdocs/website/class/websiteaccount.class.php new file mode 100644 index 00000000000..275b2491e49 --- /dev/null +++ b/htdocs/website/class/websiteaccount.class.php @@ -0,0 +1,501 @@ + + * Copyright (C) 2014-2016 Juanjo Menent + * Copyright (C) 2015 Florian Henry + * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file class/websiteaccount.class.php + * \ingroup website + * \brief This file is a CRUD class file for WebsiteAccount (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for WebsiteAccount + */ +class WebsiteAccount extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'websiteaccount'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'website_account'; + /** + * @var array Does websiteaccount support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 0; + /** + * @var string String with name of icon for websiteaccount. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'globe'; + + + /** + * 'type' if the field format. + * 'label' the translation key. + * 'enabled' is a condition when the field must be managed. + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only. Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'position' is the sort order of field. + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'help' is a string visible as a tooltip on field + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'default' is a default value for creation (can still be replaced by the global setup of default values) + * 'showoncombobox' if field must be shown into the label of combobox + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',), + 'login' => array('type'=>'varchar(64)', 'label'=>'Login', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>'Login',), + 'pass_encoding' => array('type'=>'varchar(24)', 'label'=>'PassEncoding', 'visible'=>-2, 'enabled'=>1, 'position'=>30), + 'pass_crypted' => array('type'=>'varchar(128)', 'label'=>'Password', 'visible'=>1, 'enabled'=>1, 'position'=>31, 'notnull'=>1), + 'pass_temp' => array('type'=>'varchar(128)', 'label'=>'Temp', 'visible'=>0, 'enabled'=>0, 'position'=>32, 'notnull'=>-1,), + 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1, 'index'=>1), + 'fk_website' => array('type'=>'integer:Website:website/class/website.class.php', 'label'=>'WebSite', 'visible'=>1, 'enabled'=>1, 'position'=>41, 'notnull'=>1, 'index'=>1), + 'date_last_login' => array('type'=>'datetime', 'label'=>'LastConnexion', 'visible'=>2, 'enabled'=>1, 'position'=>50, 'notnull'=>0,), + 'date_previous_login' => array('type'=>'datetime', 'label'=>'PreviousConnexion', 'visible'=>2, 'enabled'=>1, 'position'=>51, 'notnull'=>0,), + //'note_public' => array('type'=>'text', 'label'=>'NotePublic', 'visible'=>-1, 'enabled'=>1, 'position'=>45, 'notnull'=>-1,), + 'note_private' => array('type'=>'text', 'label'=>'NotePrivate', 'visible'=>-1, 'enabled'=>1, 'position'=>46, 'notnull'=>-1,), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + 'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + 'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>-1,), + 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'visible'=>-2, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,), + 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'index'=>1, 'default'=>1, 'arrayofkeyval'=>array('1'=>'Active','0'=>'Disabled')), + ); + public $rowid; + public $login; + public $pass_encoding; + public $pass_crypted; + public $date_last_login; + public $date_previous_login; + public $note_private; + public $date_creation; + public $tms; + public $fk_user_creat; + public $fk_user_modif; + public $import_key; + public $status; + public $fk_soc; + // END MODULEBUILDER PROPERTIES + + + + + // If this object has a subtable with lines + + /** + * @var int Name of subtable line + */ + //public $table_element_line = 'website_accountdet'; + /** + * @var int Field with ID of parent key if this field has a parent + */ + //public $fk_element = 'fk_website_account'; + /** + * @var int Name of subtable class that manage subtable lines + */ + //public $class_element_line = 'WebsiteAccountline'; + /** + * @var array Array of child tables (child tables to delete before deleting a record) + */ + //protected $childtables=array('website_accountdet'); + /** + * @var WebsiteAccountLine[] Array of subtable lines + */ + //public $lines = array(); + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + /** + * Clone and object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $hookmanager, $langs; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $object->fetchCommon($fromid); + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + // Clear fields + $object->ref = "copy_of_".$object->ref; + $object->title = $langs->trans("CopyOf")." ".$object->title; + // ... + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetchLines() + { + $this->lines=array(); + + // Load lines with object WebsiteAccountLine + + return count($this->lines)?1:0; + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + } + + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + function getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1) + { + global $db, $conf, $langs; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + + $result = ''; + $companylink = ''; + + $this->ref = $this->login; + + $label = '' . $langs->trans("WebsiteAccount") . ''; + $label.= '
    '; + $label.= '' . $langs->trans('Login') . ': ' . $this->ref; + //$label.= '' . $langs->trans('WebSite') . ': ' . $this->ref; + + $url = dol_buildpath('/website/websiteaccount_card.php',1).'?id='.$this->id; + + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + + $linkclose=''; + if (empty($notooltip)) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowWebsiteAccount"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + } + else $linkclose = ($morecss?' class="'.$morecss.'"':''); + + $linkstart = '
    '; + $linkend=''; + + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; + + return $result; + } + + /** + * Return link to download file from a direct external access + * + * @param int $withpicto Add download picto into link + * @return string HTML link to file + */ + function getDirectExternalLink($withpicto=0) + { + return 'todo'; + } + + /** + * 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, 6=Long label + Picto + * @return string Label of status + */ + static function LibStatut($status,$mode=0) + { + global $langs; + + if ($mode == 0) + { + $prefix=''; + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 1) + { + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 2) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 3) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 4) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 5) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 6) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } + } + + /** + * Charge les informations d'ordre info dans l'objet commande + * + * @param int $id Id of order + * @return void + */ + function info($id) + { + $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; + $sql.= ' fk_user_creat, fk_user_modif'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql.= ' WHERE t.rowid = '.$id; + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if ($obj->fk_user_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + + } + else + { + dol_print_error($this->db); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } + + + /** + * Action executed by scheduler + * CAN BE A CRON TASK + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function doScheduledJob() + { + global $conf, $langs; + + $this->output = ''; + $this->error=''; + + dol_syslog(__METHOD__, LOG_DEBUG); + + // ... + + return 0; + } +} + +/** + * Class WebsiteAccountLine. You can also remove this and generate a CRUD class for lines objects. + */ +/* +class WebsiteAccountLine +{ + // @var int ID + public $id; + // @var mixed Sample line property 1 + public $prop1; + // @var mixed Sample line property 2 + public $prop2; +} +*/ \ No newline at end of file diff --git a/htdocs/websites/class/websitepage.class.php b/htdocs/website/class/websitepage.class.php similarity index 57% rename from htdocs/websites/class/websitepage.class.php rename to htdocs/website/class/websitepage.class.php index 4f9dc58c615..15ffc7bed69 100644 --- a/htdocs/websites/class/websitepage.class.php +++ b/htdocs/website/class/websitepage.class.php @@ -20,10 +20,9 @@ */ /** - * \file websites/websitepage.class.php - * \ingroup websites - * \brief This file is an example for a CRUD class file (Create/Read/Update/Delete) - * Put some comments here + * \file website/websitepage.class.php + * \ingroup website + * \brief File for the CRUD class of websitepage (Create/Read/Update/Delete) */ // Put here all includes required by your class file @@ -44,6 +43,10 @@ class WebsitePage extends CommonObject * @var string Name of table without prefix where object is stored */ public $table_element = 'website_page'; + /** + * @var string String with name of icon for websitepage. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'label'; /** */ @@ -53,13 +56,38 @@ class WebsitePage extends CommonObject public $title; public $description; public $keywords; + public $htmlheader; public $content; public $status; public $date_creation; public $date_modification; + // BEGIN MODULEBUILDER PROPERTIES /** - */ + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), + 'pageurl' =>array('type'=>'varchar(16)', 'label'=>'WEBSITE_PAGENAME', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Alias of page'), + 'title' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1), + 'description' =>array('type'=>'varchar(255)', 'label'=>'Description', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1), + 'keywords' =>array('type'=>'varchar(255)', 'label'=>'Keywords', 'enabled'=>1, 'visible'=>1, 'position'=>45, 'searchall'=>0), + 'lang' =>array('type'=>'varchar(6)', 'label'=>'Lang', 'enabled'=>1, 'visible'=>1, 'position'=>45, 'searchall'=>0), + //'status' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'index'=>true, 'position'=>1000), + 'fk_website' =>array('type'=>'integer', 'label'=>'WebsiteId', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>40, 'searchall'=>0, 'foreignkey'=>'websitepage.rowid'), + 'fk_page' =>array('type'=>'integer', 'label'=>'ParentPageId', 'enabled'=>1, 'visible'=>1, 'notnull'=>-1, 'position'=>45, 'searchall'=>0, 'foreignkey'=>'website.rowid'), + 'htmlheader' =>array('type'=>'text', 'label'=>'HtmlHeader', 'enabled'=>1, 'visible'=>0, 'position'=>50, 'searchall'=>0), + 'content' =>array('type'=>'mediumtext', 'label'=>'Content', 'enabled'=>1, 'visible'=>0, 'position'=>51, 'searchall'=>0), + 'grabbed_from' =>array('type'=>'varchar(255)', 'label'=>'GrabbedFrom', 'enabled'=>1, 'visible'=>1, 'index'=>1, 'position'=>400, 'comment'=>'URL page content was grabbed from'), + 'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>501), + //'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>502), + //'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'notnull'=>true, 'position'=>510), + //'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-1, 'position'=>511), + //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'index'=>1, 'position'=>1000, 'notnull'=>-1), + ); + // END MODULEBUILDER PROPERTIES /** @@ -77,113 +105,19 @@ class WebsitePage extends CommonObject * * @param User $user User that creates * @param bool $notrigger false=launch triggers after, true=disable triggers - * - * @return int <0 if KO, Id of created object if OK + * @return int <0 if KO, Id of created object if OK */ public function create(User $user, $notrigger = false) { - dol_syslog(__METHOD__, LOG_DEBUG); - - $error = 0; - $now=dol_now(); - - // Clean parameters - if (isset($this->fk_website)) { - $this->fk_website = trim($this->fk_website); - } - if (isset($this->pageurl)) { - $this->pageurl = trim($this->pageurl); - } - if (isset($this->title)) { - $this->title = trim($this->title); - } - if (isset($this->description)) { - $this->description = trim($this->description); - } - if (isset($this->keywords)) { - $this->keywords = trim($this->keywords); - } - if (isset($this->content)) { - $this->content = trim($this->content); - } - if (isset($this->status)) { - $this->status = trim($this->status); - } - if (isset($this->date_creation)) { - $this->date_creation = $now; - } - if (isset($this->date_modification)) { - $this->date_modification = $now; - } - - // Check parameters - // Put here code to add control on parameters values - - // Insert request - $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '('; - $sql.= 'fk_website,'; - $sql.= 'pageurl,'; - $sql.= 'title,'; - $sql.= 'description,'; - $sql.= 'keywords,'; - $sql.= 'content,'; - $sql.= 'status,'; - $sql.= 'date_creation,'; - $sql.= 'tms'; - $sql .= ') VALUES ('; - $sql .= ' '.(! isset($this->fk_website)?'NULL':$this->fk_website).','; - $sql .= ' '.(! isset($this->pageurl)?'NULL':"'".$this->db->escape($this->pageurl)."'").','; - $sql .= ' '.(! isset($this->title)?'NULL':"'".$this->db->escape($this->title)."'").','; - $sql .= ' '.(! isset($this->description)?'NULL':"'".$this->db->escape($this->description)."'").','; - $sql .= ' '.(! isset($this->keywords)?'NULL':"'".$this->db->escape($this->keywords)."'").','; - $sql .= ' '.(! isset($this->content)?'NULL':"'".$this->db->escape($this->content)."'").','; - $sql .= ' '.(! isset($this->status)?'NULL':$this->status).','; - $sql .= ' '.(! isset($this->date_creation) || dol_strlen($this->date_creation)==0?'NULL':"'".$this->db->idate($this->date_creation)."'").','; - $sql .= ' '.(! isset($this->date_modification) || dol_strlen($this->date_modification)==0?'NULL':"'".$this->db->idate($this->date_modification)."'"); - $sql .= ')'; - - $this->db->begin(); - - $resql = $this->db->query($sql); - if (! $resql) { - $error++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); - } - - if (! $error) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); - - if (!$notrigger) { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action to call a trigger. - - //// Call triggers - //$result=$this->call_trigger('MYOBJECT_CREATE',$user); - //if ($result < 0) $error++; - //// End call triggers - } - } - - // Commit or rollback - if ($error) - { - $this->db->rollback(); - - return - 1 * $error; - } else { - $this->db->commit(); - - return $this->id; - } + return $this->createCommon($user, $notrigger); } /** * Load object in memory from the database * - * @param int $id Id object. If this is 0, the default page of website_id will be used, if not defined, the first one. found - * @param string $website_id Web site id - * @param string $page Page name + * @param int $id Id object. If this is 0, the default page of website_id will be used, if not defined, the first one found. + * @param string $website_id Web site id (page name must also be filled if this parameter is used) + * @param string $page Page name (website id must also be filled if this parameter is used) * * @return int <0 if KO, 0 if not found, >0 if OK */ @@ -198,19 +132,28 @@ class WebsitePage extends CommonObject $sql .= " t.title,"; $sql .= " t.description,"; $sql .= " t.keywords,"; + $sql .= " t.htmlheader,"; $sql .= " t.content,"; + $sql .= " t.lang,"; + $sql .= " t.fk_page,"; $sql .= " t.status,"; + $sql .= " t.grabbed_from,"; $sql .= " t.date_creation,"; $sql .= " t.tms as date_modification"; $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; //$sql .= ' WHERE entity IN ('.getEntity('website').')'; // entity is on website level $sql .= ' WHERE 1 = 1'; - if (null !== $website_id) { - $sql .= " AND t.fk_website = '" . $this->db->escape($website_id) . "'"; - if ($page) $sql .= " AND t.pageurl = '" . $this->db->escape($page) . "'"; - } else { + if ($id > 0) + { $sql .= ' AND t.rowid = ' . $id; } + else + { + if (null !== $website_id) { + $sql .= " AND t.fk_website = '" . $this->db->escape($website_id) . "'"; + if ($page) $sql .= " AND t.pageurl = '" . $this->db->escape($page) . "'"; + } + } $sql .= $this->db->plimit(1); $resql = $this->db->query($sql); @@ -226,8 +169,12 @@ class WebsitePage extends CommonObject $this->title = $obj->title; $this->description = $obj->description; $this->keywords = $obj->keywords; + $this->htmlheader = $obj->htmlheader; $this->content = $obj->content; + $this->lang = $obj->lang; + $this->fk_page = $obj->fk_page; $this->status = $obj->status; + $this->grabbed_from = $obj->grabbed_from; $this->date_creation = $this->db->jdate($obj->date_creation); $this->date_modification = $this->db->jdate($obj->date_modification); } @@ -271,8 +218,12 @@ class WebsitePage extends CommonObject $sql .= " t.title,"; $sql .= " t.description,"; $sql .= " t.keywords,"; + $sql .= " t.htmlheader,"; $sql .= " t.content,"; + $sql .= " t.lang,"; + $sql .= " t.fk_page,"; $sql .= " t.status,"; + $sql .= " t.grabbed_from,"; $sql .= " t.date_creation,"; $sql .= " t.tms as date_modification"; $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t'; @@ -313,8 +264,12 @@ class WebsitePage extends CommonObject $record->title = $obj->title; $record->description = $obj->description; $record->keywords = $obj->keywords; + $record->htmlheader = $obj->htmlheader; $record->content = $obj->content; + $record->lang = $obj->lang; + $record->fk_page = $obj->fk_page; $record->status = $obj->status; + $record->grabbed_from = $obj->grabbed_from; $record->date_creation = $this->db->jdate($obj->date_creation); $record->date_modification = $this->db->jdate($obj->date_modification); //var_dump($record->id); @@ -336,158 +291,64 @@ class WebsitePage extends CommonObject * * @param User $user User that modifies * @param bool $notrigger false=launch triggers after, true=disable triggers - * - * @return int <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK */ public function update(User $user, $notrigger = false) { - $error = 0; - - dol_syslog(__METHOD__, LOG_DEBUG); - - // Clean parameters - - if (isset($this->fk_website)) { - $this->fk_website = trim($this->fk_website); - } - if (isset($this->pageurl)) { - $this->pageurl = trim($this->pageurl); - } - if (isset($this->title)) { - $this->title = trim($this->title); - } - if (isset($this->description)) { - $this->description = trim($this->description); - } - if (isset($this->keywords)) { - $this->keywords = trim($this->keywords); - } - if (isset($this->content)) { - $this->content = trim($this->content); - } - if (isset($this->status)) { - $this->status = trim($this->status); - } - - // Check parameters - // Put here code to add a control on parameters values - - // Update request - $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET'; - $sql .= ' fk_website = '.(isset($this->fk_website)?$this->fk_website:"null").','; - $sql .= ' pageurl = '.(isset($this->pageurl)?"'".$this->db->escape($this->pageurl)."'":"null").','; - $sql .= ' title = '.(isset($this->title)?"'".$this->db->escape($this->title)."'":"null").','; - $sql .= ' description = '.(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").','; - $sql .= ' keywords = '.(isset($this->keywords)?"'".$this->db->escape($this->keywords)."'":"null").','; - $sql .= ' content = '.(isset($this->content)?"'".$this->db->escape($this->content)."'":"null").','; - $sql .= ' status = '.(isset($this->status)?$this->status:"null").','; - $sql .= ' date_creation = '.(! isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').','; - $sql .= ' tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'"); - $sql .= ' WHERE rowid=' . $this->id; - - $this->db->begin(); - - $resql = $this->db->query($sql); - if (!$resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); - } - - if ($this->old_object->pageurl != $this->pageurl) - { - dol_syslog("The alias was changed, we must rename/recreate the page file into document"); - - } - - if (!$error && !$notrigger) { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action calls a trigger. - - //// Call triggers - //$result=$this->call_trigger('MYOBJECT_MODIFY',$user); - //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} - //// End call triggers - } - - // Commit or rollback - if ($error) { - $this->db->rollback(); - - return - 1 * $error; - } else { - $this->db->commit(); - - return 1; - } + return $this->updateCommon($user, $notrigger); } /** * Delete object in database * - * @param User $user User that deletes - * @param bool $notrigger false=launch triggers after, true=disable triggers - * - * @return int <0 if KO, >0 if OK + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK */ public function delete(User $user, $notrigger = false) { - dol_syslog(__METHOD__, LOG_DEBUG); + $result = $this->deleteCommon($user, $trigger); - $error = 0; + if ($result > 0) + { + $websiteobj=new Website($this->db); + $result = $websiteobj->fetch($this->fk_website); - $this->db->begin(); + if ($result > 0) + { + global $dolibarr_main_data_root; + $pathofwebsite=$dolibarr_main_data_root.'/website/'.$websiteobj->ref; - if (!$error) { - if (!$notrigger) { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action calls a trigger. + $filealias=$pathofwebsite.'/'.$this->pageurl.'.php'; + $filetpl=$pathofwebsite.'/page'.$this->id.'.tpl.php'; - //// Call triggers - //$result=$this->call_trigger('MYOBJECT_DELETE',$user); - //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} - //// End call triggers + dol_delete_file($filealias); + dol_delete_file($filetpl); } } - if (!$error) { - $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element; - $sql .= ' WHERE rowid=' . $this->id; - - $resql = $this->db->query($sql); - if (!$resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); - } - } - - // Commit or rollback - if ($error) { - $this->db->rollback(); - - return - 1 * $error; - } else { - $this->db->commit(); - - return 1; - } + return $result; } /** * Load an object from its id and create a new one in database * - * @param int $fromid Id of object to clone - * - * @return int New id of clone + * @param User $user User making the clone + * @param int $fromid Id of object to clone + * @param string $newref New ref/alias of page + * @param string $newlang New language + * @param int $istranslation 1=New page is a translation of the cloned page. + * @param int $newwebsite 0=Same web site, 1=New web site + * @return mixed New object created, <0 if KO */ - public function createFromClone($fromid) + public function createFromClone(User $user, $fromid, $newref, $newlang='', $istranslation=0, $newwebsite=0) { + global $hookmanager, $langs; + $error = 0; + dol_syslog(__METHOD__, LOG_DEBUG); - global $user; - $error = 0; - $object = new Websitepage($this->db); + $object = new self($this->db); $this->db->begin(); @@ -497,14 +358,20 @@ class WebsitePage extends CommonObject $object->id = 0; // Clear fields - // ... + $object->ref = $newref; + $object->pageurl = $newref; + $object->title = $langs->trans("CopyOf").' '.$object->title; + if (! empty($newlang)) $object->lang=$newlang; + if ($istranslation) $object->fk_page = $fromid; + else $object->fk_page = 0; + if (! empty($newwebsite)) $object->fk_website=$newwebsite; // Create clone + $object->context['createfromclone'] = 'createfromclone'; $result = $object->create($user); - - // Other options if ($result < 0) { - $error ++; + $error++; + $this->error = $object->error; $this->errors = $object->errors; dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); } @@ -513,11 +380,11 @@ class WebsitePage extends CommonObject if (!$error) { $this->db->commit(); - return $object->id; + return $object; } else { $this->db->rollback(); - return - 1; + return -1; } } @@ -545,17 +412,19 @@ class WebsitePage extends CommonObject $label.= '
    '; $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; - $link = 'picto?$this->picto:'generic'), ($notooltip?'':'class="classfortooltip"')).$linkend); + if ($withpicto != 2) $result.=' '; } - $result.= $link . $this->ref . $linkend; + $result.= $linkstart . $this->ref . $linkend; return $result; } @@ -632,8 +501,10 @@ class WebsitePage extends CommonObject $this->title = 'My Page'; $this->description = 'This is my page'; $this->keywords = 'keyword1, keyword2'; + $this->htmlheader = ''; $this->content = 'This is a html content'; $this->status = ''; + $this->grabbed_from = ''; $this->date_creation = $now - (24 * 30 * 3600); $this->date_modification = $now - (24 * 7 * 3600); } diff --git a/htdocs/websites/index.html b/htdocs/website/index.html similarity index 100% rename from htdocs/websites/index.html rename to htdocs/website/index.html diff --git a/htdocs/website/index.php b/htdocs/website/index.php new file mode 100644 index 00000000000..79eca309e59 --- /dev/null +++ b/htdocs/website/index.php @@ -0,0 +1,2145 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/website/index.php + * \ingroup website + * \brief Page to website view/edit + */ + +define('NOSCANPOSTFORINJECTION',1); +define('NOSTYLECHECK',1); + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formwebsite.class.php'; +require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; +require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; + +$langs->load("admin"); +$langs->load("other"); +$langs->load("website"); + +if (! $user->admin) accessforbidden(); + +if (! ((GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))) +{ + $conf->dol_hide_leftmenu = 1; // Force hide of left menu. +} + +$error=0; +$website=GETPOST('website', 'alpha'); +$page=GETPOST('page', 'alpha'); +$pageid=GETPOST('pageid', 'int'); +$pageref=GETPOST('pageref', 'aZ09'); +$action=GETPOST('action','alpha'); + + +if (GETPOST('delete')) { $action='delete'; } +if (GETPOST('preview')) $action='preview'; +if (GETPOST('createsite')) { $action='createsite'; } +if (GETPOST('create')) { $action='create'; } +if (GETPOST('file_manager')) { $action='file_manager'; } +if (GETPOST('editcss')) { $action='editcss'; } +if (GETPOST('editmenu')) { $action='editmenu'; } +if (GETPOST('setashome')) { $action='setashome'; } +if (GETPOST('editmeta')) { $action='editmeta'; } +if (GETPOST('editsource')) { $action='editsource'; } +if (GETPOST('editcontent')) { $action='editcontent'; } +if (GETPOST('createfromclone')) { $action='createfromclone'; } +if (GETPOST('createpagefromclone')) { $action='createpagefromclone'; } + +if (empty($action)) $action='preview'; + +$object=new Website($db); +$objectpage=new WebsitePage($db); + +$object->fetchAll(); // Init $object->records + +// If website not defined, we take first found +if (empty($website)) +{ + foreach($object->records as $key => $valwebsite) + { + $website=$valwebsite->ref; + break; + } +} +if ($website) +{ + $res = $object->fetch(0, $website); +} + +if ($pageid < 0) $pageid = 0; +if (($pageid > 0 || $pageref) && $action != 'add') +{ + $res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), $pageref); + $pageid = $objectpage->id; +} + +global $dolibarr_main_data_root; +$pathofwebsite=$dolibarr_main_data_root.'/website/'.$website; +$filehtmlheader=$pathofwebsite.'/htmlheader.html'; +$filecss=$pathofwebsite.'/styles.css.php'; +$filejs=$pathofwebsite.'/javascript.js.php'; +$filerobot=$pathofwebsite.'/robots.txt'; +$filehtaccess=$pathofwebsite.'/.htaccess'; +$filetpl=$pathofwebsite.'/page'.$pageid.'.tpl.php'; +$fileindex=$pathofwebsite.'/index.php'; + +// Define $urlwithroot +$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); +$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 + + + +/* + * Actions + */ + +if (GETPOST('refreshsite')) // If we change the site, we reset the pageid and cancel addsite action. +{ + $pageid=0; + if ($action == 'addsite') $action = 'preview'; +} +if (GETPOST('refreshpage') && ! in_array($action, array('updatecss'))) $action='preview'; + + +// Add site +if ($action == 'addsite') +{ + $db->begin(); + + if (! $error && ! GETPOST('WEBSITE_REF','alpha')) + { + $error++; + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); + } + if (! $error && ! preg_match('/^[a-z0-9_\-\.]+$/i', GETPOST('WEBSITE_REF','alpha'))) + { + $error++; + setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities("Ref")), null, 'errors'); + } + + if (! $error) + { + $tmpobject=new Website($db); + $tmpobject->ref = GETPOST('WEBSITE_REF','alpha'); + $tmpobject->description = GETPOST('WEBSITE_DESCRIPTION','alpha'); + $tmpobject->virtualhost = GETPOST('WEBSITE_VIRTUALHOST','alpha'); + + $result = $tmpobject->create($user); + if ($result <= 0) + { + $error++; + setEventMessages($tmpobject->error, $tmpobject->errors, 'errors'); + } + } + + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("SiteAdded", $object->ref), null, 'mesgs'); + $action=''; + + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$tmpobject->ref); + exit; + } + else + { + $db->rollback(); + $action='createsite'; + } + + if (! $error) + { + $action = 'preview'; + $id = $object->id; + } +} + +// Add page +if ($action == 'add') +{ + dol_mkdir($pathofwebsite); + + $db->begin(); + + $objectpage->fk_website = $object->id; + if (GETPOST('fetchexternalurl','alpha')) + { + $urltograb=GETPOST('externalurl','alpha'); + } + + if ($urltograb) + { + // Clean url to grab, so url can be + // http://www.example.com/ or http://www.example.com/dir1/ or http://www.example.com/dir1/aaa + $urltograbwithoutdomainandparam = preg_replace('/^https?:\/\/[^\/]+\/?/i', '', $urltograb); + $urltograbwithoutdomainandparam = preg_replace('/\?.*$/', '', $urltograbwithoutdomainandparam); + if (empty($urltograbwithoutdomainandparam) && ! preg_match('/\/$/', $urltograb)) + { + $urltograb.='/'; + } + $urltograbdirwithoutslash = dirname($urltograb.'.'); + + include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; + + $tmp = getURLContent($urltograb); + if ($tmp['curl_error_no']) + { + $error++; + setEventMessages($tmp['curl_error_msg'], null, 'errors'); + $action='create'; + } + else + { + preg_match('/(.*)<\/head>/is', $tmp['content'], $reg); + $head = $reg[1]; + + $objectpage->pageurl = dol_sanitizeFileName(preg_replace('/[\/\.]/','-',$urltograbwithoutdomainandparam)); + if (empty($objectpage->pageurl)) + { + $tmpdomain = getDomainFromURL($urltograb); + $objectpage->pageurl=$tmpdomain.'-home'; + } + + if (preg_match('/(.*)<\/title>/ims', $head, $regtmp)) + { + $objectpage->title = $regtmp[1]; + } + if (preg_match('/<meta name="description"[^"]+content="([^"]+)"/ims', $head, $regtmp)) + { + $objectpage->description = $regtmp[1]; + } + if (preg_match('/<meta name="keywords"[^"]+content="([^"]+)"/ims', $head, $regtmp)) + { + $objectpage->keywords = $regtmp[1]; + } + if (preg_match('/<html\s+lang="([^"]+)"/ims', $tmp['content'], $regtmp)) + { + $tmplang=explode('-', $regtmp[1]); + $objectpage->lang = $tmplang[0].($tmplang[1] ? '_'.strtoupper($tmplang[1]) : ''); + } + + $objectpage->content = $tmp['content']; + $objectpage->content = preg_replace('/^.*<body(\s[^>]*)*>/ims', '', $objectpage->content); + $objectpage->content = preg_replace('/<\/body(\s[^>]*)*>.*$/ims', '', $objectpage->content); + + $absoluteurlinaction=$urltograbdirwithoutslash; + // TODO Replace 'action="$urltograbdirwithoutslash' into action="/" + // TODO Replace 'action="$urltograbdirwithoutslash..."' into action="..." + // TODO Replace 'a href="$urltograbdirwithoutslash' into a href="/" + // TODO Replace 'a href="$urltograbdirwithoutslash..."' into a href="..." + + // Now loop to fetch all css files. Include them inline into header of page + $objectpage->htmlheader = $tmp['content']; + $objectpage->htmlheader = preg_replace('/^.*<head(\s[^>]*)*>/ims', '', $objectpage->htmlheader); + $objectpage->htmlheader = preg_replace('/<\/head(\s[^>]*)*>.*$/ims', '', $objectpage->htmlheader); + $objectpage->htmlheader = preg_replace('/<base(\s[^>]*)*>\n*/ims', '', $objectpage->htmlheader); + $objectpage->htmlheader = preg_replace('/<meta name="robot(\s[^>]*)*>\n*/ims', '', $objectpage->htmlheader); + $objectpage->htmlheader = preg_replace('/<meta name="keywords(\s[^>]*)*>\n*/ims', '', $objectpage->htmlheader); + $objectpage->htmlheader = preg_replace('/<meta name="title(\s[^>]*)*>\n*/ims', '', $objectpage->htmlheader); + $objectpage->htmlheader = preg_replace('/<meta name="description(\s[^>]*)*>\n*/ims', '', $objectpage->htmlheader); + $objectpage->htmlheader = preg_replace('/<meta name="generator(\s[^>]*)*>\n*/ims', '', $objectpage->htmlheader); + //$objectpage->htmlheader = preg_replace('/<meta name="verify-v1[^>]*>\n*/ims', '', $objectpage->htmlheader); + //$objectpage->htmlheader = preg_replace('/<meta name="msvalidate.01[^>]*>\n*/ims', '', $objectpage->htmlheader); + $objectpage->htmlheader = preg_replace('/<title>[^<]*<\/title>\n*/ims', '', $objectpage->htmlheader); + $objectpage->htmlheader = preg_replace('/<link[^>]*rel="shortcut[^>]*>\n/ims', '', $objectpage->htmlheader); + + // Now loop to fetch JS + $tmp = $objectpage->htmlheader; + + preg_match_all('/<script([^\.>]+)src=["\']([^"\'>]+)["\']([^>]*)><\/script>/i', $objectpage->htmlheader, $regs); + foreach ($regs[0] as $key => $val) + { + dol_syslog("We will grab the resource ".$regs[2][$key]); + + $linkwithoutdomain = $regs[2][$key]; + $urltograbbis = $urltograbdirwithoutslash.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; + + //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; + if (preg_match('/^http/', $regs[2][$key])) + { + $urltograbbis = $regs[2][$key]; + $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]); + //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; + } + + //print $domaintograb.' - '.$domaintograbbis.' - '.$urltograbdirwithoutslash.' - '; + //print $linkwithoutdomain.' - '.$urltograbbis."<br>\n"; + + // Test if this is an external URL of grabbed web site. If yes, we do not load resource + $domaintograb = getDomainFromURL($urltograbdirwithoutslash); + $domaintograbbis = getDomainFromURL($urltograbbis); + if ($domaintograb != $domaintograbbis) continue; + + /* + $tmpgeturl = getURLContent($urltograbbis); + if ($tmpgeturl['curl_error_no']) + { + $error++; + setEventMessages($tmpgeturl['curl_error_msg'], null, 'errors'); + $action='create'; + } + else + { + dol_mkdir(dirname($filetosave)); + + $fp = fopen($filetosave, "w"); + fputs($fp, $tmpgeturl['content']); + fclose($fp); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); + } + */ + + //$filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; + $tmp = preg_replace('/'.preg_quote($regs[0][$key],'/').'/i', '', $tmp); + } + $objectpage->htmlheader = trim($tmp); + + + // Now loop to fetch CSS + $pagecsscontent = "\n".'<style>'."\n"; + + preg_match_all('/<link([^\.>]+)href=["\']([^"\'>]+\.css[^"\'>]*)["\']([^>]*)>/i', $objectpage->htmlheader, $regs); + foreach ($regs[0] as $key => $val) + { + dol_syslog("We will grab the resource ".$regs[2][$key]); + + $linkwithoutdomain = $regs[2][$key]; + $urltograbbis = $urltograbdirwithoutslash.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; + + //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; + if (preg_match('/^http/', $regs[2][$key])) + { + $urltograbbis = $regs[2][$key]; + $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]); + //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; + } + + //print $domaintograb.' - '.$domaintograbbis.' - '.$urltograbdirwithoutslash.' - '; + //print $linkwithoutdomain.' - '.$urltograbbis."<br>\n"; + + // Test if this is an external URL of grabbed web site. If yes, we do not load resource + $domaintograb = getDomainFromURL($urltograbdirwithoutslash); + $domaintograbbis = getDomainFromURL($urltograbbis); + if ($domaintograb != $domaintograbbis) continue; + + $tmpgeturl = getURLContent($urltograbbis); + if ($tmpgeturl['curl_error_no']) + { + $error++; + setEventMessages($tmpgeturl['curl_error_msg'], null, 'errors'); + $action='create'; + } + else + { + //dol_mkdir(dirname($filetosave)); + + //$fp = fopen($filetosave, "w"); + //fputs($fp, $tmpgeturl['content']); + //fclose($fp); + //if (! empty($conf->global->MAIN_UMASK)) + // @chmod($file, octdec($conf->global->MAIN_UMASK)); + } + + // $filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; + $pagecsscontent.='/* Content of file '.$urltograbbis.' */'."\n"; + + getAllImages($object, $objectpage, $urltograbbis, $tmpgeturl['content'], $action, 1); + + $pagecsscontent.=$tmpgeturl['content']."\n"; + + $objectpage->htmlheader = preg_replace('/'.preg_quote($regs[0][$key],'/').'\n*/ims', '', $objectpage->htmlheader); + } + + $pagecsscontent.='</style>'."\n"; + //var_dump($pagecsscontent); + + //print dol_escape_htmltag($tmp);exit; + $objectpage->htmlheader .= $pagecsscontent; + + + // Now loop to fetch all images + $tmp = $objectpage->content; + + getAllImages($object, $objectpage, $urltograb, $tmp, $action, 1); + + //print dol_escape_htmltag($tmp);exit; + $objectpage->content = $tmp; + + $objectpage->grabbed_from = $urltograb; + } + } + else + { + $objectpage->title = GETPOST('WEBSITE_TITLE','alpha'); + $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME','alpha'); + $objectpage->description = GETPOST('WEBSITE_DESCRIPTION','alpha'); + $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS','alpha'); + $objectpage->lang = GETPOST('WEBSITE_LANG','aZ09'); + $objectpage->htmlheader = GETPOST('htmlheader','none'); + } + + if (! $error) + { + if (empty($objectpage->pageurl)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); + $error++; + $action='create'; + } + else if (! preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) + { + setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors'); + $error++; + $action='create'; + } + if (empty($objectpage->title)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_TITLE")), null, 'errors'); + $error++; + $action='create'; + } + } + + if (! $error) + { + $res = $objectpage->create($user); + if ($res <= 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } + } + if (! $error) + { + if (! empty($objectpage->content)) + { + $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; + $filetpl=$pathofwebsite.'/page'.$objectpage->id.'.tpl.php'; + + // Save page alias + $result=dolSavePageAlias($filealias, $object, $objectpage); + if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + + // Save page of content + $result=dolSavePageContent($filetpl, $object, $objectpage); + if ($result) + { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + //exit; + } + else + { + setEventMessages('Failed to write file '.$filetpl, null, 'errors'); + //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + //exit; + } + } + } + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); + $action=''; + } + else + { + $db->rollback(); + } + + if (! $error) + { + $pageid = $objectpage->id; + + // To generate the CSS, robot and htmlheader file. + + // Check symlink to medias and restore it if ko + $pathtomedias=DOL_DATA_ROOT.'/medias'; + $pathtomediasinwebsite=$pathofwebsite.'/medias'; + if (! is_link(dol_osencode($pathtomediasinwebsite))) + { + dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); + dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists + $result = symlink($pathtomedias, $pathtomediasinwebsite); + } + + if (! dol_is_file($filehtmlheader)) + { + $htmlheadercontent = "<!-- HTML header content (common for all pages) -->"; + $result=dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); + } + + if (! dol_is_file($filecss)) + { + $csscontent = "/* CSS content (all pages) */\nbody.bodywebsite { margin: 0; }"; + $result=dolSaveCssFile($filecss, $csscontent); + } + + if (! dol_is_file($filejs)) + { + $jscontent = "/* JS content (all pages) */\n"; + $result=dolSaveJsFile($filejs, $jscontent); + } + + if (! dol_is_file($filerobot)) + { + $robotcontent = "# Robot file. Generated with Dolibarr\nUser-agent: *\nAllow: /public/\nDisallow: /administrator/"; + $result=dolSaveRobotFile($filerobot, $robotcontent); + } + + if (! dol_is_file($filehtaccess)) + { + $htaccesscontent = "# Order allow,deny\n# Deny from all"; + $result=dolSaveHtaccessFile($filehtaccess, $htaccesscontent); + } + + $action = 'preview'; + } +} + +// Delete page +if ($action == 'delete') +{ + $db->begin(); + + $res = $object->fetch(0, $website); + + $res = $objectpage->fetch($pageid, $object->fk_website); + + if ($res > 0) + { + $res = $objectpage->delete($user); + if (! $res > 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } + + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); + + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website); + exit; + } + else + { + $db->rollback(); + } + } + else + { + dol_print_error($db); + } +} + +// Update css +if ($action == 'updatecss') +{ + if (GETPOST('refreshsite') || GETPOST('refreshpage')) // If we tried to reload another site/page, we stay on editcss mode. + { + $action='editcss'; + } + else + { + $res = $object->fetch(0, $website); + + // Html header file + $htmlheadercontent =''; + + /* We disable php code since htmlheader is never executed as an include but only read by fgets_content. + $htmlheadercontent.= "<?php // BEGIN PHP\n"; + $htmlheadercontent.= '$websitekey=basename(dirname(__FILE__));'."\n"; + $htmlheadercontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once './master.inc.php'; } // Not already loaded"."\n"; + $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $htmlheadercontent.= "ob_start();\n"; + // $htmlheadercontent.= "header('Content-type: text/html');\n"; // Not required. htmlheader.html is never call as a standalone page + $htmlheadercontent.= "// END PHP ?>\n";*/ + + $htmlheadercontent.= preg_replace(array('/<html>\n*/ims','/<\/html>\n*/ims'),array('',''),GETPOST('WEBSITE_HTML_HEADER', 'none')); + + /*$htmlheadercontent.= "\n".'<?php // BEGIN PHP'."\n"; + $htmlheadercontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n"; + $htmlheadercontent.= "// END PHP ?>"."\n";*/ + + $htmlheadercontent = trim($htmlheadercontent)."\n"; + + dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); + + + // Css file + $csscontent =''; + + $csscontent.= "<?php // BEGIN PHP\n"; + $csscontent.= '$websitekey=basename(dirname(__FILE__));'."\n"; + $csscontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once dirname(__FILE__).'/master.inc.php'; } // Not already loaded"."\n"; // For the css, we need to set path of master using the dirname of css file. + $csscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $csscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $csscontent.= "ob_start();\n"; + $csscontent.= "header('Content-type: text/css');\n"; + $csscontent.= "// END PHP ?>\n"; + + $csscontent.= GETPOST('WEBSITE_CSS_INLINE', 'none'); + + $csscontent.= "\n".'<?php // BEGIN PHP'."\n"; + $csscontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n"; + $csscontent.= "// END PHP ?>"."\n"; + + dol_syslog("Save css content into ".$filecss); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filecss, $csscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filecss, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + $error++; + setEventMessages('Failed to write file '.$filecss, null, 'errors'); + } + + + // Js file + $jscontent =''; + + $jscontent.= "<?php // BEGIN PHP\n"; + $jscontent.= '$websitekey=basename(dirname(__FILE__));'."\n"; + $jscontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once dirname(__FILE__).'/master.inc.php'; } // Not already loaded"."\n"; // For the css, we need to set path of master using the dirname of css file. + $jscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $jscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $jscontent.= "ob_start();\n"; + $jscontent.= "header('Content-type: application/javascript');\n"; + $jscontent.= "// END PHP ?>\n"; + + $jscontent.= GETPOST('WEBSITE_JS_INLINE', 'none'); + + $jscontent.= "\n".'<?php // BEGIN PHP'."\n"; + $jscontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n"; + $jscontent.= "// END PHP ?>"."\n"; + + dol_syslog("Save js content into ".$filejs); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filejs, $jscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filejs, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + $error++; + setEventMessages('Failed to write file '.$filejs, null, 'errors'); + } + + + // Robot file + $robotcontent =''; + + /*$robotcontent.= "<?php // BEGIN PHP\n"; + $robotcontent.= '$websitekey=basename(dirname(__FILE__));'."\n"; + $robotcontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once './master.inc.php'; } // Not already loaded"."\n"; + $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $robotcontent.= "ob_start();\n"; + $robotcontent.= "header('Content-type: text/css');\n"; + $robotcontent.= "// END PHP ?>\n";*/ + + $robotcontent.= GETPOST('WEBSITE_ROBOT', 'none'); + + /*$robotcontent.= "\n".'<?php // BEGIN PHP'."\n"; + $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n"; + $robotcontent.= "// END PHP ?>"."\n";*/ + + dol_syslog("Save file robot into ".$filerobot); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filerobot, $robotcontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filerobot, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + $error++; + setEventMessages('Failed to write file '.$filerobot, null, 'errors'); + } + + + // Css file + $htaccesscontent =''; + + /*$robotcontent.= "<?php // BEGIN PHP\n"; + $robotcontent.= '$websitekey=basename(dirname(__FILE__));'."\n"; + $robotcontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once './master.inc.php'; } // Not already loaded"."\n"; + $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $robotcontent.= "ob_start();\n"; + $robotcontent.= "header('Content-type: text/css');\n"; + $robotcontent.= "// END PHP ?>\n";*/ + + $htaccesscontent.= GETPOST('WEBSITE_HTACCESS', 'none'); + + /*$robotcontent.= "\n".'<?php // BEGIN PHP'."\n"; + $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n"; + $robotcontent.= "// END PHP ?>"."\n";*/ + + dol_syslog("Save file htaccess into ".$filehtaccess); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filehtaccess, $htaccesscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filehtaccess, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + $error++; + setEventMessages('Failed to write file '.$filehtaccess, null, 'errors'); + } + + // Message if no error + if (! $error) + { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + } + + $action='preview'; + } +} + +// Update page +if ($action == 'setashome') +{ + $db->begin(); + $object->fetch(0, $website); + + $object->fk_default_home = $pageid; + $res = $object->update($user); + if (! $res > 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } + + if (! $error) + { + $db->commit(); + + // Generate the index.php page to be the home page + //------------------------------------------------- + dol_mkdir($pathofwebsite); + dol_delete_file($fileindex); + + $indexcontent = '<?php'."\n"; + $indexcontent.= '// File generated to provide a shortcut to the Home Page - DO NOT MODIFY - It is just an include.'."\n"; + $indexcontent.= "include_once './".basename($filetpl)."'\n"; + $indexcontent.= '?>'."\n"; + $result = file_put_contents($fileindex, $indexcontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($fileindex, octdec($conf->global->MAIN_UMASK)); + + if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); + else setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + + $action='preview'; + } + else + { + $db->rollback(); + } +} + +// Update page (meta) +if ($action == 'updatemeta') +{ + $db->begin(); + $object->fetch(0, $website); + + $objectpage->fk_website = $object->id; + + // Check parameters + if (! preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) + { + $error++; + setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors'); + $action='editmeta'; + } + + $res = $objectpage->fetch($pageid, $object->fk_website); + if ($res <= 0) + { + $error++; + dol_print_error($db, 'Page not found'); + } + + if (! $error) + { + $objectpage->old_object = clone $objectpage; + + $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); + $objectpage->title = GETPOST('WEBSITE_TITLE', 'alpha'); + $objectpage->description = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); + $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS', 'alpha'); + $objectpage->lang = GETPOST('WEBSITE_LANG', 'aZ09'); + $objectpage->htmlheader = GETPOST('htmlheader', 'none'); + + $res = $objectpage->update($user); + if (! $res > 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } + + if (! $error) + { + $db->commit(); + + $filemaster=$pathofwebsite.'/master.inc.php'; + $fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; + $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; + + dol_mkdir($pathofwebsite); + + + // Now generate the master.inc.php page + dol_syslog("We regenerate the master file (because we update meta)"); + dol_delete_file($filemaster); + + $mastercontent = '<?php'."\n"; + $mastercontent.= '// File generated to link to the master file - DO NOT MODIFY - It is just an include'."\n"; + $mastercontent.= "if (! defined('USEDOLIBARRSERVER')) require_once '".DOL_DOCUMENT_ROOT."/master.inc.php';\n"; + //$mastercontent.= "include_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php';"."\n"; + //$mastercontent.= '$website = new WebSite($db)'."\n"; + $mastercontent.= '?>'."\n"; + $result = file_put_contents($filemaster, $mastercontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); + + if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + + + // Now generate the alias.php page + if (! empty($fileoldalias)) + { + dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); + dol_delete_file($fileoldalias); + } + + // Save page alias + $result=dolSavePageAlias($filealias, $object, $objectpage); + if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + + // Save page of content + $result=dolSavePageContent($filetpl, $object, $objectpage); + if ($result) + { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + //exit; + } + else + { + setEventMessages('Failed to write file '.$filetpl, null, 'errors'); + //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + //exit; + } + + $action='preview'; + } + else + { + $db->rollback(); + } + } +} + +// Update page +if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'confirm_createfromclone' || $action == 'confirm_createpagefromclone') + || ($action == 'preview' && (GETPOST('refreshsite') || GETPOST('refreshpage') || GETPOST('preview')))) +{ + $object->fetch(0, $website); + + if ($action == 'confirm_createfromclone') + { + $objectnew = new Website($db); + $result = $objectnew->createFromClone($user, GETPOST('id','int'), GETPOST('siteref','aZ09'), (GETPOST('newlang','aZ09')?GETPOST('newlang','aZ09'):'')); + if ($result < 0) + { + $error++; + setEventMessages($objectnew->error, $objectnew->errors, 'errors'); + $action='preview'; + } + else + { + $object = $objectnew; + $id = $object->id; + $pageid = $object->fk_default_home; + } + } + + if ($action == 'confirm_createpagefromclone') + { + $istranslation=(GETPOST('is_a_translation','aZ09')=='on'?1:0); + if ($istranslation) + { + if (GETPOST('newlang','aZ09') == $objectpage->lang) + { + $error++; + setEventMessages($langs->trans("LanguageMustNotBeSameThanClonedPage"), null, 'errors'); + $action='preview'; + } + } + + if (! $error) + { + $objectpage = new WebsitePage($db); + $result = $objectpage->createFromClone($user, $pageid, GETPOST('pageurl','aZ09'), (GETPOST('newlang','aZ09')?GETPOST('newlang','aZ09'):''), $istranslation, GETPOST('newwebsite','int')); + if ($result < 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + $action='createpagefromclone'; + } + else + { + // TODO Switch on the new page ? + } + } + } + + $res = 0; + + if (! $error) + { + // Check symlink to medias and restore it if ko + $pathtomedias=DOL_DATA_ROOT.'/medias'; + $pathtomediasinwebsite=$pathofwebsite.'/medias'; + if (! is_link(dol_osencode($pathtomediasinwebsite))) + { + dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); + dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists + $result = symlink($pathtomedias, $pathtomediasinwebsite); + } + + /*if (GETPOST('savevirtualhost') && $object->virtualhost != GETPOST('previewsite')) + { + $object->virtualhost = GETPOST('previewsite', 'alpha'); + $object->update($user); + }*/ + + $objectpage->fk_website = $object->id; + + if ($pageid > 0) + { + $res = $objectpage->fetch($pageid); + } + else + { + $res=0; + if ($object->fk_default_home > 0) + { + $res = $objectpage->fetch($object->fk_default_home); + } + if (! ($res > 0)) + { + $res = $objectpage->fetch(0, $object->id); + } + } + } + + if (! $error && $res > 0) + { + if ($action == 'updatesource' || $action == 'updatecontent') + { + $db->begin(); + + $objectpage->content = GETPOST('PAGE_CONTENT','none'); + + // Clean data. We remove all the head section. + $objectpage->content = preg_replace('/<head>.*<\/head>/s', '', $objectpage->content); + /* $objectpage->content = preg_replace('/<base\s+href=[\'"][^\'"]+[\'"]\s/?>/s', '', $objectpage->content); */ + + + $res = $objectpage->update($user); + if ($res < 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } + + if (! $error) + { + $db->commit(); + + $filemaster=$pathofwebsite.'/master.inc.php'; + //$fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; + $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; + + dol_mkdir($pathofwebsite); + + + // Now generate the master.inc.php page + dol_syslog("We regenerate the master file"); + dol_delete_file($filemaster); + + $mastercontent = '<?php'."\n"; + $mastercontent.= '// File generated to link to the master file'."\n"; + $mastercontent.= "if (! defined('USEDOLIBARRSERVER')) require_once '".DOL_DOCUMENT_ROOT."/master.inc.php';\n"; + $mastercontent.= '?>'."\n"; + $result = file_put_contents($filemaster, $mastercontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); + + if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + + + // Now generate the alias.php page + if (! empty($fileoldalias)) + { + dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); + dol_delete_file($fileoldalias); + } + + // Save page alias + $result=dolSavePageAlias($filealias, $object, $objectpage); + if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + + // Save page content + $result=dolSavePageContent($filetpl, $object, $objectpage); + if ($result) + { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + exit; + } + else + { + setEventMessages('Failed to write file '.$filetpl, null, 'errors'); + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + exit; + } + } + else + { + $db->rollback(); + } + } + else + { + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + exit; + } + } + else + { + if (! $error) setEventMessages($langs->trans("NoPageYet"), null, 'warnings'); + } +} + +// Export site +if (GETPOST('exportsite')) +{ + $fileofzip = $object->exportWebSite(); + + $file_name = basename($fileofzip); + + header("Content-Type: application/zip"); + header("Content-Disposition: attachment; filename=".$file_name); + header("Content-Length: " . filesize($fileofzip)); + + readfile($fileofzip); + exit; +} + + + +/* + * View + */ + +$form = new Form($db); +$formadmin = new FormAdmin($db); +$formwebsite = new FormWebsite($db); + +$help_url=''; + +$arrayofjs = array( + '/includes/ace/ace.js', + '/includes/ace/ext-statusbar.js', + '/includes/ace/ext-language_tools.js', + //'/includes/ace/ext-chromevox.js' +); +$arrayofcss = array(); + +$moreheadcss=''; +$moreheadjs=''; + +$arrayofjs[]='includes/jquery/plugins/blockUI/jquery.blockUI.js'; +$arrayofjs[]='core/js/blockUI.js'; // Used by ecm/tpl/enabledfiletreeajax.tpl.pgp +if (empty($conf->global->MAIN_ECM_DISABLE_JS)) $arrayofjs[]="includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js"; + +$moreheadjs.='<script type="text/javascript">'."\n"; +$moreheadjs.='var indicatorBlockUI = \''.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'\';'."\n"; +$moreheadjs.='</script>'."\n"; + +llxHeader($moreheadcss.$moreheadjs, $langs->trans("websiteetup"), $help_url, '', 0, 0, $arrayofjs, $arrayofcss, '', '', '<!-- Begin div class="fiche" -->'."\n".'<div class="fichebutwithotherclass">'); + +print "\n".'<form action="'.$_SERVER["PHP_SELF"].'" method="POST"><div>'; +print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; +if ($action == 'createsite') +{ + print '<input type="hidden" name="action" value="addsite">'; +} +if ($action == 'create') +{ + print '<input type="hidden" name="action" value="add">'; +} +if ($action == 'editcss') +{ + print '<input type="hidden" name="action" value="updatecss">'; +} +if ($action == 'editmenu') +{ + print '<input type="hidden" name="action" value="updatemenu">'; +} +if ($action == 'setashome') +{ + print '<input type="hidden" name="action" value="updateashome">'; +} +if ($action == 'editmeta') +{ + print '<input type="hidden" name="action" value="updatemeta">'; +} +if ($action == 'editsource') +{ + print '<input type="hidden" name="action" value="updatesource">'; +} +if ($action == 'editcontent') +{ + print '<input type="hidden" name="action" value="updatecontent">'; +} +if ($action == 'edit') +{ + print '<input type="hidden" name="action" value="update">'; +} + + +// Add a margin under toolbar ? +$style=''; +if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource') $style=' margin-bottom: 5px;'; + +//var_dump($objectpage);exit; +print '<div class="centpercent websitebar">'; + +if (count($object->records) > 0) +{ + // ***** Part for web sites + + print '<div class="websiteselection hideonsmartphoneimp minwwidth100">'; + print '<input type="submit"'.$disabled.' class="button" value="'.dol_escape_htmltag($langs->trans("AddWebsite")).'" name="createsite">'; + print '</div>'; + + print '<div class="websiteselection hideonsmartphoneimp">'; + print $langs->trans("WebSite").': '; + print '</div>'; + + // List of website + print '<div class="websiteselection">'; + $out=''; + $out.='<select name="website" class="minwidth100" id="website">'; + if (empty($object->records)) $out.='<option value="-1"> </option>'; + // Loop on each sites + $i=0; + foreach($object->records as $key => $valwebsite) + { + if (empty($website)) $website=$valwebsite->ref; + + $out.='<option value="'.$valwebsite->ref.'"'; + if ($website == $valwebsite->ref) $out.=' selected'; // To preselect a value + $out.='>'; + $out.=$valwebsite->ref; + $out.='</option>'; + $i++; + } + $out.='</select>'; + $out.=ajax_combobox('website'); + print $out; + print '<input type="submit" class="button" name="refreshsite" value="'.$langs->trans("Load").'">'; + + if ($website) + { + $virtualurl=''; + $dataroot=DOL_DATA_ROOT.'/website/'.$website; + if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; + } + + if ($website && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) + { + $disabled=''; + if (empty($user->rights->website->write)) $disabled=' disabled="disabled"'; + + print '   '; + + print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditCss")).'" name="editcss">'; + //print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditMenu")).'" name="editmenu">'; + print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("CloneSite")).'" name="createfromclone">'; + print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("ExportSite")).'" name="exportsite">'; + + print '   '; + + print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">'; + } + + print '</div>'; + + // Button for website + print '<div class="websitetools">'; + + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') + { + print '<a class="websitebuttonsitepreview" id="previewsite" href="'.$urlwithroot.'/public/website/index.php?website='.$website.'" target="tab'.$website.'" alt="'.dol_escape_htmltag($langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint, $dataroot), 1, 'preview'); + print '</a>'; + + print '<div class="websiteinputurl" id="websiteinputurl">'; + print '<input type="text" id="previewsiteurl" class="minwidth200imp" name="previewsite" placeholder="'.$langs->trans("http://myvirtualhost").'" value="'.$virtualurl.'">'; + //print '<input type="submit" class="button" name="previewwebsite" target="tab'.$website.'" value="'.$langs->trans("ViewSiteInNewTab").'">'; + $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); + print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helpvirtualhost'); + print '</div>'; + + $urlext=$virtualurl; + $urlint=$urlwithroot.'/public/website/index.php?website='.$website; + print '<a class="websitebuttonsitepreview'.($urlext?'':' websitebuttonsitepreviewdisabled cursornotallowed').'" id="previewsiteext" href="'.$urlext.'" target="tab'.$website.'ext" alt="'.dol_escape_htmltag($langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext?$urlext:'<span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span>'), 1, 'preview_ext'); + print '</a>'; + } + + if (in_array($action, array('editcss','editmenu','file_manager'))) + { + if (preg_match('/^create/',$action) && $action != 'file_manager') print '<input type="submit" id="savefile" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + if (preg_match('/^edit/',$action) && $action != 'file_manager') print '<input type="submit" id="savefile" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + if ($action != 'preview') print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="preview">'; + } + + print '</div>'; + + + // ***** Part for pages + + if ($website && ! in_array($action, array('editcss','editmenu','file_manager'))) + { + print '</div>'; // Close current websitebar to open a new one + + $array=$objectpage->fetchAll($object->id); + if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + $atleastonepage=(is_array($array) && count($array) > 0); + + print '<div class="centpercent websitebar"'.($style?' style="'.$style.'"':'').'">'; + + print '<div class="websiteselection hideonsmartphoneimp minwidth100">'; + print '<input type="submit"'.$disabled.' class="button" value="'.dol_escape_htmltag($langs->trans("AddPage")).'" name="create">'; + print '</div>'; + + print '<div class="websiteselection hideonsmartphoneimp">'; + print $langs->trans("Page").': '; + print '</div>'; + print '<div class="websiteselection">'; + + if ($action != 'add') + { + $out=''; + $out.='<select name="pageid" id="pageid" class="minwidth200 maxwidth300">'; + if ($atleastonepage) + { + if (empty($pageid) && $action != 'create') // Page id is not defined, we try to take one + { + $firstpageid=0;$homepageid=0; + foreach($array as $key => $valpage) + { + if (empty($firstpageid)) $firstpageid=$valpage->id; + if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid=$valpage->id; + } + $pageid=$homepageid?$homepageid:$firstpageid; // We choose home page and if not defined yet, we take first page + } + + foreach($array as $key => $valpage) + { + $out.='<option value="'.$key.'"'; + if ($pageid > 0 && $pageid == $key) $out.=' selected'; // To preselect a value + $out.='>'; + $out.=$valpage->pageurl.' - '.$valpage->title; + if ($object->fk_default_home && $key == $object->fk_default_home) $out.=' ('.$langs->trans("HomePage").')'; + $out.='</option>'; + } + } + else $out.='<option value="-1"> </option>'; + $out.='</select>'; + $out.=ajax_combobox('pageid'); + print $out; + } + else + { + print $langs->trans("New"); + } + + print '<input type="submit" class="button" name="refreshpage" value="'.$langs->trans("Load").'"'.($atleastonepage?'':' disabled="disabled"').'>'; + + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') + { + $disabled=''; + if (empty($user->rights->website->write)) $disabled=' disabled="disabled"'; + + // Confirmation to clone + if ($action == 'createfromclone') { + // Create an array for form + $formquestion = array( + array('type' => 'text', 'name' => 'siteref', 'label'=> $langs->trans("WebSite") ,'value'=> 'copy_of_'.$object->ref), + //array('type' => 'checkbox', 'name' => 'is_a_translation', 'label' => $langs->trans("SiteIsANewTranslation"), 'value' => 0), + //array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'az09')?GETPOST('newlang', 'az09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')), + //array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)) + ); + + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id='.$object->id, $langs->trans('CloneSite'), '', 'confirm_createfromclone', $formquestion, 0, 1, 200); + + print $formconfirm; + } + + if ($pageid > 0) + { + // Confirmation to clone + if ($action == 'createpagefromclone') { + // Create an array for form + $formquestion = array( + array('type' => 'text', 'name' => 'pageurl', 'label'=> $langs->trans("WEBSITE_PAGENAME") ,'value'=> 'copy_of_'.$objectpage->pageurl), + array('type' => 'checkbox', 'name' => 'is_a_translation', 'label' => $langs->trans("PageIsANewTranslation"), 'value' => 0), + array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'az09')?GETPOST('newlang', 'az09'):$langs->defaultlang, 'newlang', 0, null, 1, 0, 0, 'minwidth200')), + array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)), + ); + + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?website='.$object->ref.'&pageid=' . $pageid, $langs->trans('ClonePage'), '', 'confirm_createpagefromclone', $formquestion, 0, 1, 300, 550); + + print $formconfirm; + } + + print '   '; + + print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditPageMeta")).'" name="editmeta">'; + print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditWithEditor")).'" name="editcontent">'; + print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditHTMLSource")).'" name="editsource">'; + if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print '<input type="submit" class="button" disabled="disabled" value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">'; + else print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">'; + print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("ClonePage")).'" name="createpagefromclone">'; + print '<input type="submit" class="buttonDelete" name="delete" value="'.$langs->trans("Delete").'"'.($atleastonepage?'':' disabled="disabled"').'>'; + } + } + + print '</div>'; // end website selection + + print '<div class="websitetools">'; + + if ($website && $pageid > 0 && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) + { + $websitepage = new WebSitePage($db); + $websitepage->fetch($pageid); + + $realpage=$urlwithroot.'/public/website/index.php?website='.$website.'&pageref='.$websitepage->pageurl; + $pagealias = $websitepage->pageurl; + + print '<a class="websitebuttonsitepreview" id="previewpage" href="'.$realpage.'&nocache='.dol_now().'" class="button" target="tab'.$website.'" alt="'.dol_escape_htmltag($langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot), 1, 'preview'); + print '</a>'; // View page in new Tab + + print '<div class="websiteinputurl" id="websiteinputpage">'; + print '<input type="text" id="previewpageurl" class="minwidth200imp" name="previewsite" value="'.$pagealias.'" disabled="disabled">'; + $htmltext=$langs->trans("PageNameAliasHelp", $langs->transnoentitiesnoconv("EditPageMeta")); + print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helppagealias'); + print '</div>'; + + $urlext=$virtualurl.'/'.$pagealias.'.php'; + $urlint=$urlwithroot.'/public/website/index.php?website='.$website; + print '<a class="websitebuttonsitepreview'.($virtualurl?'':' websitebuttonsitepreviewdisabled cursornotallowed').'" id="previewpageext" href="'.$urlext.'" target="tab'.$website.'ext" alt="'.dol_escape_htmltag($langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $virtualurl?$urlext:'<span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span>'), 1, 'preview_ext'); + print '</a>'; + //print '<input type="submit" class="button" name="previewpage" target="tab'.$website.'"value="'.$langs->trans("ViewPageInNewTab").'">'; + + // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext + } + if (! in_array($action, array('editcss','editmenu','file_manager','createsite','create','createpagefromclone'))) + { + if (preg_match('/^create/',$action)) print '<input type="submit" id="savefile" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + if (preg_match('/^edit/',$action)) print '<input type="submit" id="savefile" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + if ($action != 'preview') print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="preview">'; + } + + print '</div>'; // end websitetools + + print '<div class="websitehelp">'; + if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) + { + $htmltext=$langs->transnoentitiesnoconv("YouCanEditHtmlSource"); + print $form->textwithpicto($langs->trans("SyntaxHelp"), $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution'); + } + print '</div>'; // end websitehelp + + + + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') + { + // Adding jquery code to change on the fly url of preview ext + if (! empty($conf->use_javascript_ajax)) + { + print '<script type="text/javascript" language="javascript"> + jQuery(document).ready(function() { + jQuery("#websiteinputurl").keyup(function() { + console.log("Website external url modified "+jQuery("#previewsiteurl").val()); + if (jQuery("#previewsiteurl").val() != "") jQuery("a.websitebuttonsitepreviewdisabled img").css({ opacity: 1 }); + else jQuery("a.websitebuttonsitepreviewdisabled img").css({ opacity: 0.2 }); + }); + jQuery("#previewsiteext,#previewpageext").click(function() { + newurl=jQuery("#previewsiteurl").val(); + newpage=jQuery("#previewsiteurl").val() + "/" + jQuery("#previewpageurl").val() + ".php"; + console.log("Open url "+newurl); + /* Save url */ + jQuery.ajax({ + method: "POST", + url: "'.DOL_URL_ROOT.'/core/ajax/saveinplace.php", + data: { + field: \'editval_virtualhost\', + element: \'website\', + table_element: \'website\', + fk_element: '.$object->id.', + value: newurl, + }, + context: document.body + }); + + jQuery("#previewsiteext").attr("href",newurl); + jQuery("#previewpageext").attr("href",newpage); + }); + }); + </script>'; + } + } + } +} +else +{ + print '<div class="websiteselection">'; + $langs->load("errors"); + print $langs->trans("ErrorModuleSetupNotComplete"); + print '<div>'; + $action=''; +} + + +print '</div>'; // end current websitebar + +$head = array(); + + +/* + * Edit mode + */ + +if ($action == 'editcss') +{ + print '<div class="fiche">'; + + print '<br>'; + + $csscontent = @file_get_contents($filecss); + // Clean the php css file to remove php code and get only css part + $csscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $csscontent); + $csscontent.= GETPOST('WEBSITE_CSS_INLINE'); + if (! trim($csscontent)) $csscontent='/* CSS content (all pages) */'."\n".'body.bodywebsite { margin: 0; }'; + + $jscontent = @file_get_contents($filejs); + // Clean the php js file to remove php code and get only js part + $jscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $jscontent); + $jscontent.= GETPOST('WEBSITE_JS_INLINE'); + if (! trim($jscontent)) $jscontent='/* JS content (all pages) */'."\n"; + + $htmlheader = @file_get_contents($filehtmlheader); + // Clean the php htmlheader file to remove php code and get only html part + $htmlheader = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htmlheader); + if (! trim($htmlheader)) $htmlheader='<!-- HTML header content (common for all pages) -->'; + else $htmlheader='<html>'."\n".trim($htmlheader)."\n".'</html>'; + + $robotcontent = @file_get_contents($filerobot); + // Clean the php htmlheader file to remove php code and get only html part + $robotcontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $robotcontent); + if (! trim($robotcontent)) + { + $robotcontent.="# Robot file. Generated with ".DOL_APPLICATION_TITLE."\n"; + $robotcontent.="User-agent: *\n"; + $robotcontent.="Allow: /public/\n"; + $robotcontent.="Disallow: /administrator/\n"; + } + + $htaccesscontent = @file_get_contents($filehtaccess); + // Clean the php htaccesscontent file to remove php code and get only html part + $htaccesscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htaccesscontent); + if (! trim($htaccesscontent)) + { + $htaccesscontent.="# Order allow,deny\n"; + $htaccesscontent.="# Deny from all\n"; + } + //else $htaccesscontent='<html>'."\n".$htaccesscontent."\n".'</html>';*/ + + dol_fiche_head(); + + print '<!-- Edit CSS -->'."\n"; + print '<table class="border" width="100%">'; + + // Website + print '<tr><td class="titlefieldcreate">'; + print $langs->trans('WebSite'); + print '</td><td>'; + print $website; + print '</td></tr>'; + + // CSS file + print '<tr><td class="tdtop">'; + print $langs->trans('WEBSITE_CSS_INLINE'); + print '</td><td>'; + + $doleditor=new DolEditor('WEBSITE_CSS_INLINE', $csscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + print $doleditor->Create(1, '', true, 'CSS', 'css'); + + print '</td></tr>'; + + // JS file + print '<tr><td class="tdtop">'; + print $langs->trans('WEBSITE_JS_INLINE'); + print '</td><td>'; + + $doleditor=new DolEditor('WEBSITE_JS_INLINE', $jscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + print $doleditor->Create(1, '', true, 'JS', 'javascript'); + + print '</td></tr>'; + + // Common HTML header + print '<tr><td class="tdtop">'; + print $langs->trans('WEBSITE_HTML_HEADER'); + print '</td><td>'; + + $doleditor=new DolEditor('WEBSITE_HTML_HEADER', $htmlheader, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + print $doleditor->Create(1, '', true, 'HTML Header', 'html'); + + print '</td></tr>'; + + // Robot file + print '<tr><td class="tdtop">'; + print $langs->trans('WEBSITE_ROBOT'); + print '</td><td>'; + + $doleditor=new DolEditor('WEBSITE_ROBOT', $robotcontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + print $doleditor->Create(1, '', true, 'Robot file', 'txt'); + + print '</td></tr>'; + + // .htaccess + print '<tr><td class="tdtop">'; + print $langs->trans('WEBSITE_HTACCESS'); + print '</td><td>'; + + $doleditor=new DolEditor('WEBSITE_HTACCESS', $htaccesscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + print $doleditor->Create(1, '', true, $langs->trans("File").' .htaccess', 'txt'); + + print '</td></tr>'; + + print '</table>'; + + dol_fiche_end(); + + print '</div>'; + + print '<br>'; +} + +if ($action == 'createsite') +{ + print '<div class="fiche">'; + + print '<br>'; + + /*$h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath('/website/index.php',1).'?id='.$object->id; + $head[$h][1] = $langs->trans("AddSite"); + $head[$h][2] = 'card'; + $h++; + + dol_fiche_head($head, 'card', $langs->trans("AddSite"), -1, 'globe'); + */ + if ($action == 'create') print_fiche_titre($langs->trans("AddSite")); + + print '<!-- Add site -->'."\n"; + //print '<div class="fichecenter">'; + + print '<table class="border" width="100%">'; + + if (GETPOST('WEBSITE_REF')) $siteref=GETPOST('WEBSITE_REF','alpha'); + if (GETPOST('WEBSITE_DESCRIPTION')) $sitedesc=GETPOST('WEBSITE_DESCRIPTION','alpha'); + + print '<tr><td class="titlefieldcreate fieldrequired">'; + print $langs->trans('Ref'); + print '</td><td>'; + print '<input type="text" class="flat maxwidth300" name="WEBSITE_REF" value="'.dol_escape_htmltag($siteref).'">'; + print '</td></tr>'; + + print '<tr><td>'; + print $langs->trans('Description'); + print '</td><td>'; + print '<input type="text" class="flat minwidth300" name="WEBSITE_DESCRIPTION" value="'.dol_escape_htmltag($sitedesc).'">'; + print '</td></tr>'; + + print '<tr><td>'; + print $form->textwithpicto($langs->trans('Virtualhost'), $langs->trans("SetHereVirtualHost", DOL_DATA_ROOT.'/website/<i>websiteref</i>'), 1, 'help', '', 0, 2, 'tooltipvirtual'); + print '</td><td>'; + print '<input type="text" class="flat minwidth300" name="WEBSITE_DESCRIPTION" value="'.dol_escape_htmltag($sitedesc).'">'; + print '</td></tr>'; + + + print '</table>'; + + if ($action == 'createsite') + { + print '<div class="center">'; + + print '<input class="button" type="submit" name="add" value="'.$langs->trans("Create").'">'; + print '<input class="button" type="submit" name="preview" value="'.$langs->trans("Cancel").'">'; + + print '</div>'; + } + + + //print '</div>'; + + //dol_fiche_end(); + + print '</div>'; + + print '<br>'; +} + +if ($action == 'editmeta' || $action == 'create') +{ + print '<div class="fiche">'; + + print '<br>'; + + /*$h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath('/website/index.php',1).'?id='.$object->id; + $head[$h][1] = $langs->trans("AddPage"); + $head[$h][2] = 'card'; + $h++; + + dol_fiche_head($head, 'card', $langs->trans("AddPage"), -1, 'globe'); + */ + if ($action == 'create') print_fiche_titre($langs->trans("AddPage")); + + print '<!-- Edit or create page -->'."\n"; + //print '<div class="fichecenter">'; + + if ($action == 'create') + { + print '<br>'; + + print ' * '.$langs->trans("CreateByFetchingExternalPage").'<br><hr>'; + print '<table class="border" width="100%">'; + print '<tr><td class="titlefieldcreate">'; + print $langs->trans("URL"); + print '</td><td>'; + print '<input class="flat minwidth300" type="text" name="externalurl" value="'.dol_escape_htmltag(GETPOST('externalurl','alpha')).'" placeholder="http://externalsite/pagetofetch"> '; + print '<input class="button" type="submit" name="fetchexternalurl" value="'.dol_escape_htmltag($langs->trans("FetchAndCreate")).'">'; + print '</td></tr>'; + print '</table>'; + + print '<br>'; + + print ' * '.$langs->trans("OrEnterPageInfoManually").'<br><hr>'; + } + + print '<table class="border" width="100%">'; + + if ($action != 'create') + { + print '<tr><td class="titlefield">'; + print $langs->trans('IDOfPage'); + print '</td><td>'; + print $pageid; + print '</td></tr>'; + + print '<tr><td class="titlefield">'; + print $langs->trans('WEBSITE_PAGEURL'); + print '</td><td>'; + print '/public/website/index.php?website='.urlencode($website).'&pageid='.urlencode($pageid); + print '</td></tr>'; + + /* + print '<tr><td class="titlefield">'; + print $langs->trans('InitiallyGrabbedFrom'); + print '</td><td>'; + print $objectpage->grabbed_from; + print '</td></tr>'; + */ + + $pageurl=$objectpage->pageurl; + $pagetitle=$objectpage->title; + $pagedescription=$objectpage->description; + $pagekeywords=$objectpage->keywords; + $pagelang=$objectpage->lang; + $pagehtmlheader=$objectpage->htmlheader; + } + if (GETPOST('WEBSITE_PAGENAME','alpha')) $pageurl=GETPOST('WEBSITE_PAGENAME','alpha'); + if (GETPOST('WEBSITE_TITLE','alpha')) $pagetitle=GETPOST('WEBSITE_TITLE','alpha'); + if (GETPOST('WEBSITE_DESCRIPTION','alpha')) $pagedescription=GETPOST('WEBSITE_DESCRIPTION','alpha'); + if (GETPOST('WEBSITE_KEYWORDS','alpha')) $pagekeywords=GETPOST('WEBSITE_KEYWORDS','alpha'); + if (GETPOST('WEBSITE_LANG','aZ09')) $pagelang=GETPOST('WEBSITE_LANG','aZ09'); + if (GETPOST('htmlheader','none')) $pagehtmlheader=GETPOST('htmlheader','none'); + + print '<tr><td class="titlefieldcreate fieldrequired">'; + print $langs->trans('WEBSITE_PAGENAME'); + print '</td><td>'; + print '<input type="text" class="flat maxwidth300" name="WEBSITE_PAGENAME" value="'.dol_escape_htmltag($pageurl).'">'; + print '</td></tr>'; + + print '<tr><td class="fieldrequired">'; + print $langs->trans('WEBSITE_TITLE'); + print '</td><td>'; + print '<input type="text" class="flat quatrevingtpercent" name="WEBSITE_TITLE" value="'.dol_escape_htmltag($pagetitle).'">'; + print '</td></tr>'; + + print '<tr><td>'; + print $langs->trans('WEBSITE_DESCRIPTION'); + print '</td><td>'; + print '<input type="text" class="flat quatrevingtpercent" name="WEBSITE_DESCRIPTION" value="'.dol_escape_htmltag($pagedescription).'">'; + print '</td></tr>'; + + print '<tr><td>'; + print $langs->trans('WEBSITE_KEYWORDS'); + print '</td><td>'; + print '<input type="text" class="flat quatrevingtpercent" name="WEBSITE_KEYWORDS" value="'.dol_escape_htmltag($pagekeywords).'">'; + print '</td></tr>'; + + print '<tr><td>'; + print $langs->trans('Language'); + print '</td><td>'; + print $formadmin->select_language($pagelang?$pagelang:$langs->defaultlang, 'WEBSITE_LANG', 0, null, '1'); + print '</td></tr>'; + + print '<tr><td>'; + print $langs->trans('HtmlHeaderPage'); + print '</td><td>'; + $doleditor=new DolEditor('htmlheader', $pagehtmlheader, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + print $doleditor->Create(1, '', true, 'HTML Header', 'html'); + print '</td></tr>'; + + print '</table>'; + + if ($action == 'create') + { + print '<div class="center">'; + + print '<input class="button" type="submit" name="add" value="'.$langs->trans("Create").'">'; + print '<input class="button" type="submit" name="preview" value="'.$langs->trans("Cancel").'">'; + + print '</div>'; + } + + + //print '</div>'; + + //dol_fiche_end(); + + print '</div>'; + + print '<br>'; +} + +if ($action == 'file_manager') +{ + print '<!-- Edit Media -->'."\n"; + print '<br><br>'; + //print '<div class="center">'.$langs->trans("FeatureNotYetAvailable").'</center>'; + + $module = 'medias'; + include DOL_DOCUMENT_ROOT.'/ecm/tpl/filemanager.tpl.php'; +} + +if ($action == 'editmenu') +{ + print '<!-- Edit Menu -->'."\n"; + print '<div class="center">'.$langs->trans("FeatureNotYetAvailable").'</center>'; +} + +if ($action == 'editsource') +{ + /* + * Editing with source editor + */ + + $contentforedit = ''; + /*$contentforedit.='<style scoped>'."\n"; // "scoped" means "apply to parent element only". Not yet supported by browsers + $contentforedit.=$csscontent; + $contentforedit.='</style>'."\n";*/ + $contentforedit .= $objectpage->content; + + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,'ace',ROWS_5,'90%'); + $doleditor->Create(0, '', false, 'HTML Source', 'php'); +} + +if ($action == 'editcontent') +{ + /* + * Editing with default ckeditor + */ + + $contentforedit = ''; + /*$contentforedit.='<style scoped>'."\n"; // "scoped" means "apply to parent element only". Not yet supported by browsers + $contentforedit.=$csscontent; + $contentforedit.='</style>'."\n";*/ + $contentforedit .= $objectpage->content; + + $contentforedit = preg_replace('/(<img.*src=")(?!http)/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $contentforedit, -1, $nbrep); + + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%'); + $doleditor->Create(0, '', false); +} + +print "</div>\n</form>\n"; + + + +if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') +{ + if ($pageid > 0) + { + // Ouput page under the Dolibarr top menu + $objectpage->fetch($pageid); + $csscontent = @file_get_contents($filecss); + $jscontent = @file_get_contents($filejs); + + $out = '<!-- Page content '.$filetpl.' : Div with (CSS Of website from file + Style/htmlheader of page from database + Page content from database) -->'."\n"; + + $out.='<div id="websitecontentundertopmenu" class="websitecontentundertopmenu">'."\n"; + + + // REPLACEMENT OF LINKS When page called by website editor + + $out.='<style scoped>'."\n"; // "scoped" means "apply to parent element only". Not yet supported by browsers + $out.= '<!-- Include website CSS file -->'."\n"; + $out.=dolWebsiteReplacementOfLinks($object, $csscontent); + $out.= '<!-- Include HTML header from page inline block -->'."\n"; + $out.= $objectpage->htmlheader."\n"; + $out.='</style>'."\n"; + + $out.='<div id="bodywebsite" class="bodywebsite">'."\n"; + + $out.=dolWebsiteReplacementOfLinks($object, $objectpage->content)."\n"; + + $out.='</div>'; + + $out.='</div>'; + + $out.= "\n".'<!-- End page content '.$filetpl.' -->'."\n\n"; + + print $out; + + /*file_put_contents($filetpl, $out); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); + + // Output file on browser + dol_syslog("index.php include $filetpl $filename content-type=$type"); + $original_file_osencoded=dol_osencode($filetpl); // New file name encoded in OS encoding charset + + // This test if file exists should be useless. We keep it to find bug more easily + if (! file_exists($original_file_osencoded)) + { + dol_print_error(0,$langs->trans("ErrorFileDoesNotExists",$original_file)); + exit; + } + + //include_once $original_file_osencoded; + */ + + /*print '<iframe class="websiteiframenoborder centpercent" src="'.DOL_URL_ROOT.'/public/website/index.php?website='.$website.'&pageid='.$pageid.'"/>'; + print '</iframe>';*/ + } + else + { + print '<br><br><div class="center">'.$langs->trans("PreviewOfSiteNotYetAvailable", $website).'</center><br><br><br>'; + print '<div class="center"><div class="logo_setup"></div></div>'; + } +} + + + +llxFooter(); + +$db->close(); + + + + +/** + * Save content of a page on disk + * + * @param string $filealias Full path of filename to generate + * @param Website $object Object website + * @param WebsitePage $objectpage Object websitepage + * @return boolean True if OK + */ +function dolSavePageAlias($filealias, $object, $objectpage) +{ + global $conf; + + // Now create the .tpl file (duplicate code with actions updatesource or updatecontent but we need this to save new header) + dol_syslog("We regenerate the alias page filealias=".$filealias); + + $aliascontent = '<?php'."\n"; + $aliascontent.= "// File generated to wrap the alias page - DO NOT MODIFY - It is just a wrapper to real page\n"; + $aliascontent.= 'global $dolibarr_main_data_root;'."\n"; + $aliascontent.= 'if (empty($dolibarr_main_data_root)) require \'./page'.$objectpage->id.'.tpl.php\'; '; + $aliascontent.= 'else require $dolibarr_main_data_root.\'/website/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n"; + $aliascontent.= '?>'."\n"; + $result = file_put_contents($filealias, $aliascontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filealias, octdec($conf->global->MAIN_UMASK)); + + return ($result?true:false); +} + + +/** + * Save content of a page on disk + * + * @param string $filetpl Full path of filename to generate + * @param Website $object Object website + * @param WebsitePage $objectpage Object websitepage + * @return boolean True if OK + */ +function dolSavePageContent($filetpl, $object, $objectpage) +{ + global $conf; + + // Now create the .tpl file (duplicate code with actions updatesource or updatecontent but we need this to save new header) + dol_syslog("We regenerate the tpl page filetpl=".$filetpl); + + dol_delete_file($filetpl); + + $shortlangcode = ''; + if ($objectpage->lang) $shortlangcode=preg_replace('/[_-].*$/', '', $objectpage->lang); // en_US or en-US -> en + + $tplcontent =''; + $tplcontent.= "<?php // BEGIN PHP\n"; + $tplcontent.= '$websitekey=basename(dirname(__FILE__));'."\n"; + $tplcontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once './master.inc.php'; } // Not already loaded"."\n"; + $tplcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $tplcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $tplcontent.= "ob_start();\n"; + $tplcontent.= "// END PHP ?>\n"; + $tplcontent.= '<html'.($shortlangcode ? ' lang="'.$shortlangcode.'"':'').'>'."\n"; + $tplcontent.= '<head>'."\n"; + $tplcontent.= '<title>'.dol_string_nohtmltag($objectpage->title, 0, 'UTF-8').''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= 'ref.'/htmlheader.html"); ?>'."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= $objectpage->htmlheader."\n"; + $tplcontent.= ''."\n"; + + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= $objectpage->content."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; + + $tplcontent.= '"."\n"; + + //var_dump($filetpl);exit; + $result = file_put_contents($filetpl, $tplcontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); + + return $result; +} + + +/** + * Save content of a page on disk + * + * @param string $filehtmlheader Full path of filename to generate + * @param string $htmlheadercontent Content of file + * @return boolean True if OK + */ +function dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filehtmlheader); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filehtmlheader, $htmlheadercontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filehtmlheader, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors'); + return false; + } + + return true; +} + +/** + * Save content of a page on disk + * + * @param string $filecss Full path of filename to generate + * @param string $csscontent Content of file + * @return boolean True if OK + */ +function dolSaveCssFile($filecss, $csscontent) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filecss); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filecss, $csscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filecss, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filecss, null, 'errors'); + return false; + } + + return true; +} + +/** + * Save content of a page on disk + * + * @param string $filejs Full path of filename to generate + * @param string $jscontent Content of file + * @return boolean True if OK + */ +function dolSaveJsFile($filejs, $jscontent) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filejs); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filejs, $jscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filejs, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filejs, null, 'errors'); + return false; + } + + return true; +} + +/** + * Save content of a page on disk + * + * @param string $filerobot Full path of filename to generate + * @param string $robotcontent Content of file + * @return boolean True if OK + */ +function dolSaveRobotFile($filerobot, $robotcontent) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filerobot); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filerobot, $robotcontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filerobot, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filerobot, null, 'errors'); + return false; + } + + return true; +} + +/** + * Save content of a page on disk + * + * @param string $filehtaccess Full path of filename to generate + * @param string $htaccess Content of file + * @return boolean True if OK + */ +function dolSaveHtaccessFile($filehtaccess, $htaccess) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filehtaccess); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filehtaccess, $htaccess); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filehtaccess, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filehtaccess, null, 'errors'); + return false; + } + + return true; +} + diff --git a/htdocs/website/lib/websiteaccount.lib.php b/htdocs/website/lib/websiteaccount.lib.php new file mode 100644 index 00000000000..95ae071d971 --- /dev/null +++ b/htdocs/website/lib/websiteaccount.lib.php @@ -0,0 +1,85 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/website/lib/websiteaccount.lib.php + * \ingroup website + * \brief Library files with common functions for WebsiteAccount + */ + +/** + * Prepare array of tabs for WebsiteAccount + * + * @param WebsiteAccount $object WebsiteAccount + * @return array Array of tabs + */ +function websiteaccountPrepareHead($object) +{ + global $db, $langs, $conf; + + $langs->load("monmodule@monmodule"); + + $h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath("/website/websiteaccount_card.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Card"); + $head[$h][2] = 'card'; + $h++; + + /*if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) + { + $nbNote = 0; + if(!empty($object->fields['note_private'])) $nbNote++; + if(!empty($object->fields['note_public'])) $nbNote++; + $head[$h][0] = dol_buildpath('/monmodule/websiteaccount_note.php', 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Notes'); + if ($nbNote > 0) $head[$h][1].= ' '.$nbNote.''; + $head[$h][2] = 'note'; + $h++; + }*/ + + /* + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->monmodule->dir_output . "/websiteaccount/" . dol_sanitizeFileName($object->ref); + $nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$')); + $nbLinks=Link::count($db, $object->element, $object->id); + $head[$h][0] = dol_buildpath("/monmodule/websiteaccount_document.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Documents'); + if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' '.($nbFiles+$nbLinks).''; + $head[$h][2] = 'document'; + $h++; + + $head[$h][0] = dol_buildpath("/monmodule/websiteaccount_agenda.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Events"); + $head[$h][2] = 'agenda'; + $h++; + */ + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@monmodule:/monmodule/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@monmodule:/monmodule/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'websiteaccount@website'); + + return $head; +} diff --git a/htdocs/website/websiteaccount_card.php b/htdocs/website/websiteaccount_card.php new file mode 100644 index 00000000000..9918b0b3022 --- /dev/null +++ b/htdocs/website/websiteaccount_card.php @@ -0,0 +1,428 @@ + +* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/Website/websiteaccount_card.php + * \ingroup website + * \brief Page to create/edit/view websiteaccount + */ + +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check anti CSRF attack test +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test done when option MAIN_SECURITY_CSRF_WITH_TOKEN is on. +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) + +// Load Dolibarr environment +$res=0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"); +// Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME +$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; +while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } +if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include(substr($tmp, 0, ($i+1))."/main.inc.php"); +if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"); +// Try main.inc.php using relative path +if (! $res && file_exists("../main.inc.php")) $res=@include("../main.inc.php"); +if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); +if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main.inc.php"); +if (! $res) die("Include of main fails"); + +include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'); +include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); +include_once(DOL_DOCUMENT_ROOT.'/website/class/websiteaccount.class.php'); +include_once(DOL_DOCUMENT_ROOT.'/website/lib/websiteaccount.lib.php'); + +// Load traductions files requiredby by page +$langs->loadLangs(array("website","other")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +// Initialize technical objects +$object=new WebsiteAccount($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->website->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('websiteaccountcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('websiteaccount'); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); + +// Initialize array of search criterias +$search_all=trim(GETPOST("search_all",'alpha')); +$search=array(); +foreach($object->fields as $key => $val) +{ + if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); +} + +if (empty($action) && empty($id) && empty($ref)) $action='view'; + +// Security check - Protection if external user +//if ($user->societe_id > 0) access_forbidden(); +//if ($user->societe_id > 0) $socid = $user->societe_id; +//$result = restrictedArea($user, 'website', $id); + +// fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals + + + +/* + * Actions + */ + +$parameters=array(); +$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)) +{ + $error=0; + + $permissiontoadd = $user->rights->website->write; + $permissiontodelete = $user->rights->website->delete; + $backurlforlist = dol_buildpath('/website/websiteaccount_list.php',1); + + // Actions cancel, add, update or delete + include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; + + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + + // Actions to send emails + $trigger_name='MYOBJECT_SENTBYMAIL'; + $autocopy='MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; + $trackid='websiteaccount'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; +} + + +/* + * View + */ + +$form=new Form($db); +$formfile=new FormFile($db); + +llxHeader('','WebsiteAccount',''); + +// Example : Adding jquery code +print ''; + + +// Part to create +if ($action == 'create') +{ + print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("WebsiteAccount"))); + + print '
    '; + print ''; + print ''; + print ''; + + dol_fiche_head(); + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + + print '
    '."\n"; + + dol_fiche_end(); + + print '
    '; + print ''; + print '  '; + print ''; // Cancel for create does not post form if we don't know the backtopage + print '
    '; + + print '
    '; +} + +// Part to edit record +if (($id || $ref) && $action == 'edit') +{ + print load_fiche_titre($langs->trans("WebsiteAccount")); + + print '
    '; + print ''; + print ''; + print ''; + + dol_fiche_head(); + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + + print '
    '; + + dol_fiche_end(); + + print '
    '; + print '   '; + print '
    '; + + print '
    '; +} + +// Part to show record +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) +{ + if ($object->fk_soc >0 && empty($socid)) $socid = $object->fk_soc; + + $res = $object->fetch_optionals($object->id, $extralabels); + + $head = websiteaccountPrepareHead($object); + dol_fiche_head($head, 'card', $langs->trans("WebsiteAccount"), -1, 'websiteaccount@website'); + + $formconfirm = ''; + + // Confirmation to delete + if ($action == 'delete') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteWebsiteAccount'), $langs->trans('ConfirmDeleteWebsiteAccount'), 'confirm_delete', '', 0, 1); + } + + // Confirmation of action xxxx + if ($action == 'xxx') + { + $formquestion=array(); + /* + $formquestion = array( + // 'text' => $langs->trans("ConfirmClone"), + // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), + // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), + // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1))); + }*/ + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + } + + if (! $formconfirm) { + $parameters = array('lineid' => $lineid); + $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $formconfirm.=$hookmanager->resPrint; + elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint; + } + + // Print form confirm + print $formconfirm; + + + // Object card + // ------------------------------------------------------------ + $linkback=''; + if ($socid) $linkback = '
    ' . $langs->trans("BackToListOfThirdParty") . ''; + if ($fk_website) $linkback = '' . $langs->trans("BackToList") . ''; + + $morehtmlref='
    '; + /* + // Ref bis + $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->website->creer, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->website->creer, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->website->creer) + { + if ($action != 'classify') + { + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + */ + $morehtmlref.='
    '; + + if ($socid > 0) $object->next_prev_filter = 'te.fk_soc = '.$socid; + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'rowid', $morehtmlref); + + + print '
    '; + print '
    '; + print '
    '; + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print '

    '; + + dol_fiche_end(); + + + // Buttons for actions + if ($action != 'presend' && $action != 'editline') { + print '
    '."\n"; + $parameters=array(); + $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + if (empty($reshook)) + { + // Send + print ''."\n"; + + if ($user->rights->website->write) + { + print ''."\n"; + } + + /* + if ($user->rights->sellyoursaas->create) + { + if ($object->status == 1) + { + print ''."\n"; + } + else + { + print ''."\n"; + } + } + */ + + if ($user->rights->website->delete) + { + print ''."\n"; + } + } + print '
    '."\n"; + } + + + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } + + if ($action != 'presend') + { + print '
    '; + print ''; // ancre + + // Documents + /*$comref = dol_sanitizeFileName($object->ref); + $relativepath = $comref . '/' . $comref . '.pdf'; + $filedir = $conf->website->dir_output . '/' . $comref; + $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $genallowed = $user->rights->website->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->website->create; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('website', $comref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + */ + + // Show links to link elements + /*$linktoelem = $form->showLinkToObjectBlock($object, null, array('websiteaccount')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + */ + + print '
    '; + + $MAXEVENT = 10; + + // List of actions on element + /* + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT); + */ + + print '
    '; + } + + // Presend form + $modelmail='websiteaccount'; + $defaulttopic='Information'; + $diroutput = $conf->website->dir_output; + $trackid = 'websiteaccount'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; +} + + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/websites/frametop.php b/htdocs/websites/frametop.php deleted file mode 100644 index 7cebf239e28..00000000000 --- a/htdocs/websites/frametop.php +++ /dev/null @@ -1,41 +0,0 @@ - - * Copyright (C) 2010 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/externalsite/frametop.php - * \ingroup externalsite - * \brief Top frame to show external web application - */ - -require ("../main.inc.php"); -//require_once (DOL_DOCUMENT_ROOT."/websites/class/website.class.php"); - -$langs->load("externalsite"); - -top_htmlhead("",""); - -print '' . "\n"; - -top_menu("","","_top"); - -print ''; - -/* -$website = new Website($db); -$listofwebsites = $website->fetchAll(); -*/ diff --git a/htdocs/websites/index.php b/htdocs/websites/index.php deleted file mode 100644 index 9fbd6e6a4e0..00000000000 --- a/htdocs/websites/index.php +++ /dev/null @@ -1,1193 +0,0 @@ - - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/website/index.php - * \ingroup website - * \brief Page to website view/edit - */ - -define('NOSCANPOSTFORINJECTION',1); -define('NOSTYLECHECK',1); - - -/** - * Show HTML header HTML + BODY + Top menu + left menu + DIV - * - * @param string $head Optionnal head lines - * @param string $title HTML title - * @param string $help_url Url links to help page - * Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage - * For other external page: http://server/url - * @param string $target Target to use on links - * @param int $disablejs More content into html header - * @param int $disablehead More content into html header - * @param array $arrayofjs Array of complementary js files - * @param array $arrayofcss Array of complementary css files - * @param string $morequerystring Query string to add to the link "print" to get same parameters (set this only if autodetect fails) - * @return void - */ -function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='') -{ - global $conf; - - // html header - top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); - - print ''; - - // top menu and left menu area - if (empty($conf->dol_hide_topmenu)) - { - top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url); - } - if (empty($conf->dol_hide_leftmenu)) - { - left_menu('', $help_url, '', '', 1, $title, 1); - } - - // main area - //main_area($title); - print ''."\n".'
    '."\n"; -} - - - -require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/websites/class/website.class.php'; -require_once DOL_DOCUMENT_ROOT.'/websites/class/websitepage.class.php'; - -$langs->load("admin"); -$langs->load("other"); -$langs->load("website"); - -if (! $user->admin) accessforbidden(); - -if (! ((GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))) -{ - $conf->dol_hide_leftmenu = 1; // Force hide of left menu. -} - -$error=0; -$website=GETPOST('website', 'alpha'); -$page=GETPOST('page', 'alpha'); -$pageid=GETPOST('pageid', 'int'); -$action=GETPOST('action','alpha'); - -if (GETPOST('delete')) { $action='delete'; } -if (GETPOST('preview')) $action='preview'; -if (GETPOST('create')) { $action='create'; } -if (GETPOST('editmedia')) { $action='editmedia'; } -if (GETPOST('editcss')) { $action='editcss'; } -if (GETPOST('editmenu')) { $action='editmenu'; } -if (GETPOST('setashome')) { $action='setashome'; } -if (GETPOST('editmeta')) { $action='editmeta'; } -if (GETPOST('editsource')) { $action='editsource'; } -if (GETPOST('editcontent')) { $action='editcontent'; } - -if (empty($action)) $action='preview'; - -$object=new Website($db); -$objectpage=new WebsitePage($db); - -$object->fetchAll(); // Init $object->records - -// If website not defined, we take first found -if (empty($website)) -{ - foreach($object->records as $key => $valwebsite) - { - $website=$valwebsite->ref; - break; - } -} -if ($website) -{ - $res = $object->fetch(0, $website); -} - -if ($pageid < 0) $pageid = 0; -if ($pageid > 0 && $action != 'add') -{ - $res = $objectpage->fetch($pageid); -} - -global $dolibarr_main_data_root; -$pathofwebsite=$dolibarr_main_data_root.'/websites/'.$website; -$filehtmlheader=$pathofwebsite.'/header.html'; -$filecss=$pathofwebsite.'/styles.css.php'; -$filetpl=$pathofwebsite.'/page'.$pageid.'.tpl.php'; -$fileindex=$pathofwebsite.'/index.php'; - -// Define $urlwithroot -$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); -$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 - - - -/* - * Actions - */ - -if (GETPOST('refreshsite')) $pageid=0; // If we change the site, we reset the pageid. -if (GETPOST('refreshpage')) $action='preview'; - - -// Add page -if ($action == 'add') -{ - $db->begin(); - - $objectpage->fk_website = $object->id; - - $objectpage->title = GETPOST('WEBSITE_TITLE'); - $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); - $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); - $objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); - - if (empty($objectpage->pageurl)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); - $error++; - $action='create'; - } - if (empty($objectpage->title)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_TITLE")), null, 'errors'); - $error++; - $action='create'; - } - - if (! $error) - { - $res = $objectpage->create($user); - if ($res <= 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } - } - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); - $action=''; - } - else - { - $db->rollback(); - } - - if (! $error) - { - $action = 'preview'; - $id = $objectpage->id; - } -} - -// Update page -if ($action == 'delete') -{ - $db->begin(); - - $res = $object->fetch(0, $website); - - $res = $objectpage->fetch($pageid, $object->fk_website); - - if ($res > 0) - { - $res = $objectpage->delete($user); - if (! $res > 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } - - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); - - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website); - exit; - } - else - { - $db->rollback(); - } - } - else - { - dol_print_error($db); - } -} - -// Update css -if ($action == 'updatecss') -{ - $res = $object->fetch(0, $website); - - // Html header file - $htmlheadercontent = ''."\n"; - $htmlheadercontent.= ''."\n"; - $htmlheadercontent.= ''."\n"; - $htmlheadercontent.= GETPOST('WEBSITE_HTML_HEADER'); - - dol_syslog("Save file css into ".$filehtmlheader); - - dol_mkdir($pathofwebsite); - $result = file_put_contents($filehtmlheader, $htmlheadercontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filehtmlheader, octdec($conf->global->MAIN_UMASK)); - - if (! $result) - { - $error++; - setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors'); - } - - // Css file - $csscontent = ''."\n"; - $csscontent.= ''."\n"; - $csscontent.= '"."\n"; - $csscontent.= ''."\n"; - $csscontent.= GETPOST('WEBSITE_CSS_INLINE'); - - dol_syslog("Save file css into ".$filecss); - - dol_mkdir($pathofwebsite); - $result = file_put_contents($filecss, $csscontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filecss, octdec($conf->global->MAIN_UMASK)); - - if (! $result) - { - $error++; - setEventMessages('Failed to write file '.$filecss, null, 'errors'); - } - - - if (! $error) - { - setEventMessages($langs->trans("Saved"), null, 'mesgs'); - } - - $action='preview'; -} - -// Update page -if ($action == 'setashome') -{ - $db->begin(); - $object->fetch(0, $website); - - $object->fk_default_home = $pageid; - $res = $object->update($user); - if (! $res > 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } - - if (! $error) - { - $db->commit(); - - // Generate the index.php page to be the home page - //------------------------------------------------- - dol_mkdir($pathofwebsite); - dol_delete_file($fileindex); - - $indexcontent = ''."\n"; - $result = file_put_contents($fileindex, $indexcontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($fileindex, octdec($conf->global->MAIN_UMASK)); - - if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); - else setEventMessages('Failed to write file '.$fileindex, null, 'errors'); - - $action='preview'; - } - else - { - $db->rollback(); - } -} - -// Update page (meta) -if ($action == 'updatemeta') -{ - $db->begin(); - $object->fetch(0, $website); - - $objectpage->fk_website = $object->id; - - $res = $objectpage->fetch($pageid, $object->fk_website); - if ($res > 0) - { - $objectpage->old_object = clone $objectpage; - - $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); - $objectpage->title = GETPOST('WEBSITE_TITLE'); - $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); - $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS'); - - $res = $objectpage->update($user); - if (! $res > 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } - - if (! $error) - { - $db->commit(); - - $filemaster=$pathofwebsite.'/master.inc.php'; - $fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; - $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; - - dol_mkdir($pathofwebsite); - - - // Now generate the master.inc.php page - dol_syslog("We regenerate the master file (because we update meta)"); - dol_delete_file($filemaster); - - $mastercontent = ''."\n"; - $result = file_put_contents($filemaster, $mastercontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); - - if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); - - - // Now generate the alias.php page - if (! empty($fileoldalias)) - { - dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); - dol_delete_file($fileoldalias); - } - - $aliascontent = 'id.".tpl.php';\n"; - $aliascontent.= '?>'."\n"; - $result = file_put_contents($filealias, $aliascontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filealias, octdec($conf->global->MAIN_UMASK)); - - if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); - - - // Now create the .tpl file (duplicate code with actions updatecontent but we need this to save new header) - dol_syslog("We regenerate the tpl page filetpl=".$filetpl); - - dol_delete_file($filetpl); - - $tplcontent =''; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= '
    '."\n"; - $tplcontent.= ''.dol_escape_htmltag($objectpage->title).''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= 'ref.'/header.html"); ?>'."\n"; - $tplcontent.= '
    '."\n"; - - $tplcontent.= ''."\n"; - $tplcontent.= $objectpage->content."\n"; - $tplcontent.= ''."\n"; - //var_dump($filetpl);exit; - $result = file_put_contents($filetpl, $tplcontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); - - if ($result) - { - setEventMessages($langs->trans("Saved"), null, 'mesgs'); - //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); - //exit; - } - else setEventMessages('Failed to write file '.$filetpl, null, 'errors'); - - $action='preview'; - } - else - { - $db->rollback(); - } - } - else - { - dol_print_error($db, 'Page not found'); - } -} - -// Update page -if ($action == 'updatecontent' || GETPOST('refreshsite') || GETPOST('refreshpage') || GETPOST('preview')) -{ - $object->fetch(0, $website); - - // Check symlink to medias and restore it if ko - $pathtomedias=DOL_DATA_ROOT.'/medias'; - $pathtomediasinwebsite=$pathofwebsite.'/medias'; - if (! is_link(dol_osencode($pathtomediasinwebsite))) - { - dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); - dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists - $result = symlink($pathtomedias, $pathtomediasinwebsite); - } - - /*if (GETPOST('savevirtualhost') && $object->virtualhost != GETPOST('previewsite')) - { - $object->virtualhost = GETPOST('previewsite', 'alpha'); - $object->update($user); - }*/ - - $objectpage->fk_website = $object->id; - - if ($pageid > 0) - { - $res = $objectpage->fetch($pageid); - } - else - { - $res=0; - if ($object->fk_default_home > 0) - { - $res = $objectpage->fetch($object->fk_default_home); - } - if (! ($res > 0)) - { - $res = $objectpage->fetch(0, $object->id); - } - } - - if ($res > 0) - { - if ($action == 'updatecontent') - { - $db->begin(); - - $objectpage->content = GETPOST('PAGE_CONTENT'); - - // Clean data. We remove all the head section. - $objectpage->content = preg_replace('//s', '', $objectpage->content); - /* $objectpage->content = preg_replace('//s', '', $objectpage->content); */ - - $res = $objectpage->update($user); - if ($res < 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } - - if (! $error) - { - $db->commit(); - - $filemaster=$pathofwebsite.'/master.inc.php'; - //$fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; - $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; - - dol_mkdir($pathofwebsite); - - - // Now generate the master.inc.php page - dol_syslog("We regenerate the master file"); - dol_delete_file($filemaster); - - $mastercontent = ''."\n"; - $result = file_put_contents($filemaster, $mastercontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); - - if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); - - - // Now generate the alias.php page - if (! empty($fileoldalias)) - { - dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); - dol_delete_file($fileoldalias); - } - - $aliascontent = 'id.".tpl.php';\n"; - $aliascontent.= '?>'."\n"; - $result = file_put_contents($filealias, $aliascontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filealias, octdec($conf->global->MAIN_UMASK)); - - if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); - - - // Now create the .tpl file with code to be able to make dynamic changes - dol_delete_file($filetpl); - - $tplcontent =''; - $tplcontent.= "\n"; - $tplcontent.= ''."\n"; - $tplcontent.= '
    '."\n"; - $tplcontent.= ''.dol_escape_htmltag($objectpage->title).''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; - $tplcontent.= 'ref.'/header.html"); ?>'."\n"; - $tplcontent.= '
    '."\n"; - - $tplcontent.= ''."\n"; - $tplcontent.= $objectpage->content."\n"; - $tplcontent.= ''."\n"; - - $tplcontent.= '"."\n"; - - //var_dump($filetpl);exit; - $result = file_put_contents($filetpl, $tplcontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); - - if ($result) - { - setEventMessages($langs->trans("Saved"), null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); - exit; - } - else - { - setEventMessages('Failed to write file '.$filetpl, null, 'errors'); - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); - exit; - } - } - else - { - $db->rollback(); - } - } - else - { - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); - exit; - } - } - else - { - setEventMessages($langs->trans("NoPageYet"), null, 'warnings'); - } -} - - - -/* - * View - */ - -$form = new Form($db); - -$help_url=''; - -llxHeader('', $langs->trans("WebsiteSetup"), $help_url); - -print "\n".'
    '; -print ''; -if ($action == 'create') -{ - print ''; -} -if ($action == 'editcss') -{ - print ''; -} -if ($action == 'editmenu') -{ - print ''; -} -if ($action == 'setashome') -{ - print ''; -} -if ($action == 'editmeta') -{ - print ''; -} -if ($action == 'editsource') -{ - print ''; -} -if ($action == 'editcontent') -{ - print ''; -} -if ($action == 'edit') -{ - print ''; -} - - -// Add a margin under toolbar ? -$style=''; -if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource') $style=' margin-bottom: 5px;'; - -//var_dump($objectpage);exit; -print '
    '; - -if (count($object->records) > 0) -{ - // ***** Part for web sites - - print '
    '; - print $langs->trans("Website").': '; - print '
    '; - - // List of websites - print '
    '; - $out=''; - $out.=''; - $out.=ajax_combobox('website'); - print $out; - print ''; - - if ($website) - { - $virtualurl=''; - $dataroot=DOL_DATA_ROOT.'/websites/'.$website; - if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; - } - - if ($website && $action == 'preview') - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - - print '   '; - - //print ''; - print ''; - print ''; - print ''; - } - - print '
    '; - - // Button for websites - print '
    '; - - if ($action == 'preview') - { - print '
    '; - print ''; - //print ''; - $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); - print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helpvirtualhost'); - print '
    '; - - $urlext=$virtualurl; - $urlint=$urlwithroot.'/public/websites/index.php?website='.$website; - print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - - print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint, $dataroot), 1, 'preview'); - print ''; - } - - if (in_array($action, array('editcss','editmenu','create'))) - { - if ($action != 'preview') print ''; - if (preg_match('/^create/',$action)) print ''; - if (preg_match('/^edit/',$action)) print ''; - } - - print '
    '; - - - // ***** Part for pages - - if ($website) - { - print '
    '; - - $array=$objectpage->fetchAll($object->id); - if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); - $atleastonepage=(is_array($array) && count($array) > 0); - - print '
    '; - print '
    '; - print $langs->trans("Page").': '; - print '
    '; - print '
    '; - - if ($action != 'add') - { - $out=''; - $out.=''; - $out.=ajax_combobox('pageid'); - print $out; - } - else - { - print $langs->trans("New"); - } - - print ''; - - if ($action == 'preview') - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - - if ($pageid > 0) - { - print '   '; - - if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; - else print ''; - print ''; - print ''; - print ''; - //print ''.dol_escape_htmltag($langs->trans("EditPageMeta")).''; - //print ''.dol_escape_htmltag($langs->trans("EditPageContent")).''; - print ''; - } - } - - print '
    '; - - print '
    '; - - if ($website && $pageid > 0 && $action == 'preview') - { - $websitepage = new WebSitePage($db); - $websitepage->fetch($pageid); - - $realpage=$urlwithroot.'/public/websites/index.php?website='.$website.'&page='.$pageid; - $pagealias = $websitepage->pageurl; - - print '
    '; - print ''; - $htmltext=$langs->trans("PageNameAliasHelp", $langs->transnoentitiesnoconv("EditPageMeta")); - print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helppagealias'); - print '
    '; - - if (! empty($object->virtualhost)) - { - $urlext=$virtualurl.'/'.$pagealias.'.php'; - print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - } - else - { - print ''; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - } - - print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot), 1, 'preview'); - print ''; // View page in new Tab - //print ''; - - // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext - } - if (! in_array($action, array('editcss','editmenu','create'))) - { - if ($action != 'preview') print ''; - if (preg_match('/^create/',$action)) print ''; - if (preg_match('/^edit/',$action)) print ''; - } - - print '
    '; - - print '
    '; - if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) - { - $htmltext=$langs->transnoentitiesnoconv("YouCanEditHtmlSource"); - print $form->textwithpicto($langs->trans("SyntaxHelp"), $htmltext, 1, 'help', 'inline-block', 0, 2, 'tooltipsubstitution'); - } - print '
    '; - - - - if ($action == 'preview') - { - // Adding jquery code to change on the fly url of preview ext - if (! empty($conf->use_javascript_ajax)) - { - print ''; - } - } - } -} -else -{ - print '
    '; - $langs->load("errors"); - print $langs->trans("ErrorModuleSetupNotComplete"); - print '
    '; - $action=''; -} - - -print '
    '; - -$head = array(); - - -/* - * Edit mode - */ - -if ($action == 'editcss') -{ - print '
    '; - - print '
    '; - - $htmlheader = @file_get_contents($filehtmlheader); - // Clean the php css file to remove php code and get only html part - $htmlheader = preg_replace('//s', '', $htmlheader); - - - $csscontent = @file_get_contents($filecss); - // Clean the php css file to remove php code and get only css part - $csscontent = preg_replace('//s', '', $csscontent); - - dol_fiche_head(); - - print ''."\n"; - print ''; - - print ''; - - print ''; - - print ''; - - /*print '';*/ - - print '
    '; - print $langs->trans('WebSite'); - print ''; - print $website; - print '
    '; - print $langs->trans('WEBSITE_CSS_INLINE'); - print ''; - print ''; - print '
    '; - print $langs->trans('WEBSITE_HTML_HEADER'); - print ''; - print ''; - print '
    '; - print $langs->trans('WEBSITE_CSS_URL'); - print ''; - print ''; - print '
    '; - - dol_fiche_end(); - - print '
    '; - - print '
    '; -} - -if ($action == 'editmeta' || $action == 'create') -{ - print '
    '; - - print '
    '; - - dol_fiche_head(); - - print ''."\n"; - print ''; - - if ($action != 'create') - { - print ''; - $pageurl=dol_escape_htmltag($objectpage->pageurl); - $pagetitle=dol_escape_htmltag($objectpage->title); - $pagedescription=dol_escape_htmltag($objectpage->description); - $pagekeywords=dol_escape_htmltag($objectpage->keywords); - } - if (GETPOST('WEBSITE_PAGENAME')) $pageurl=GETPOST('WEBSITE_PAGENAME'); - if (GETPOST('WEBSITE_TITLE')) $pagetitle=GETPOST('WEBSITE_TITLE'); - if (GETPOST('WEBSITE_DESCRIPTION')) $pagedescription=GETPOST('WEBSITE_DESCRIPTION'); - if (GETPOST('WEBSITE_KEYWORDS')) $pagekeywords=GETPOST('WEBSITE_KEYWORDS'); - - print ''; - - print ''; - - print ''; - - print ''; - - print '
    '; - print $langs->trans('WEBSITE_PAGEURL'); - print ''; - print '/public/websites/index.php?website='.urlencode($website).'&pageid='.urlencode($pageid); - print '
    '; - print $langs->trans('WEBSITE_PAGENAME'); - print ''; - print ''; - print '
    '; - print $langs->trans('WEBSITE_TITLE'); - print ''; - print ''; - print '
    '; - print $langs->trans('WEBSITE_DESCRIPTION'); - print ''; - print ''; - print '
    '; - print $langs->trans('WEBSITE_KEYWORDS'); - print ''; - print ''; - print '
    '; - - dol_fiche_end(); - - print '
    '; - - print '
    '; -} - -if ($action == 'editmedia') -{ - print ''."\n"; - print '
    '.$langs->trans("FeatureNotYetAvailable").''; -} - -if ($action == 'editmenu') -{ - print ''."\n"; - print '
    '.$langs->trans("FeatureNotYetAvailable").''; -} - -if ($action == 'editsource') -{ - /* - * Editing global variables not related to a specific theme - */ - - $csscontent = @file_get_contents($filecss); - - $contentforedit = ''; - /*$contentforedit.=''."\n";*/ - $contentforedit .= $objectpage->content; - - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%'); - $doleditor->Create(0, '', false); -} - -if ($action == 'editcontent') -{ - /* - * Editing global variables not related to a specific theme - */ - - $csscontent = @file_get_contents($filecss); - - $contentforedit = ''; - /*$contentforedit.=''."\n";*/ - $contentforedit .= $objectpage->content; - - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%'); - $doleditor->Create(0, '', false); -} - -print "
    \n\n"; - - - -if ($action == 'preview') -{ - if ($pageid > 0) - { - $objectpage->fetch($pageid); - - $out = ''."\n"; - - $out.='
    '."\n"; - - $csscontent = @file_get_contents($filecss); - - $out.=''."\n"; - - // Replace php code - $content = preg_replace('/<\?php.*\?>/ims', '...php...', $objectpage->content); - - $out.=$content."\n"; - - $out.='
    '; - - $out.= "\n".''."\n\n"; - - print $out; - - /*file_put_contents($filetpl, $out); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); - - // Output file on browser - dol_syslog("index.php include $filetpl $filename content-type=$type"); - $original_file_osencoded=dol_osencode($filetpl); // New file name encoded in OS encoding charset - - // This test if file exists should be useless. We keep it to find bug more easily - if (! file_exists($original_file_osencoded)) - { - dol_print_error(0,$langs->trans("ErrorFileDoesNotExists",$original_file)); - exit; - } - - //include_once $original_file_osencoded; - */ - - /*print '';*/ - } - else - { - print '

    '.$langs->trans("PreviewOfSiteNotYetAvailable", $website).'


    '; - print '
    '; - } -} - - - -llxFooter(); - -$db->close(); diff --git a/scripts/accountancy/export-thirdpartyaccount.php b/scripts/accountancy/export-thirdpartyaccount.php index cfc43113eda..e5ba6bad702 100755 --- a/scripts/accountancy/export-thirdpartyaccount.php +++ b/scripts/accountancy/export-thirdpartyaccount.php @@ -104,7 +104,7 @@ $exportlink = ''; $nom = $langs->trans("ReportThirdParty"); $period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1); $description = $langs->trans("DescThirdPartyReport"); -$builddate = time(); +$builddate=dol_now(); $moreparam=array('action' => ''); report_header($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, $moreparam); diff --git a/scripts/emailings/mailing-send.php b/scripts/emailings/mailing-send.php index 6465e765cfe..a56c2be2055 100755 --- a/scripts/emailings/mailing-send.php +++ b/scripts/emailings/mailing-send.php @@ -32,7 +32,7 @@ $path=dirname(__FILE__).'/'; // Test if batch mode if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit(-1); } @@ -64,7 +64,7 @@ print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; if ($conf->global->MAILING_LIMIT_SENDBYCLI == '-1') { - + } $user = new User($db); @@ -98,7 +98,7 @@ if ($resql) $emailing = new Mailing($db); $emailing->fetch($obj->rowid); - + $id = $emailing->id; $subject = $emailing->sujet; $message = $emailing->body; @@ -116,11 +116,11 @@ if ($resql) $sql2 = "SELECT mc.rowid, mc.lastname as lastname, mc.firstname as firstname, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type, mc.tag"; $sql2.= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; $sql2.= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$id; - if ($conf->global->MAILING_LIMIT_SENDBYCLI > 0) - { - $sql2.= " LIMIT ".$conf->global->MAILING_LIMIT_SENDBYCLI; - } - + if ($conf->global->MAILING_LIMIT_SENDBYCLI > 0) + { + $sql2.= " LIMIT ".$conf->global->MAILING_LIMIT_SENDBYCLI; + } + $resql2=$db->query($sql2); if ($resql2) { @@ -145,6 +145,7 @@ if ($resql) $i = 0; while ($i < $num2) { + // Here code is common with same loop ino card.php $res=1; $now=dol_now(); @@ -156,33 +157,70 @@ if ($resql) // Make subtsitutions on topic and body $other=explode(';',$obj2->other); $tmpfield=explode('=',$other[0],2); $other1=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=',$other[1],2); $other2=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=',$other[2],2); $other3=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=',$other[3],2); $other4=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=',$other[4],2); $other5=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''); + $tmpfield=explode('=',$other[1],2); $other2=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $tmpfield=explode('=',$other[2],2); $other3=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $tmpfield=explode('=',$other[3],2); $other4=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $tmpfield=explode('=',$other[4],2); $other5=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''); + + $object = null; // Not defined with mass emailing + $parameters=array('mode'=>'emailing'); + $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount'), $object); // Note: On mass emailing, this is null because we don't know object // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) - $substitutionarray=array( - '__ID__' => $obj2->source_id, - '__EMAIL__' => $obj2->email, - '__LASTNAME__' => $obj2->lastname, - '__FIRSTNAME__' => $obj2->firstname, - '__MAILTOEMAIL__' => ''.$obj2->email.'', - '__OTHER1__' => $other1, - '__OTHER2__' => $other2, - '__OTHER3__' => $other3, - '__OTHER4__' => $other4, - '__OTHER5__' => $other5, - '__SIGNATURE__' => $signature, // Signature is empty when ran from command line or taken from user in parameter) - '__CHECK_READ__' => '', - '__UNSUBSCRIBE__' => ''.$langs->trans("MailUnsubcribe").'' - ); + $substitutionarray['__ID__'] = $obj->source_id; + $substitutionarray['__EMAIL__'] = $obj->email; + $substitutionarray['__LASTNAME__'] = $obj->lastname; + $substitutionarray['__FIRSTNAME__'] = $obj->firstname; + $substitutionarray['__MAILTOEMAIL__'] = ''.$obj->email.''; + $substitutionarray['__OTHER1__'] = $other1; + $substitutionarray['__OTHER2__'] = $other2; + $substitutionarray['__OTHER3__'] = $other3; + $substitutionarray['__OTHER4__'] = $other4; + $substitutionarray['__OTHER5__'] = $other5; + $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) + $substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility + $substitutionarray['__CHECK_READ__'] = ''; + $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").''; + + $onlinepaymentenabled = 0; + if (! empty($conf->paypal->enabled)) $onlinepaymentenabled++; + if (! empty($conf->paybox->enabled)) $onlinepaymentenabled++; + if (! empty($conf->stripe->enabled)) $onlinepaymentenabled++; + if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN)) + { + $substitutionarray['__SECUREKEYPAYMENT__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) + { + $substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + } + else + { + $substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'order' . $obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2); + } + } + /* For backward compatibility */ if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN)) { $substitutionarray['__SECUREKEYPAYPAL__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_MEMBER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); else $substitutionarray['__SECUREKEYPAYPAL_MEMBER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2); + + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_ORDER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + else $substitutionarray['__SECUREKEYPAYPAL_ORDER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'order' . $obj->source_id, 2); + + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_INVOICE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + else $substitutionarray['__SECUREKEYPAYPAL_INVOICE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2); + + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2); } complete_substitutions_array($substitutionarray,$langs); @@ -194,22 +232,22 @@ if ($resql) // Fabrication du mail $trackid='emailing-'.$obj2->source_type.$obj2->source_id; $mail = new CMailFile( - $newsubject, - $sendto, - $from, - $newmessage, - array(), - array(), - array(), - '', - '', - 0, - $msgishtml, - $errorsto, - '', - $trackid, - '', - 'emailing' + $newsubject, + $sendto, + $from, + $newmessage, + array(), + array(), + array(), + '', + '', + 0, + $msgishtml, + $errorsto, + '', + $trackid, + '', + 'emailing' ); if ($mail->error) @@ -252,7 +290,7 @@ if ($resql) if ($result < 0) $error++; // End call triggers */ - + $sqlok ="UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; $sqlok.=" SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj2->rowid; $resqlok=$db->query($sqlok); @@ -276,7 +314,7 @@ if ($resql) $error++; } - //Update status communication of contact prospect + //Update status communication of contact prospect $sqlx = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.rowid=".$obj2->rowid." AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)"; dol_syslog("card.php: set prospect contact status", LOG_DEBUG); @@ -288,9 +326,9 @@ if ($resql) } } - if (!empty($conf->global->MAILING_DELAY)) { - sleep($conf->global->MAILING_DELAY); - } + if (!empty($conf->global->MAILING_DELAY)) { + sleep($conf->global->MAILING_DELAY); + } } } diff --git a/scripts/invoices/rebuild_merge_pdf.php b/scripts/invoices/rebuild_merge_pdf.php index 6727dc5cab7..30782d3b913 100755 --- a/scripts/invoices/rebuild_merge_pdf.php +++ b/scripts/invoices/rebuild_merge_pdf.php @@ -289,7 +289,7 @@ function usage() print "To exclude deposit invoices, use filter=nodeposit\n"; print "To exclude some thirdparties, use filter=excludethirdparties id1,id2...\n"; print "To limit to some thirdparties, use filter=onlythirdparties id1,id2...\n"; - print "To regenerate existing PDF, use regenerate=crabe\n"; + print "To regenerate existing PDF, use regenerate=templatename\n"; print "To generate invoices in a language, use lang=xx_XX\n"; print "To set prefix of generated file name, use prefix=myfileprefix\n"; print "\n"; diff --git a/scripts/members/sync_members_types_dolibarr2ldap.php b/scripts/members/sync_members_types_dolibarr2ldap.php new file mode 100755 index 00000000000..939a98c8728 --- /dev/null +++ b/scripts/members/sync_members_types_dolibarr2ldap.php @@ -0,0 +1,131 @@ +#!/usr/bin/env php + + * Copyright (C) 2006 Laurent Destailleur + * Copyright (C) 2017 Regis Houssin + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file scripts/user/sync_members_types_dolibarr2ldap.php + * \ingroup ldap core + * \brief Script de mise a jour des types de membres dans LDAP depuis base Dolibarr + */ + +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path=dirname(__FILE__).'/'; + +// Test if batch mode +if (substr($sapi_type, 0, 3) == 'cgi') { + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit(-1); +} + +if (! isset($argv[1]) || ! $argv[1]) { + print "Usage: ".$script_file." now\n"; + exit(-1); +} +$now=$argv[1]; + +require_once($path."../../htdocs/master.inc.php"); +require_once(DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"); +require_once(DOL_DOCUMENT_ROOT."/adherents/class/adherent_type.class.php"); + +// Global variables +$version=DOL_VERSION; +$error=0; + + +/* + * Main + */ + +@set_time_limit(0); +print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; +dol_syslog($script_file." launched with arg ".join(',',$argv)); + +/* +if (! $conf->global->LDAP_SYNCHRO_ACTIVE) +{ + print $langs->trans("LDAPSynchronizationNotSetupInDolibarr"); + exit(-1); +} +*/ + +$sql = "SELECT rowid"; +$sql .= " FROM ".MAIN_DB_PREFIX."adherent_type"; + +$resql = $db->query($sql); +if ($resql) +{ + $num = $db->num_rows($resql); + $i = 0; + + $ldap=new Ldap(); + $result=$ldap->connect_bind(); + + if ($result > 0) + { + while ($i < $num) + { + $ldap->error=""; + + $obj = $db->fetch_object($resql); + + $membertype = new AdherentType($db); + $membertype->id = $obj->rowid; + $membertype->fetch($membertype->id); + + print $langs->trans("UpdateMemberType")." rowid=".$membertype->id." ".$membertype-label; + + $oldobject=$membertype; + + $oldinfo=$membertype->_load_ldap_info(); + $olddn=$membertype->_load_ldap_dn($oldinfo); + + $info=$membertype->_load_ldap_info(); + $dn=$membertype->_load_ldap_dn($info); + + $result=$ldap->add($dn,$info,$user); // Wil fail if already exists + $result=$ldap->update($dn,$info,$user,$olddn); + if ($result > 0) + { + print " - ".$langs->trans("OK"); + } + else + { + $error++; + print " - ".$langs->trans("KO").' - '.$ldap->error; + } + print "\n"; + + $i++; + } + + $ldap->unbind(); + $ldap->close(); + } + else { + print $ldap->error; + } +} +else +{ + dol_print_error($db); +} + +exit($error); diff --git a/scripts/members/sync_members_types_ldap2dolibarr.php b/scripts/members/sync_members_types_ldap2dolibarr.php new file mode 100755 index 00000000000..55d5606cd30 --- /dev/null +++ b/scripts/members/sync_members_types_ldap2dolibarr.php @@ -0,0 +1,221 @@ +#!/usr/bin/env php + + * Copyright (C) 2006-2012 Laurent Destailleur + * Copyright (C) 2013 Maxime Kohlhaas + * Copyright (C) 2017 Regis Houssin + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file scripts/user/sync_members_types_ldap2dolibarr.php + * \ingroup ldap member + * \brief Script to update members types into Dolibarr from LDAP + */ + +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path=dirname(__FILE__).'/'; + +// Test if batch mode +if (substr($sapi_type, 0, 3) == 'cgi') { + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit(-1); +} + +require_once($path."../../htdocs/master.inc.php"); +require_once(DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"); +require_once(DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"); +require_once(DOL_DOCUMENT_ROOT."/adherents/class/adherent_type.class.php"); + +$langs->load("main"); +$langs->load("errors"); + + +// Global variables +$version=DOL_VERSION; +$error=0; +$forcecommit=0; +$confirmed=0; + + +/* + * Main + */ + +@set_time_limit(0); +print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; +dol_syslog($script_file." launched with arg ".join(',',$argv)); + +// List of fields to get from LDAP +$required_fields = array( + $conf->global->LDAP_KEY_MEMBERS_TYPES, + $conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME, + $conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION, + $conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS +); + +// Remove from required_fields all entries not configured in LDAP (empty) and duplicated +$required_fields=array_unique(array_values(array_filter($required_fields, "dolValidElementType"))); + + +if (! isset($argv[1])) { + //print "Usage: $script_file (nocommitiferror|commitiferror) [id_group]\n"; + print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n"; + exit(-1); +} + +foreach($argv as $key => $val) +{ + if ($val == 'commitiferror') $forcecommit=1; + if (preg_match('/--server=([^\s]+)$/',$val,$reg)) $conf->global->LDAP_SERVER_HOST=$reg[1]; + if (preg_match('/--excludeuser=([^\s]+)$/',$val,$reg)) $excludeuser=explode(',',$reg[1]); + if (preg_match('/-y$/',$val,$reg)) $confirmed=1; +} + +print "Mails sending disabled (useless in batch mode)\n"; +$conf->global->MAIN_DISABLE_ALL_MAILS=1; // On bloque les mails +print "\n"; +print "----- Synchronize all records from LDAP database:\n"; +print "host=".$conf->global->LDAP_SERVER_HOST."\n"; +print "port=".$conf->global->LDAP_SERVER_PORT."\n"; +print "login=".$conf->global->LDAP_ADMIN_DN."\n"; +print "pass=".preg_replace('/./i','*',$conf->global->LDAP_ADMIN_PASS)."\n"; +print "DN to extract=".$conf->global->LDAP_MEMBER_TYPE_DN."\n"; +print 'Filter=('.$conf->global->LDAP_KEY_MEMBERS_TYPES.'=*)'."\n"; +print "----- To Dolibarr database:\n"; +print "type=".$conf->db->type."\n"; +print "host=".$conf->db->host."\n"; +print "port=".$conf->db->port."\n"; +print "login=".$conf->db->user."\n"; +print "database=".$conf->db->name."\n"; +print "----- Options:\n"; +print "commitiferror=".$forcecommit."\n"; +print "Mapped LDAP fields=".join(',',$required_fields)."\n"; +print "\n"; + +if (! $confirmed) +{ + print "Hit Enter to continue or CTRL+C to stop...\n"; + $input = trim(fgets(STDIN)); +} + +if (empty($conf->global->LDAP_MEMBER_TYPE_DN)) +{ + print $langs->trans("Error").': '.$langs->trans("LDAP setup for members types not defined inside Dolibarr"); + exit(-1); +} + + +$ldap = new Ldap(); +$result = $ldap->connect_bind(); +if ($result >= 0) +{ + $justthese=array(); + + + // We disable synchro Dolibarr-LDAP + $conf->global->LDAP_MEMBER_TYPE_ACTIVE=0; + + $ldaprecords = $ldap->getRecords('*',$conf->global->LDAP_MEMBER_TYPE_DN, $conf->global->LDAP_KEY_MEMBERS_TYPES, $required_fields, 0, array($conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS)); + if (is_array($ldaprecords)) + { + $db->begin(); + + // Warning $ldapuser has a key in lowercase + foreach ($ldaprecords as $key => $ldapgroup) + { + $membertype = new AdherentType($db); + $membertype->fetch('', $ldapgroup[$conf->global->LDAP_KEY_MEMBERS_TYPES]); + $membertype->label = $ldapgroup[$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME]; + $membertype->description = $ldapgroup[$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION]; + $membertype->entity = $conf->entity; + + //print_r($ldapgroup); + + if ($membertype->id > 0) { // Member type update + print $langs->transnoentities("MemberTypeUpdate").' # '.$key.': name='.$membertype->label; + $res=$membertype->update($user); + + if ($res > 0) + { + print ' --> Updated member type id='.$membertype->id.' name='.$membertype->label; + } + else + { + $error++; + print ' --> '.$res.' '.$membertype->error; + } + print "\n"; + } else { // Member type creation + print $langs->transnoentities("MemberTypeCreate").' # '.$key.': name='.$membertype->label; + $res=$membertype->create($user); + + if ($res > 0) + { + print ' --> Created member type id='.$membertype->id.' name='.$membertype->label; + } + else + { + $error++; + print ' --> '.$res.' '.$membertype->error; + } + print "\n"; + } + + //print_r($membertype); + } + + if (! $error || $forcecommit) + { + if (! $error) print $langs->transnoentities("NoErrorCommitIsDone")."\n"; + else print $langs->transnoentities("ErrorButCommitIsDone")."\n"; + $db->commit(); + } + else + { + print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone",$error)."\n"; + $db->rollback(); + } + print "\n"; + } + else + { + dol_print_error('',$ldap->error); + $error++; + } +} +else +{ + dol_print_error('',$ldap->error); + $error++; +} + + +exit($error); + + +/** + * Function to say if a value is empty or not + * + * @param string $element Value to test + * @return boolean True of false + */ +function dolValidElementType($element) +{ + return (trim($element) != ''); +} + diff --git a/scripts/odt2pdf/odt2pdf.sh b/scripts/odt2pdf/odt2pdf.sh index 4cf1ab54013..2a3550de29b 100755 --- a/scripts/odt2pdf/odt2pdf.sh +++ b/scripts/odt2pdf/odt2pdf.sh @@ -3,20 +3,26 @@ # @copyright GPL License 2013 - Florian HEnry - florian.henry@open-concept.pro # @copyright GPL License 2017 - Laurent Destailleur - eldy@users.sourceforge.net # -# Convert an ODT into a PDF using "jodconverter" or "pyodconverter" tool. -# Dolibarr variable MAIN_ODT_AS_PDF must be defined to value "jodconverter" to call jodconverter wrapper after ODT generation +# Convert an ODT into a PDF using "jodconverter" or "pyodconverter" or "unoconv" tool. +# Dolibarr variable MAIN_ODT_AS_PDF must be defined +# to value "unoconv" to call unoconv CLI tool after ODT generation. # or value "pyodconverter" to call DocumentConverter.py after ODT generation. +# or value "jodconverter" to call jodconverter wrapper after ODT generation # or value "/pathto/jodconverter-cli-file.jar" to call jodconverter java tool without wrapper after ODT generation. # Dolibarr variable MAIN_DOL_SCRIPTS_ROOT must be defined to path of script directories (otherwise dolibarr will try to guess). if [ "x$1" == "x" ] then - echo "Usage: odt2pdf.sh fullfilename [jodconverter|pyodconverter|pathtojodconverterjar]" + echo "Usage: odt2pdf.sh fullfilename [unoconv|jodconverter|pyodconverter|pathtojodconverterjar]" + echo "Example: odt2pdf.sh myfile unoconv" echo "Example: odt2pdf.sh myfile ~/jodconverter/jodconverter-cli-2.2.2.jar" exit fi + + + # Full patch where soffice is installed soffice="/usr/bin/soffice" @@ -26,7 +32,21 @@ home_java="/tmp" # Main program if [ -f "$1.odt" ] - then +then + + if [ "x$2" == "xunoconv" ] + then + # See issue https://github.com/dagwieers/unoconv/issues/87 + /usr/bin/unoconv -vvv "$1.odt" + retcode=$? + if [ $retcode -ne 0 ] + then + echo "Error while converting odt to pdf: $retcode" + exit 1 + fi + exit 0 + fi + nbprocess=$(pgrep -c soffice) if [ $nbprocess -ne 1 ] # If there is some soffice process running then @@ -59,8 +79,9 @@ if [ -f "$1.odt" ] echo "Error while converting odt to pdf: $retcode" exit 1 fi + sleep 1 - else +else echo "Error: Odt file $1.odt does not exist" exit 1 fi diff --git a/test/phpunit/AdherentTest.php b/test/phpunit/AdherentTest.php index 34ec0a80917..4c92f507f66 100644 --- a/test/phpunit/AdherentTest.php +++ b/test/phpunit/AdherentTest.php @@ -138,8 +138,8 @@ class AdherentTest extends PHPUnit_Framework_TestCase $localobject=new AdherentType($this->savdb); $localobject->statut=1; - $localobject->libelle='Adherent type test'; - $localobject->cotisation=1; + $localobject->label='Adherent type test'; + $localobject->subscription=1; $localobject->vote=1; $result=$localobject->create($user); print __METHOD__." result=".$result."\n"; @@ -196,7 +196,6 @@ class AdherentTest extends PHPUnit_Framework_TestCase $result=$localobject->fetch($id); print __METHOD__." id=".$id." result=".$result."\n"; $this->assertLessThan($result, 0); - return $localobject; } @@ -318,14 +317,13 @@ class AdherentTest extends PHPUnit_Framework_TestCase $langs=$this->savlangs; $db=$this->savdb; - $template = '%DOL_MAIN_URL_ROOT%,%ID%,%CIVILITY%,%FIRSTNAME%,%LASTNAME%,%FULLNAME%,%COMPANY%,'. - '%ADDRESS%,%ZIP%,%TOWN%,%COUNTRY%,%EMAIL%,%BIRTH%,%PHOTO%,%LOGIN%,%PASSWORD%,%PRENOM%,'. - '%NOM%,%SOCIETE%,%ADDRESS%,%ZIP%,%TOWN%,%COUNTRY%'; + $template = '__CIVILITY__,__FIRSTNAME__,__LASTNAME__,__FULLNAME__,__COMPANY__,'. + '__ADDRESS__,__ZIP__,__TOWN__,__COUNTRY__,__EMAIL__,__BIRTH__,__PHOTO__,__LOGIN__'; // If option to store clear password has been set, we get 'dolibspec' into PASSWORD field. - $expected = DOL_MAIN_URL_ROOT.','.$localobject->id.',,New firstname,New name,New firstname New name,'. + $expected = ',New firstname,New name,New firstname New name,'. 'New company,New address,New zip,New town,Belgium,newemail@newemail.com,'.dol_print_date($localobject->birth,'day').',,'. - 'newlogin,dolibspec,New firstname,New name,New company,New address,New zip,New town,Belgium'; + 'newlogin'; $result = $localobject->makeSubstitution($template); print __METHOD__." result=".$result."\n"; diff --git a/test/phpunit/AllTests.php b/test/phpunit/AllTests.php index 56c5541d0bb..df36ffabd28 100644 --- a/test/phpunit/AllTests.php +++ b/test/phpunit/AllTests.php @@ -113,6 +113,11 @@ class AllTests require_once dirname(__FILE__).'/SecurityTest.php'; $suite->addTestSuite('SecurityTest'); + require_once dirname(__FILE__).'/UserTest.php'; + $suite->addTestSuite('UserTest'); + require_once dirname(__FILE__).'/UserGroupTest.php'; + $suite->addTestSuite('UserGroupTest'); + require_once dirname(__FILE__).'/NumberingModulesTest.php'; $suite->addTestSuite('NumberingModulesTest'); require_once dirname(__FILE__).'/PgsqlTest.php'; @@ -151,6 +156,9 @@ class AllTests require_once dirname(__FILE__).'/PropalTest.php'; $suite->addTestSuite('PropalTest'); + require_once dirname(__FILE__).'/SupplierProposalTest.php'; + $suite->addTestSuite('SupplierProposalTest'); + require_once dirname(__FILE__).'/CommandeTest.php'; $suite->addTestSuite('CommandeTest'); @@ -166,10 +174,6 @@ class AllTests require_once dirname(__FILE__).'/FactureFournisseurTest.php'; $suite->addTestSuite('FactureFournisseurTest'); - require_once dirname(__FILE__).'/UserTest.php'; - $suite->addTestSuite('UserTest'); - require_once dirname(__FILE__).'/UserGroupTest.php'; - $suite->addTestSuite('UserGroupTest'); require_once dirname(__FILE__).'/BankAccountTest.php'; $suite->addTestSuite('BankAccountTest'); require_once dirname(__FILE__).'/CompanyBankAccountTest.php'; diff --git a/test/phpunit/BuildDocTest.php b/test/phpunit/BuildDocTest.php index 25b7bd15c03..c30bf1b9a96 100644 --- a/test/phpunit/BuildDocTest.php +++ b/test/phpunit/BuildDocTest.php @@ -172,7 +172,7 @@ class BuildDocTest extends PHPUnit_Framework_TestCase $localobjectcom->initAsSpecimen(); $localobject=new Facture($this->savdb); - $localobject->createFromOrder($localobjectcom); + $localobject->createFromOrder($localobjectcom, $user); $localobject->date_lim_reglement = dol_now() + 3600 * 24 *30; // Crabe (english) diff --git a/test/phpunit/CodingPhpTest.php b/test/phpunit/CodingPhpTest.php index 1a11f3fc1c8..073adc8ef9a 100644 --- a/test/phpunit/CodingPhpTest.php +++ b/test/phpunit/CodingPhpTest.php @@ -177,10 +177,10 @@ class CodingPhpTest extends PHPUnit_Framework_TestCase $ok=true; $matches=array(); // Check string ='".$this->xxx with xxx that is not 'escape'. It means we forget a db->escape when forging sql request. - preg_match_all('/=\s*\'"\s*\.\s*\$this->(....)/', $filecontent, $matches, PREG_SET_ORDER); + preg_match_all('/(=|sql.+)\s*\'"\s*\.\s*\$this->(....)/', $filecontent, $matches, PREG_SET_ORDER); foreach($matches as $key => $val) { - if ($val[1] != 'db->' && $val[1] != 'esca') + if ($val[2] != 'db->' && $val[2] != 'esca') { $ok=false; break; @@ -199,13 +199,13 @@ class CodingPhpTest extends PHPUnit_Framework_TestCase preg_match_all('/(...................)\$_SERVER\[\'QUERY_STRING\'\]/', $filecontent, $matches, PREG_SET_ORDER); foreach($matches as $key => $val) { - if ($val[1] != 'dol_escape_htmltag(') + if ($val[1] != 'dol_escape_htmltag(' && $val[1] != 'l_string_nohtmltag(') { $ok=false; break; } } - $this->assertTrue($ok, 'Found a $_SERVER[\'QUERY_STRING\'] without dol_escape_htmltag around in file '.$file['fullname'].' ('.$val[1].'$_SERVER[\'QUERY_STRING\']). Bad.'); + $this->assertTrue($ok, 'Found a $_SERVER[\'QUERY_STRING\'] without dol_escape_htmltag neither dol_string_nohtmltag around it, in file '.$file['fullname'].' ('.$val[1].'$_SERVER[\'QUERY_STRING\']). Bad.'); // Test that first param of print_liste_field_titre is a translation key and not the translated value diff --git a/test/phpunit/CoreTest.php b/test/phpunit/CoreTest.php index 3a158260e96..54ebca5ac67 100644 --- a/test/phpunit/CoreTest.php +++ b/test/phpunit/CoreTest.php @@ -137,7 +137,7 @@ class CoreTest extends PHPUnit_Framework_TestCase global $dolibarr_main_db_type; global $dolibarr_main_db_prefix; - $testtodo=3; + $testtodo=0; // Case 1: // Test for subdir dolibarrnew (that point to htdocs) in root directory /var/www @@ -217,9 +217,12 @@ class CoreTest extends PHPUnit_Framework_TestCase // Force to rerun filefunc.inc.php include dirname(__FILE__).'/../../htdocs/filefunc.inc.php'; - print __METHOD__." DOL_MAIN_URL_ROOT=".DOL_MAIN_URL_ROOT."\n"; - print __METHOD__." DOL_URL_ROOT=".DOL_URL_ROOT."\n"; - $this->assertEquals($expectedresult, DOL_URL_ROOT); + if ($testtodo != 0) + { + print __METHOD__." DOL_MAIN_URL_ROOT=".DOL_MAIN_URL_ROOT."\n"; + print __METHOD__." DOL_URL_ROOT=".DOL_URL_ROOT."\n"; + $this->assertEquals($expectedresult, DOL_URL_ROOT); + } return true; } @@ -256,59 +259,138 @@ class CoreTest extends PHPUnit_Framework_TestCase */ function test_sql_and_script_inject($val, $type) { - $sql_inj = 0; - // For SQL Injection (only GET and POST are used to be included into bad escaped SQL requests) - if ($type != 2) - { - $sql_inj += preg_match('/delete\s+from/i', $val); - $sql_inj += preg_match('/create\s+table/i', $val); - $sql_inj += preg_match('/update.+set.+=/i', $val); - $sql_inj += preg_match('/insert\s+into/i', $val); - $sql_inj += preg_match('/select.+from/i', $val); - $sql_inj += preg_match('/union.+select/i', $val); - $sql_inj += preg_match('/into\s+(outfile|dumpfile)/i', $val); - $sql_inj += preg_match('/(\.\.%2f)+/i', $val); - } - // For XSS Injection done by adding javascript with script - // This is all cases a browser consider text is javascript: - // When it found ' - $sql_inj += preg_match('/onerror\s*=/i', $val); // onerror can be set on img or any html tag like - if ($type == 1) - { - $sql_inj += preg_match('/javascript:/i', $val); - $sql_inj += preg_match('/vbscript:/i', $val); - } - // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param) - if ($type == 1) $sql_inj += preg_match('/"/i', $val); // We refused " in GET parameters value - if ($type == 2) $sql_inj += preg_match('/[;"]/', $val); // PHP_SELF is a file system path. It can contains spaces. - return $sql_inj; + $inj = 0; + // For SQL Injection (only GET and POST are used to be included into bad escaped SQL requests) + if ($type != 2) + { + $inj += preg_match('/delete\s+from/i', $val); + $inj += preg_match('/create\s+table/i', $val); + $inj += preg_match('/update.+set.+=/i', $val); + $inj += preg_match('/insert\s+into/i', $val); + $inj += preg_match('/select.+from/i', $val); + $inj += preg_match('/union.+select/i', $val); + $inj += preg_match('/into\s+(outfile|dumpfile)/i', $val); + $inj += preg_match('/(\.\.%2f)+/i', $val); + } + // For XSS Injection done by adding javascript with script + // This is all cases a browser consider text is javascript: + // When it found ' + $inj += preg_match('/onerror\s*=/i', $val); // onerror can be set on img or any html tag like + $inj += preg_match('/onfocus\s*=/i', $val); // onfocus can be set on input text html tag like + $inj += preg_match('/onload\s*=/i', $val); // onload can be set on svg tag or other tag like body + //$inj += preg_match('/on[A-Z][a-z]+\*=/', $val); // To lock event handlers onAbort(), ... + $inj += preg_match('/:|:|:/i', $val); // refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...' + //if ($type == 1) + //{ + $inj += preg_match('/javascript:/i', $val); + $inj += preg_match('/vbscript:/i', $val); + //} + // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param) + if ($type == 1) $inj += preg_match('/"/i', $val); // We refused " in GET parameters value + if ($type == 2) $inj += preg_match('/[;"]/', $val); // PHP_SELF is a file system path. It can contains spaces. + return $inj; } // Run tests - + // More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet + + // Should be OK + $expectedresult=0; + $_SERVER["PHP_SELF"]='/DIR WITH SPACE/htdocs/admin/index.php?mainmenu=home&leftmenu=setup&username=weservices'; $result=test_sql_and_script_inject($_SERVER["PHP_SELF"], 2); - $expectedresult=0; $this->assertEquals($expectedresult, $result, 'Error on test_sql_and_script_inject 1a'); - + + // Should detect XSS + $expectedresult=1; + $_SERVER["PHP_SELF"]='/DIR WITH SPACE/htdocs/admin/index.php?mainmenu=home&leftmenu=setup&username=weservices;badaction'; $result=test_sql_and_script_inject($_SERVER["PHP_SELF"], 2); - $expectedresult=1; - $this->assertEquals($expectedresult, $result, 'Error on test_sql_and_script_inject 1b'); - - $_GET['aaa']=""; - $result=test_sql_and_script_inject($_GET['aaa'], 0); - $expectedresult=1; - $this->assertEquals($expectedresult, $result, 'Error on test_sql_and_script_inject 2'); - - $_POST['bbb']=""; - $result=test_sql_and_script_inject($_POST['bbb'], 2); - $expectedresult=1; - $this->assertEquals($expectedresult, $result, 'Error on test_sql_and_script_inject 3'); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject 1b'); + + $test=""; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject aaa'); + + $test=""; + $result=test_sql_and_script_inject($test, 2); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject aaa2'); + + $test=''; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject aaa3'); + $test=''; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject aaa4'); + $test=''; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject aaa5'); + $test=''; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject aaa6'); + $test=''; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject aaa7'); + + $test=''; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject bbb'); + + $test=''; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject ccc'); + + $test=''; + $result=test_sql_and_script_inject($test, 1); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject ddd'); + + $test='">'; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject eee'); + + $test=' + '; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject eee'); + + $test=""; // Is locked by some brwoser like chrome because the default directive no-referrer-when-downgrade is sent when requesting the SRC and then refused because of browser protection on img src load without referrer. + $test=""; // Same + + $test=''; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject fff1'); + $test=''; + $result=test_sql_and_script_inject($test, 0); + $this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject fff2'); + + // This case seems to be filtered by browsers now. + $test=''; + //$result=test_sql_and_script_inject($test, 0); + //$this->assertGreaterThanOrEqual($expectedresult, $result, 'Error on test_sql_and_script_inject ggg'); + + $test='