diff --git a/ChangeLog b/ChangeLog index aa82859a5b8..d1aa820e4a2 100644 --- a/ChangeLog +++ b/ChangeLog @@ -15,6 +15,10 @@ Following changes may create regressions for some external modules, but were nec * Rename property $paiementid in API api_supplier_invoices into $payment_mode_id * The deprecated subsitution key __SIGNATURE__ has been removed. Replace with __USER_SIGNATURE__ if you still use old syntax in your email templates. +* The hidden option HOLIDAY_MORE_PUBLIC_HOLIDAYS has been removed. Use instead the dictionary table if you need to define custom + days of holiday. +* Property num_paiement has been renamed num_payment everywhere for better code consistency. + ***** ChangeLog for 12.0.2 compared to 12.0.1 ***** FIX: computation of the bottom margin of returns NaN because body is not loaded yet diff --git a/SECURITY.md b/SECURITY.md index d0ab526b012..59311cf71ba 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -65,9 +65,9 @@ No vulnerability disclosure, including partial is allowed for the moment. ONLY vulnerabilities discovered, when the following setup on tested platform is used, are accepted: * $dolibarr_main_prod must be set to 1 into conf.php -* $dolibarr_nocsrfcheck must be kept to the default value 1 into conf.php +* $dolibarr_nocsrfcheck must be kept to the value 1 into conf.php (this is the default value) * The module DebugBar must NOT be enabled (by default, this module is not enabled) -* The constant MAIN_SECURITY_CSRF_WITH_TOKEN must be set to 1 into backoffice menu Home - Setup - Other (this value should be switched soon to 1 by default) +* The constant MAIN_SECURITY_CSRF_WITH_TOKEN must be set to 1 into backoffice menu Home - Setup - Other (this protection should be enabled soon by default) * ONLY security reports on "stable" modules are allowed (troubles into "experimental" and "developement" modules are not accepted). Scope is the web application (back office) and the APIs. @@ -93,11 +93,9 @@ Scope is the web application (back office) and the APIs. * "Self" XSS * Missing cookie flags * SSL/TLS best practices -* Mixed content warnings * Denial of Service attacks * Clickjacking/UI redressing * Physical or social engineering attempts -* Recently disclosed 0-day vulnerabilities * Presence of autocomplete attribute on web forms * Vulnerabilities affecting outdated browsers or platforms * Issues that require physical access to a victim’s computer/device diff --git a/build/README b/build/README index 67ceb05c8d2..f7e8ebfe60b 100644 --- a/build/README +++ b/build/README @@ -19,30 +19,34 @@ Note: Prerequisites to build autoexe DoliWamp package: > Launch "wine cmd" to check a drive Z: pointing to / exists. > Install InnoSetup For example by running isetup-5.3.9.exe (http://www.jrsoftware.org) -> Install WampServer into "C:\Program Files\Wamp" - For example by running wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-32b.exe (http://www.wampserver.com) -> Install WampServer addon to have versions: Mysql5.0.45 - For example by running WampServer2-MYSQL5045.exe (http://www.wampserver.com) -> To build from Windows (running from makepack-dolibarr.pl script is however - recommanded), open file build/exe/doliwamp.iss and click on button "Compile". - The .exe file will be build into directory build. +> Install WampServer into "C:\wamp64" to have Apache, PHP and MariaDB + For example by running wampserver3.2.0_x64.exe (http://www.wampserver.com). See file build/exe/doliwamp.iss to know the doliwamp version currently setup. > Add path to ISCC into PATH windows var: Launch wine cmd, then regedit and add entry int HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment\PATH +> To build manually the .exe from Windows (running from makepack-dolibarr.pl script is however recommanded), + open file build/exe/doliwamp.iss and click on button "Compile". + The .exe file will be build into directory build. + + - To build a theme package, launch the script > perl makepack-dolibarrtheme.pl + + - To build a package for a module, launch the script > perl makepack-dolibarrmodule.pl + + - To build developper documentation, launch the script > perl dolibarr-doxygen-build.pl + Note: -The build directory and all its contents is absolutely not required to make -Dolibarr working. It is here only to build Dolibarr packages, and those -generated packages will not contains this "build" directory. +The build directory and all its contents is absolutely not required to make Dolibarr working. +It is here only to build Dolibarr packages, and those generated packages will not contains this "build" directory. You can find in "build", following sub-directories: @@ -59,6 +63,9 @@ To build Mac OS package (not ready yet). * doap: To build Doap descriptor to promote/describe Dolibarr releases. +* docker: +To deploy Dolibarr with docker. + * doxygen: Dir with config file to build doxygen documentation. @@ -66,12 +73,12 @@ Dir with config file to build doxygen documentation. To build exe package for Windows that distribute Dolibarr sources or to build the complete DoliWamp package. +* gource: +To build the video of history of git changes. + * launchpad: Doc file to explain how to use launchpad. -* live: -Doc file to explain how to create a demo live CD. - * obs: Doc file to explain how to push release onto OBS. @@ -90,5 +97,8 @@ To build Redhat, Opensuse or Mandriva package. * tgz: To build a tgz package. +* travis-ci: +Used by travis to make CI. + * zip: To build a zip package. diff --git a/build/docker/Dockerfile b/build/docker/Dockerfile index 9264eed5ef2..2be287c2db9 100644 --- a/build/docker/Dockerfile +++ b/build/docker/Dockerfile @@ -1,38 +1,50 @@ -FROM php:7.2-apache +FROM php:7.3-apache -ENV HOST_USER_ID 33 ENV PHP_INI_DATE_TIMEZONE 'UTC' +ENV PHP_INI_MEMORY_LIMIT 256M -RUN apt-get update && apt-get install -y libpng16-16 libpng-dev libjpeg62-turbo libjpeg62-turbo-dev libldap2-dev zlib1g-dev libicu-dev g++\ - && rm -rf /var/lib/apt/lists/* \ - && docker-php-ext-configure gd --with-png-dir=/usr --with-jpeg-dir=/usr \ - && docker-php-ext-install gd \ - && docker-php-ext-install zip \ - && docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ \ - && docker-php-ext-install ldap \ - && docker-php-ext-install mysqli \ - && docker-php-ext-install calendar \ - && docker-php-ext-configure intl \ - && docker-php-ext-install intl \ - && apt-get autoremove --purge -y libpng-dev libjpeg62-turbo-dev libldap2-dev zlib1g-dev libicu-dev g++ +RUN apt-get update -y \ + && apt-get install -y --no-install-recommends \ + libfreetype6-dev \ + libjpeg62-turbo-dev \ + libjpeg62-turbo \ + libpng-dev \ + libpng16-16 \ + libldap2-dev \ + libxml2-dev \ + libzip-dev \ + zlib1g-dev \ + libicu-dev \ + g++ \ + default-mysql-client \ + unzip \ + curl \ + apt-utils \ + && apt-get autoremove -y \ + && rm -rf /var/lib/apt/lists/* \ + && docker-php-ext-configure gd --with-png-dir=/usr --with-jpeg-dir=/usr \ + && docker-php-ext-install -j$(nproc) calendar intl mysqli pdo_mysql gd soap zip \ + && docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ \ + && docker-php-ext-install -j$(nproc) ldap && \ + mv ${PHP_INI_DIR}/php.ini-development ${PHP_INI_DIR}/php.ini RUN mkdir /var/documents -RUN chown www-data /var/documents +RUN chown www-data:www-data /var/documents COPY docker-run.sh /usr/local/bin/ RUN chmod +x /usr/local/bin/docker-run.sh RUN pecl install xdebug && docker-php-ext-enable xdebug -RUN echo 'zend_extension="/usr/local/lib/php/extensions/no-debug-non-zts-20151012/xdebug.so"' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_autostart=0' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_enable=1' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.default_enable=0' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_host=docker.host' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_port=9000' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_connect_back=0' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.profiler_enable=0' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_log="/tmp/xdebug.log"' >> /usr/local/etc/php/php.ini -RUN echo '172.17.0.1 docker.host' >> /etc/hosts +RUN echo 'zend_extension="/usr/local/lib/php/extensions/no-debug-non-zts-20180731/xdebug.so"' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_autostart=1' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_enable=1' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.default_enable=1' >> ${PHP_INI_DIR}/php.ini +#RUN echo 'xdebug.remote_host=docker.host' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_port=9000' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_connect_back=1' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.profiler_enable=0' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_log="/tmp/xdebug.log"' >> ${PHP_INI_DIR}/php.ini +#RUN echo '172.17.0.1 docker.host' >> /etc/hosts EXPOSE 80 diff --git a/build/docker/README.md b/build/docker/README.md index 616cbd8fa78..2fd278a531f 100644 --- a/build/docker/README.md +++ b/build/docker/README.md @@ -1,6 +1,8 @@ # How to use it ? The docker-compose.yml file is used to build and run Dolibarr in the current workspace. +This docker image intended for developpement usage. +For production usage you should consider other contributor reference like https://hub.docker.com/r/tuxgasy/dolibarr Before build/run, define the variable HOST_USER_ID as following: @@ -26,3 +28,4 @@ The URL to go to PhpMyAdmin is (login/password is root/root) : Setup the database connection during the installation process, please use mariad b (name of the database container) as database host. +Setup documents folder, during the installation process, to /var/documents diff --git a/build/docker/docker-compose.yml b/build/docker/docker-compose.yml index cc839810e7f..efdc95d2858 100644 --- a/build/docker/docker-compose.yml +++ b/build/docker/docker-compose.yml @@ -1,32 +1,51 @@ -mariadb: - build: mariadb - environment: - MYSQL_ROOT_PASSWORD: root - MYSQL_DATABASE: dolibarr +version: '3' -phpmyadmin: - image: phpmyadmin/phpmyadmin - environment: - PMA_HOST: mariadb - links: - - mariadb - ports: - - "8080:80" +networks: + internal-pod: + internal: true + external-pod: + internal: false -web: - build: . - environment: - HOST_USER_ID: $HOST_USER_ID - volumes: - - ../../htdocs:/var/www/html - links: - - mariadb - - mail - ports: - - "80:80" +services: + mariadb: + image: mariadb:latest + environment: + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: dolibarr + networks: + - internal-pod -mail: - image: maildev/maildev - ports: - - "8081:80" - - "25:25" \ No newline at end of file + phpmyadmin: + image: phpmyadmin/phpmyadmin + environment: + PMA_HOST: mariadb + depends_on: + - mariadb + ports: + - "8080:80" + networks: + - internal-pod + - external-pod + + web: + build: . + environment: + HOST_USER_ID: $HOST_USER_ID + volumes: + - ../../htdocs:/var/www/html/ + - ../../documents:/var/documents + ports: + - "80:80" + - "9000:9000" + depends_on: + - mariadb + - mail + networks: + - internal-pod + - external-pod + + mail: + image: maildev/maildev + ports: + - "8081:80" + - "25:25" diff --git a/build/docker/docker-run.sh b/build/docker/docker-run.sh index df7272c317d..e57d9adfad0 100644 --- a/build/docker/docker-run.sh +++ b/build/docker/docker-run.sh @@ -1,15 +1,21 @@ #!/bin/bash -usermod -u $HOST_USER_ID www-data -groupmod -g $HOST_USER_ID www-data +usermod -u ${HOST_USER_ID} www-data +groupmod -g ${HOST_USER_ID} www-data chgrp -hR www-data /var/www/html chmod g+rwx /var/www/html/conf +if [ ! -d /var/documents ]; then + echo "[docker-run] => create volume directory /var/documents ..." + mkdir -p /var/documents +fi +echo "[docker-run] => Set Permission to www-data for /var/documents" +chown -R www-data:www-data /var/documents + 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 diff --git a/build/exe/doliwamp/README.md b/build/exe/doliwamp/README.md index 87d3371f9bb..be8cf1f3ac5 100644 --- a/build/exe/doliwamp/README.md +++ b/build/exe/doliwamp/README.md @@ -5,6 +5,7 @@ It's a dedicated Dolibarr version for Windows newbies with no technical knowledg This directory contains files used by *makepack-dolibarr.pl* script to build the all-in-on .EXE package DoliWamp, ready to be distributed (for Windows). +The build of .exe files need to have some windows executable files already installed (Apache, MariaDb). The package to install to get this files are defined into the file *doliwamp.iss* (searhc line starting with "; Value OK:") If you have technical knowledge in web administration and plan to share your server instance (Apache, Mysql or PHP) with other projects than Dolibarr or want to use Dolibarr other components (PostgreSQL), you should not use this assistant and make a manual installation of Dolibarr on your existing server by downloading the standard package (.tgz or .zip file). diff --git a/build/exe/doliwamp/doliwamp.iss b/build/exe/doliwamp/doliwamp.iss index 4a6dca3af01..ed8e07d7468 100644 --- a/build/exe/doliwamp/doliwamp.iss +++ b/build/exe/doliwamp/doliwamp.iss @@ -104,8 +104,8 @@ Source: "build\exe\doliwamp\UsedPort.exe"; DestDir: "{app}\"; Flags: ignoreversi ; Value OK: apache 2.2.6, php 5.2.5 (5.2.11, 5.3.0 and 5.3.1 fails if php_exif, php_pgsql, php_zip is on), mysql 5.0.45 ; Value OK: apache 2.2.11, php 5.3.0 (if no php_exif, php_pgsql, php_zip), mysql 5.0.45 ; Value OK: apache 2.4.9, php 5.5.12, mysql 5.0.45 instead of 5.6.17 (wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-32b.exe) -; Value To test: apache 2.4.41, php 7.3.12, mariadb10.4.10 (wampserver3.2.0_x64.exe) -Source: "C:\Program Files\Wamp\apps\phpmyadmin4.1.14\*.*"; DestDir: "{app}\apps\phpmyadmin4.1.14"; Flags: ignoreversion recursesubdirs; Excludes: "config.inc.php,wampserver.conf,*.log,*_log,darkblue_orange" +; Value OK: apache 2.4.41, php 7.3.12, mariadb10.4.10 (wampserver3.2.0_x64.exe) +Source: "C:\wamp64\apps\phpmyadmin4.9.2\*.*"; DestDir: "{app}\apps\phpmyadmin4.9.2"; Flags: ignoreversion recursesubdirs; Excludes: "config.inc.php,wampserver.conf,*.log,*_log,darkblue_orange" ;Source: "C:\Program Files\Wamp\bin\apache\apache2.4.9\*.*"; DestDir: "{app}\bin\apache\apache2.4.9"; Flags: ignoreversion recursesubdirs; Excludes: "php.ini,httpd.conf,wampserver.conf,*.log,*_log" Source: "C:\wamp64\bin\apache\apache2.4.41\*.*"; DestDir: "{app}\bin\apache\apache2.4.41"; Flags: ignoreversion recursesubdirs; Excludes: "php.ini,httpd.conf,wampserver.conf,*.log,*_log" ;Source: "C:\Program Files\Wamp\bin\php\php5.5.12\*.*"; DestDir: "{app}\bin\php\php5.5.12"; Flags: ignoreversion recursesubdirs; Excludes: "php.ini,phpForApache.ini,wampserver.conf,*.log,*_log" diff --git a/build/pdf/README.txt b/build/pdf/README.txt index 2335ff4b7f7..7a5424ca3d5 100644 --- a/build/pdf/README.txt +++ b/build/pdf/README.txt @@ -1,9 +1,10 @@ -To make htmldoc working from wiki.dolibarr.org, them must be modified to have +To make htmldoc working from wiki.dolibarr.org, the wiki must be modified to have -$_SERVER["HTTP_USER_AGENT"] is "HTMLDOC/x.y.z" -$_COOKIE["htmldoc"] may also be defined if set on command line. - -To disable part, add -class="htmldoc-ignore" with css +To disable part of content, add: +class="htmldoc-ignore" +with css .htmldoc-ignore { display: none; } +Note: +$_SERVER["HTTP_USER_AGENT"] is "HTMLDOC/x.y.z" +$_COOKIE["htmldoc"] may also be defined if set on command line. diff --git a/build/sitemap/urllist-wiki.txt b/build/sitemap/urllist-wiki.txt index ae13bb96d87..2a70e61f146 100644 --- a/build/sitemap/urllist-wiki.txt +++ b/build/sitemap/urllist-wiki.txt @@ -1 +1 @@ -http://wiki.dolibarr.org/ +https://wiki.dolibarr.org/ diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index f6a4adac21e..e6264648159 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -390,7 +390,7 @@ if ($resql) if (!empty($arrayfields['aa.account_number']['checked'])) { print ""; - print $accountstatic->getNomUrl(1, 0, 0, '', 0, 1); + print $accountstatic->getNomUrl(1, 0, 0, '', 0, 1, 0, 'accountcard'); print "\n"; if (!$i) $totalarray['nbfield']++; } diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php index bc695da0203..4ad131f5170 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -44,6 +44,8 @@ $cancel = GETPOST('cancel', 'alpha'); $accountingaccount = GETPOST('accountingaccount', 'alpha'); // Security check +if ($user->socid > 0) accessforbidden(); +if (!$user->rights->accounting->chartofaccount) accessforbidden(); $object = new AccountingAccount($db); diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index 96303f36b1d..84ea304a74d 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -75,7 +75,7 @@ if ($mysoc->isInEEC()) { $list_account[] = 'ACCOUNTING_SERVICE_BUY_INTRA_ACCOUNT'; } $list_account[] = 'ACCOUNTING_SERVICE_BUY_EXPORT_ACCOUNT'; -$list_account[] = '---Other---'; +$list_account[] = '---Others---'; $list_account[] = 'ACCOUNTING_VAT_BUY_ACCOUNT'; $list_account[] = 'ACCOUNTING_VAT_SOLD_ACCOUNT'; $list_account[] = 'ACCOUNTING_VAT_PAY_ACCOUNT'; @@ -94,6 +94,9 @@ if ($conf->loan->enabled) { $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_INTEREST'; $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_INSURANCE'; } +if ($conf->societe->enabled) { + $list_account[] = 'ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT'; +} /* * Actions diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index afc40bfdff9..f37ff79a1fa 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -297,12 +297,12 @@ print ''; print ''.$langs->trans("ACCOUNTANCY_COMBO_FOR_AUX").''; if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { print ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; } else { print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; } print ''; @@ -310,12 +310,12 @@ print ''; print ''.$langs->trans("ACCOUNTING_MANAGE_ZERO").''; if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO)) { print ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; } else { print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; } print ''; @@ -385,9 +385,9 @@ foreach ($list_binding as $key) if ($key == 'ACCOUNTING_DATE_START_BINDING') { print $form->selectDate(($conf->global->$key ? $db->idate($conf->global->$key) : -1), $key, 0, 0, 1); } elseif ($key == 'ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER') { - $array=array(0=>$langs->trans("PreviousMonth"), 1=>$langs->trans("CurrentMonth"), 2=>$langs->trans("Fiscalyear")); - print $form->selectarray($key, $array, (isset($conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER)?$conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER:0)); - } else { + $array = array(0=>$langs->trans("PreviousMonth"), 1=>$langs->trans("CurrentMonth"), 2=>$langs->trans("Fiscalyear")); + print $form->selectarray($key, $array, (isset($conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER) ? $conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER : 0)); + } else { print ''; } diff --git a/htdocs/accountancy/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index 059e1eb57b1..a5000dda461 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -252,8 +252,8 @@ if ($action != 'export_csv') print $langs->trans('to'); print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array(), 1, 1, ''); print ''; - print ''; - $searchpicto = $form->showFilterAndCheckAddButtons(0); + print ''; + $searchpicto = $form->showFilterButtons(); print $searchpicto; print ''; @@ -276,8 +276,12 @@ if ($action != 'export_csv') $accountingaccountstatic = new AccountingAccount($db); - $sql = "select t.numero_compte, (SUM(t.debit) - SUM(t.credit)) as opening_balance from ".MAIN_DB_PREFIX."accounting_bookkeeping as t where entity in ".$conf->entity; - $sql .= " AND t.doc_date < '".$db->idate($search_date_start)."' GROUP BY t.numero_compte"; + $sql = "SELECT t.numero_compte, (SUM(t.debit) - SUM(t.credit)) as opening_balance"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as t"; + $sql .= " WHERE t.entity = ".$conf->entity; // Never do sharing into accounting features + $sql .= " AND t.doc_date < '".$db->idate($search_date_start)."'"; + $sql .= " GROUP BY t.numero_compte"; + $resql = $db->query($sql); $nrows = $resql->num_rows; $opening_balances = array(); @@ -290,7 +294,7 @@ if ($action != 'export_csv') { $accountingaccountstatic->fetch(null, $line->numero_compte, true); if (!empty($accountingaccountstatic->account_number)) { - $accounting_account = $accountingaccountstatic->getNomUrl(0, 1, 1, '', 1); + $accounting_account = $accountingaccountstatic->getNomUrl(0, 1); } else { $accounting_account = length_accountg($line->numero_compte); } @@ -340,7 +344,7 @@ if ($action != 'export_csv') print ''; print "\n"; - // Comptabilise le sous-total + // Records the sub-total $sous_total_debit += $line->debit; $sous_total_credit += $line->credit; } diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index fa8cd088604..130c0e97659 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -809,8 +809,8 @@ class AccountancyExport foreach ($objectLines as $line) { $date_creation = dol_print_date($line->date_creation, '%Y%m%d'); - $date_doc = dol_print_date($line->doc_date, '%Y%m%d'); - $date_valid = dol_print_date($line->date_validated, '%Y%m%d'); + $date_document = dol_print_date($line->doc_date, '%Y%m%d'); + $date_validation = dol_print_date($line->date_validated, '%Y%m%d'); // FEC:JournalCode print $line->code_journal.$separator; @@ -822,25 +822,25 @@ class AccountancyExport print $line->piece_num.$separator; // FEC:EcritureDate - print $date_creation.$separator; + print $date_document . $separator; // FEC:CompteNum print $line->numero_compte.$separator; // FEC:CompteLib - print $line->label_compte.$separator; + print dol_string_unaccent($line->label_compte) . $separator; // FEC:CompAuxNum print $line->subledger_account.$separator; // FEC:CompAuxLib - print $line->subledger_label.$separator; + print dol_string_unaccent($line->subledger_label) . $separator; // FEC:PieceRef print $line->doc_ref.$separator; // FEC:PieceDate - print $date_doc.$separator; + print dol_string_unaccent($date_creation) . $separator; // FEC:EcritureLib print $line->label_operation.$separator; @@ -858,7 +858,7 @@ class AccountancyExport print $line->date_lettering.$separator; // FEC:ValidDate - print $date_valid.$separator; + print $date_validation . $separator; // FEC:Montantdevise print $line->multicurrency_amount.$separator; diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index 7cb30a74bc6..24f14d2ebd2 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -448,7 +448,7 @@ class AccountingAccount extends CommonObject * @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 * @param int $withcompletelabel 0=Short label (field short label), 1=Complete label (field label) - * @param int $option 'bookkeeping', 'bookkeepinglistbyaccount', 'accountcard' + * @param string $option 'bookkeeping', 'bookkeepinglistbyaccount', 'accountcard' * @return string String with URL */ public function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $withcompletelabel = 0, $option = '') @@ -460,12 +460,15 @@ class AccountingAccount extends CommonObject $result = ''; - if (empty($option)) { + if (empty($option) || $option == 'bookkeeping') { $url = DOL_URL_ROOT . '/accountancy/bookkeeping/list.php?search_accountancy_code_start=' . $this->account_number . '&search_accountancy_code_end=' . $this->account_number; + $labelurl = $langs->trans("ShowAccountingAccountInBookKeeping"); } elseif ($option == 'bookkeepinglistbyaccount') { $url = DOL_URL_ROOT . '/accountancy/bookkeeping/listbyaccount.php?search_accountancy_code_start=' . $this->account_number . '&search_accountancy_code_end=' . $this->account_number; + $labelurl = $langs->trans("ShowAccountingAccountInBookKeepingByAccount"); } elseif ($option == 'accountcard') { $url = DOL_URL_ROOT . '/accountancy/admin/card.php?id=' . $this->id; + $labelurl = $langs->trans("ShowAccountingAccount"); } // Add param to save lastsearch_values or not @@ -483,7 +486,7 @@ class AccountingAccount extends CommonObject $labeltoshow = $this->labelshort; } - $label = ''.$langs->trans("ShowAccountingAccount").''; + $label = ''.$labelurl.''; if (!empty($this->account_number)) $label .= '
'.$langs->trans('AccountAccounting').': '.length_accountg($this->account_number); if (!empty($labeltoshow)) @@ -495,7 +498,7 @@ class AccountingAccount extends CommonObject { if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label = $langs->trans("ShowAccountingAccount"); + $label = $labelurl; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php index b7027282281..96750389cc0 100644 --- a/htdocs/accountancy/customer/list.php +++ b/htdocs/accountancy/customer/list.php @@ -140,48 +140,48 @@ if (empty($reshook)) if ($massaction == 'ventil') { - $msg = ''; + $msg = ''; - //print '
' . $langs->trans("Processing") . '...
'; - if (!empty($mesCasesCochees)) { - $msg = '
'.$langs->trans("SelectedLines").': '.count($mesCasesCochees).'
'; - $msg .= '
'; - $cpt = 0; - $ok = 0; - $ko = 0; + //print '
' . $langs->trans("Processing") . '...
'; + if (!empty($mesCasesCochees)) { + $msg = '
'.$langs->trans("SelectedLines").': '.count($mesCasesCochees).'
'; + $msg .= '
'; + $cpt = 0; + $ok = 0; + $ko = 0; - foreach ($mesCasesCochees as $maLigneCochee) { - $maLigneCourante = explode("_", $maLigneCochee); - $monId = $maLigneCourante[0]; - $monCompte = GETPOST('codeventil'.$monId); + foreach ($mesCasesCochees as $maLigneCochee) { + $maLigneCourante = explode("_", $maLigneCochee); + $monId = $maLigneCourante[0]; + $monCompte = GETPOST('codeventil'.$monId); - if ($monCompte <= 0) - { - $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'
'; - $ko++; - } else { - $sql = " UPDATE ".MAIN_DB_PREFIX."facturedet"; - $sql .= " SET fk_code_ventilation = ".$monCompte; - $sql .= " WHERE rowid = ".$monId; + if ($monCompte <= 0) + { + $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'
'; + $ko++; + } else { + $sql = " UPDATE ".MAIN_DB_PREFIX."facturedet"; + $sql .= " SET fk_code_ventilation = ".$monCompte; + $sql .= " WHERE rowid = ".$monId; - $accountventilated = new AccountingAccount($db); - $accountventilated->fetch($monCompte, ''); + $accountventilated = new AccountingAccount($db); + $accountventilated->fetch($monCompte, ''); - dol_syslog("accountancy/customer/list.php sql=".$sql, LOG_DEBUG); - if ($db->query($sql)) { - $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("VentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'; - $ok++; - } else { - $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NotVentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'.$sql.'
'; - $ko++; - } - } + dol_syslog("accountancy/customer/list.php sql=".$sql, LOG_DEBUG); + if ($db->query($sql)) { + $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("VentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'; + $ok++; + } else { + $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NotVentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'.$sql.'
'; + $ko++; + } + } - $cpt++; - } - $msg .= '
'; - $msg .= '
'.$langs->trans("EndProcessing").'
'; - } + $cpt++; + } + $msg .= '
'; + $msg .= '
'.$langs->trans("EndProcessing").'
'; + } } @@ -199,8 +199,8 @@ if (empty($chartaccountcode)) { print $langs->trans("ErrorChartOfAccountSystemNotSelected"); // End of page - llxFooter(); - $db->close(); + llxFooter(); + $db->close(); exit; } @@ -236,28 +236,28 @@ if ($search_societe) { $sql .= natural_search('s.nom', $search_societe); } if ($search_lineid) { - $sql .= natural_search("l.rowid", $search_lineid, 1); + $sql .= natural_search("l.rowid", $search_lineid, 1); } if (strlen(trim($search_invoice))) { - $sql .= natural_search("f.ref", $search_invoice); + $sql .= natural_search("f.ref", $search_invoice); } if (strlen(trim($search_ref))) { - $sql .= natural_search("p.ref", $search_ref); + $sql .= natural_search("p.ref", $search_ref); } if (strlen(trim($search_label))) { - $sql .= natural_search("p.label", $search_label); + $sql .= natural_search("p.label", $search_label); } if (strlen(trim($search_desc))) { - $sql .= natural_search("l.description", $search_desc); + $sql .= natural_search("l.description", $search_desc); } if (strlen(trim($search_amount))) { - $sql .= natural_search("l.total_ht", $search_amount, 1); + $sql .= natural_search("l.total_ht", $search_amount, 1); } if (strlen(trim($search_account))) { - $sql .= natural_search("aa.account_number", $search_account); + $sql .= natural_search("aa.account_number", $search_account); } if (strlen(trim($search_vat))) { - $sql .= natural_search("l.tva_tx", price2num($search_vat), 1); + $sql .= natural_search("l.tva_tx", price2num($search_vat), 1); } $sql .= dolSqlDateFilter('f.datef', $search_day, $search_month, $search_year); if (strlen(trim($search_country))) { @@ -295,13 +295,13 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { - $page = 0; - $offset = 0; - } + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql .= $db->plimit($limit + 1, $offset); @@ -336,9 +336,9 @@ if ($result) { if ($search_tvaintra) $param .= "&search_tvaintra=".urlencode($search_tvaintra); $arrayofmassactions = array( - 'ventil'=>$langs->trans("Ventilate") - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + 'ventil'=>$langs->trans("Ventilate") + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->mymodule->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); //if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); @@ -376,8 +376,8 @@ if ($result) { print ''; print ''; if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { - print ''; - } + print ''; + } print ''; $formother->select_year($search_year, 'search_year', 1, 20, 5); print ''; @@ -425,7 +425,7 @@ if ($result) { $isSellerInEEC = isInEEC($mysoc); - $accountingaccount_codetotid_cache = array(); + $accountingaccount_codetotid_cache = array(); while ($i < min($num_lines, $limit)) { $objp = $db->fetch_object($result); @@ -464,29 +464,29 @@ if ($result) { $code_sell_p_notset = ''; $objp->aarowid_suggest = ''; // Will be set later - $isBuyerInEEC = isInEEC($objp); + $isBuyerInEEC = isInEEC($objp); - // Search suggested default account for product/service - $suggestedaccountingaccountbydefaultfor = ''; - if ($objp->type_l == 1) { - if ($objp->country_code == $mysoc->country_code || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) - $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); - $suggestedaccountingaccountbydefaultfor = ''; - } else { - if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with a VAT + // Search suggested default account for product/service + $suggestedaccountingaccountbydefaultfor = ''; + if ($objp->type_l == 1) { + if ($objp->country_code == $mysoc->country_code || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = ''; + } else { + if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with a VAT $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); $suggestedaccountingaccountbydefaultfor = 'eecwithvat'; - } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number - $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); - $suggestedaccountingaccountbydefaultfor = 'eecwithoutvatnumber'; + } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eecwithoutvatnumber'; } elseif ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale - $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT : ''); - $suggestedaccountingaccountbydefaultfor = 'eec'; - } else { // Foreign sale - $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT : ''); - $suggestedaccountingaccountbydefaultfor = 'export'; - } - } + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eec'; + } else { // Foreign sale + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'export'; + } + } } elseif ($objp->type_l == 0) { if ($objp->country_code == $mysoc->country_code || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : ''); @@ -512,28 +512,36 @@ if ($result) { // Search suggested account for product/service (similar code exists in page index.php to make automatic binding) $suggestedaccountingaccountfor = ''; if (($objp->country_code == $mysoc->country_code) || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) - $objp->code_sell_p = $objp->code_sell; - $objp->aarowid_suggest = $objp->aarowid; - $suggestedaccountingaccountfor = ''; - } else { - if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with VAT + $objp->code_sell_p = $objp->code_sell; + $objp->aarowid_suggest = $objp->aarowid; + $suggestedaccountingaccountfor = ''; + } else { + if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with VAT $objp->code_sell_p = $objp->code_sell; $objp->aarowid_suggest = $objp->aarowid; $suggestedaccountingaccountfor = 'eecwithvat'; - } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number - $objp->code_sell_p = $objp->code_sell; - $objp->aarowid_suggest = $objp->aarowid; // There is a doubt for this case. Is it an error on vat or we just forgot to fill vat number ? - $suggestedaccountingaccountfor = 'eecwithoutvatnumber'; + } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number + $objp->code_sell_p = $objp->code_sell; + $objp->aarowid_suggest = $objp->aarowid; // There is a doubt for this case. Is it an error on vat or we just forgot to fill vat number ? + $suggestedaccountingaccountfor = 'eecwithoutvatnumber'; } elseif ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale - $objp->code_sell_p = $objp->code_sell_intra; - $objp->aarowid_suggest = $objp->aarowid_intra; - $suggestedaccountingaccountfor = 'eec'; - } else { // Foreign sale - $objp->code_sell_p = $objp->code_sell_export; - $objp->aarowid_suggest = $objp->aarowid_export; - $suggestedaccountingaccountfor = 'export'; - } - } + $objp->code_sell_p = $objp->code_sell_intra; + $objp->aarowid_suggest = $objp->aarowid_intra; + $suggestedaccountingaccountfor = 'eec'; + } else { // Foreign sale + $objp->code_sell_p = $objp->code_sell_export; + $objp->aarowid_suggest = $objp->aarowid_export; + $suggestedaccountingaccountfor = 'export'; + } + } + + // Manage Deposit + if ($objp->description == "(DEPOSIT)") { + $accountdeposittoventilated = new AccountingAccount($db); + $accountdeposittoventilated->fetch('', $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT, 1); + $objp->code_sell_l = $accountdeposittoventilated->ref; + $objp->aarowid_suggest = $accountdeposittoventilated->rowid; + } if (!empty($objp->code_sell_p)) { // Value was defined previously @@ -585,32 +593,32 @@ if ($result) { print ''.$thirdpartystatic->getNomUrl(1, 'customer').''; // Country - print ''; - $labelcountry = ($objp->country_code && ($langs->trans("Country".$objp->country_code) != "Country".$objp->country_code)) ? $langs->trans("Country".$objp->country_code) : $objp->country_label; - print $labelcountry; - print ''; + print ''; + $labelcountry = ($objp->country_code && ($langs->trans("Country".$objp->country_code) != "Country".$objp->country_code)) ? $langs->trans("Country".$objp->country_code) : $objp->country_label; + print $labelcountry; + print ''; print ''.$objp->tva_intra.''; // Found accounts print ''; - $s = ''.(($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': '; - $shelp = ''; - if ($suggestedaccountingaccountbydefaultfor == 'eec') $shelp .= $langs->trans("SaleEEC"); - elseif ($suggestedaccountingaccountbydefaultfor == 'export') $shelp .= $langs->trans("SaleExport"); - $s .= ($objp->code_sell_l > 0 ? length_accountg($objp->code_sell_l) : ''.$langs->trans("NotDefined").''); - print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1); - if ($objp->product_id > 0) + $s = ''.(($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': '; + $shelp = ''; + if ($suggestedaccountingaccountbydefaultfor == 'eec') $shelp .= $langs->trans("SaleEEC"); + elseif ($suggestedaccountingaccountbydefaultfor == 'export') $shelp .= $langs->trans("SaleExport"); + $s .= ($objp->code_sell_l > 0 ? length_accountg($objp->code_sell_l) : ''.$langs->trans("NotDefined").''); + print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1); + if ($objp->product_id > 0) { - print '
'; - $s = ''.(($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': '; - $shelp = ''; - if ($suggestedaccountingaccountfor == 'eec') $shelp = $langs->trans("SaleEEC"); - elseif ($suggestedaccountingaccountfor == 'eecwithvat') $shelp = $langs->trans("SaleEECWithVAT"); - elseif ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') $shelp = $langs->trans("SaleEECWithoutVATNumber"); - elseif ($suggestedaccountingaccountfor == 'export') $shelp = $langs->trans("SaleExport"); - $s .= (empty($objp->code_sell_p) ? ''.$langs->trans("NotDefined").'' : length_accountg($objp->code_sell_p)); - print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1); + print '
'; + $s = ''.(($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': '; + $shelp = ''; + if ($suggestedaccountingaccountfor == 'eec') $shelp = $langs->trans("SaleEEC"); + elseif ($suggestedaccountingaccountfor == 'eecwithvat') $shelp = $langs->trans("SaleEECWithVAT"); + elseif ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') $shelp = $langs->trans("SaleEECWithoutVATNumber"); + elseif ($suggestedaccountingaccountfor == 'export') $shelp = $langs->trans("SaleExport"); + $s .= (empty($objp->code_sell_p) ? ''.$langs->trans("NotDefined").'' : length_accountg($objp->code_sell_p)); + print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1); } print ''; diff --git a/htdocs/accountancy/expensereport/lines.php b/htdocs/accountancy/expensereport/lines.php index 6135a213115..4fdc29b2c0f 100644 --- a/htdocs/accountancy/expensereport/lines.php +++ b/htdocs/accountancy/expensereport/lines.php @@ -264,7 +264,7 @@ if ($result) { print ''; print ''; print ''; - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print ''; } print ''; @@ -287,7 +287,7 @@ if ($result) { print_liste_field_titre("Employees", $_SERVER['PHP_SELF'], "u.login", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("LineId", $_SERVER["PHP_SELF"], "erd.rowid", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("ExpenseReport", $_SERVER["PHP_SELF"], "er.ref", "", $param, '', $sortfield, $sortorder); - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print_liste_field_titre("DateValidation", $_SERVER["PHP_SELF"], "er.date_valid", "", $param, '', $sortfield, $sortorder, 'center '); } print_liste_field_titre("DateOfLine", $_SERVER["PHP_SELF"], "erd.date, erd.rowid", "", $param, '', $sortfield, $sortorder, 'center '); @@ -341,7 +341,7 @@ if ($result) { print ''.$expensereportstatic->getNomUrl(1).''; // Date validation - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print ''.dol_print_date($db->jdate($objp->date_valid), 'day').''; } diff --git a/htdocs/accountancy/expensereport/list.php b/htdocs/accountancy/expensereport/list.php index 0a5bef0c57e..76d13b99805 100644 --- a/htdocs/accountancy/expensereport/list.php +++ b/htdocs/accountancy/expensereport/list.php @@ -303,7 +303,7 @@ if ($result) { print ''; print ''; print ''; - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print ''; } print ''; @@ -327,7 +327,7 @@ if ($result) { print_liste_field_titre("Employee", $_SERVER['PHP_SELF'], "u.login", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("LineId", $_SERVER["PHP_SELF"], "erd.rowid", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("ExpenseReport", $_SERVER["PHP_SELF"], "er.ref", "", $param, '', $sortfield, $sortorder); - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print_liste_field_titre("DateValidation", $_SERVER["PHP_SELF"], "er.date_valid", "", $param, '', $sortfield, $sortorder, 'center '); } print_liste_field_titre("DateOfLine", $_SERVER["PHP_SELF"], "erd.date, erd.rowid", "", $param, '', $sortfield, $sortorder, 'center '); @@ -381,7 +381,7 @@ if ($result) { print ''.$expensereport_static->getNomUrl(1).''; // Date validation - if (! empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { + if (!empty($conf->global->ACCOUNTANCY_USE_EXPENSE_REPORT_VALIDATION_DATE)) { print ''.dol_print_date($db->jdate($objp->date_valid), 'day').''; } diff --git a/htdocs/accountancy/supplier/list.php b/htdocs/accountancy/supplier/list.php index 53c987e0189..9e0b64160e1 100644 --- a/htdocs/accountancy/supplier/list.php +++ b/htdocs/accountancy/supplier/list.php @@ -144,48 +144,48 @@ if (empty($reshook)) if ($massaction == 'ventil') { - $msg = ''; + $msg = ''; - //print '
' . $langs->trans("Processing") . '...
'; - if (!empty($mesCasesCochees)) { - $msg = '
'.$langs->trans("SelectedLines").': '.count($mesCasesCochees).'
'; - $msg .= '
'; - $cpt = 0; - $ok = 0; - $ko = 0; + //print '
' . $langs->trans("Processing") . '...
'; + if (!empty($mesCasesCochees)) { + $msg = '
'.$langs->trans("SelectedLines").': '.count($mesCasesCochees).'
'; + $msg .= '
'; + $cpt = 0; + $ok = 0; + $ko = 0; - foreach ($mesCasesCochees as $maLigneCochee) { - $maLigneCourante = explode("_", $maLigneCochee); - $monId = $maLigneCourante[0]; - $monCompte = GETPOST('codeventil'.$monId); + foreach ($mesCasesCochees as $maLigneCochee) { + $maLigneCourante = explode("_", $maLigneCochee); + $monId = $maLigneCourante[0]; + $monCompte = GETPOST('codeventil'.$monId); - if ($monCompte <= 0) - { - $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'
'; - $ko++; - } else { - $sql = " UPDATE ".MAIN_DB_PREFIX."facture_fourn_det"; - $sql .= " SET fk_code_ventilation = ".$monCompte; - $sql .= " WHERE rowid = ".$monId; + if ($monCompte <= 0) + { + $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'
'; + $ko++; + } else { + $sql = " UPDATE ".MAIN_DB_PREFIX."facture_fourn_det"; + $sql .= " SET fk_code_ventilation = ".$monCompte; + $sql .= " WHERE rowid = ".$monId; - $accountventilated = new AccountingAccount($db); - $accountventilated->fetch($monCompte, ''); + $accountventilated = new AccountingAccount($db); + $accountventilated->fetch($monCompte, ''); - dol_syslog('accountancy/supplier/list.php:: sql='.$sql, LOG_DEBUG); - if ($db->query($sql)) { - $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("VentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'; - $ok++; - } else { - $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NotVentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'.$sql.'
'; - $ko++; - } - } + dol_syslog('accountancy/supplier/list.php:: sql='.$sql, LOG_DEBUG); + if ($db->query($sql)) { + $msg .= '
'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("VentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'; + $ok++; + } else { + $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NotVentilatedinAccount").' : '.length_accountg($accountventilated->account_number).'
'.$sql.'
'; + $ko++; + } + } - $cpt++; - } - $msg .= '
'; - $msg .= '
'.$langs->trans("EndProcessing").'
'; - } + $cpt++; + } + $msg .= '
'; + $msg .= '
'.$langs->trans("EndProcessing").'
'; + } } @@ -203,8 +203,8 @@ if (empty($chartaccountcode)) { print $langs->trans("ErrorChartOfAccountSystemNotSelected"); // End of page - llxFooter(); - $db->close(); + llxFooter(); + $db->close(); exit; } @@ -240,28 +240,28 @@ if ($search_societe) { $sql .= natural_search('s.nom', $search_societe); } if ($search_lineid) { - $sql .= natural_search("l.rowid", $search_lineid, 1); + $sql .= natural_search("l.rowid", $search_lineid, 1); } if (strlen(trim($search_invoice))) { - $sql .= natural_search("f.ref", $search_invoice); + $sql .= natural_search("f.ref", $search_invoice); } if (strlen(trim($search_label))) { $sql .= natural_search("f.libelle", $search_label); } if (strlen(trim($search_ref))) { - $sql .= natural_search("p.ref", $search_ref); + $sql .= natural_search("p.ref", $search_ref); } if (strlen(trim($search_desc))) { - $sql .= natural_search("l.description", $search_desc); + $sql .= natural_search("l.description", $search_desc); } if (strlen(trim($search_amount))) { - $sql .= natural_search("l.total_ht", $search_amount, 1); + $sql .= natural_search("l.total_ht", $search_amount, 1); } if (strlen(trim($search_account))) { - $sql .= natural_search("aa.account_number", $search_account); + $sql .= natural_search("aa.account_number", $search_account); } if (strlen(trim($search_vat))) { - $sql .= natural_search("l.tva_tx", price2num($search_vat), 1); + $sql .= natural_search("l.tva_tx", price2num($search_vat), 1); } $sql .= dolSqlDateFilter('f.datef', $search_day, $search_month, $search_year); if (strlen(trim($search_country))) { @@ -299,13 +299,13 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { - $page = 0; - $offset = 0; - } + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql .= $db->plimit($limit + 1, $offset); @@ -337,9 +337,9 @@ if ($result) { if ($search_tvaintra) $param .= "&search_tvaintra=".urlencode($search_tvaintra); $arrayofmassactions = array( - 'ventil'=>$langs->trans("Ventilate") - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + 'ventil'=>$langs->trans("Ventilate") + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->mymodule->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); //if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); @@ -572,12 +572,12 @@ if ($result) { print ''.$thirdpartystatic->getNomUrl(1, 'supplier').''; // Country - print ''; - $labelcountry = ($objp->country_code && ($langs->trans("Country".$objp->country_code) != "Country".$objp->country_code)) ? $langs->trans("Country".$objp->country_code) : $objp->country_label; - print $labelcountry; - print ''; + print ''; + $labelcountry = ($objp->country_code && ($langs->trans("Country".$objp->country_code) != "Country".$objp->country_code)) ? $langs->trans("Country".$objp->country_code) : $objp->country_label; + print $labelcountry; + print ''; - // VAT Num + // VAT Num print ''.$objp->tva_intra.''; // Found accounts diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php index 439854229e0..c3c14171386 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -1738,7 +1738,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { $genallowed = $user->rights->adherent->lire; $delallowed = $user->rights->adherent->creer; - print $formfile->showdocuments('member', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $object->default_lang, '', $object); + print $formfile->showdocuments('member', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $object->default_lang, '', $object); $somethingshown = $formfile->numoffiles; // Show links to link elements diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 82cdf7794a4..8b643dcbe92 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -1724,7 +1724,7 @@ class Adherent extends CommonObject // Generate PDF (whatever is option MAIN_DISABLE_PDF_AUTOUPDATE) so we can include it into email //if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - $invoice->generateDocument($invoice->modelpdf, $outputlangs); + $invoice->generateDocument($invoice->model_pdf, $outputlangs); } } @@ -2257,8 +2257,8 @@ class Adherent extends CommonObject if (!dol_strlen($modele)) { $modele = 'standard'; - if ($this->modelpdf) { - $modele = $this->modelpdf; + if ($this->model_pdf) { + $modele = $this->model_pdf; } elseif (!empty($conf->global->ADHERENT_ADDON_PDF)) { $modele = $conf->global->ADHERENT_ADDON_PDF; } diff --git a/htdocs/adherents/class/adherentstats.class.php b/htdocs/adherents/class/adherentstats.class.php index b3029a6bd55..c953d929442 100644 --- a/htdocs/adherents/class/adherentstats.class.php +++ b/htdocs/adherents/class/adherentstats.class.php @@ -68,7 +68,7 @@ class AdherentStats extends Stats $this->field = 'subscription'; - $this->where .= " m.statut != 0"; + $this->where .= " m.statut != -1"; $this->where .= " AND p.fk_adherent = m.rowid AND m.entity IN (".getEntity('adherent').")"; //if (!$user->rights->societe->client->voir && !$user->socid) $this->where .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; if ($this->memberid) { diff --git a/htdocs/adherents/class/api_memberstypes.class.php b/htdocs/adherents/class/api_memberstypes.class.php index 6930b96e656..a5923914187 100644 --- a/htdocs/adherents/class/api_memberstypes.class.php +++ b/htdocs/adherents/class/api_memberstypes.class.php @@ -293,7 +293,7 @@ class MembersTypes extends DolibarrApi unset($object->cond_reglement); unset($object->fk_delivery_address); unset($object->shipping_method_id); - unset($object->modelpdf); + unset($object->model_pdf); unset($object->fk_account); unset($object->note_public); unset($object->note_private); diff --git a/htdocs/adherents/stats/byproperties.php b/htdocs/adherents/stats/byproperties.php index 8f9a46228c6..90187e483dc 100644 --- a/htdocs/adherents/stats/byproperties.php +++ b/htdocs/adherents/stats/byproperties.php @@ -61,16 +61,16 @@ print load_fiche_titre($title, '', 'object_group'); dol_mkdir($dir); -$tab = 'byproperties'; - $data = array(); -$sql .= "SELECT COUNT(d.rowid) as nb, MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate, d.morphy as code"; + +$sql = "SELECT COUNT(DISTINCT d.rowid) as nb, COUNT(s.rowid) as nbsubscriptions,"; +$sql .= " MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate,"; +$sql .= " d.morphy as code"; $sql .= " FROM ".MAIN_DB_PREFIX."adherent as d"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."subscription as s ON s.fk_adherent = d.rowid"; $sql .= " WHERE d.entity IN (".getEntity('adherent').")"; -$sql .= " AND d.statut = 1"; +$sql .= " AND d.statut != -1"; // Not draft $sql .= " GROUP BY d.morphy"; - $foundphy = $foundmor = 0; // Define $data array @@ -85,7 +85,38 @@ if ($resql) { if ($obj->code == 'phy') $foundphy++; if ($obj->code == 'mor') $foundmor++; - $data[] = array('label'=>$obj->code, 'nb'=>$obj->nb, 'lastdate'=>$db->jdate($obj->lastdate), 'lastsubscriptiondate'=>$db->jdate($obj->lastsubscriptiondate)); + $data[$obj->code] = array('label'=>$obj->code, 'nb'=>$obj->nb, 'nbsubscriptions'=>$obj->nbsubscriptions, 'lastdate'=>$db->jdate($obj->lastdate), 'lastsubscriptiondate'=>$db->jdate($obj->lastsubscriptiondate)); + + $i++; + } + $db->free($resql); +} else { + dol_print_error($db); +} + +$sql = "SELECT COUNT(DISTINCT d.rowid) as nb, COUNT(s.rowid) as nbsubscriptions,"; +$sql .= " MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate,"; +$sql .= " d.morphy as code"; +$sql .= " FROM ".MAIN_DB_PREFIX."adherent as d"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."subscription as s ON s.fk_adherent = d.rowid"; +$sql .= " WHERE d.entity IN (".getEntity('adherent').")"; +$sql .= " AND d.statut >= 1"; // Active (not draft=-1, not resiliated=0) +$sql .= " GROUP BY d.morphy"; +$foundphy = $foundmor = 0; + +// Define $data array +dol_syslog("Count member still active", LOG_DEBUG); +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $db->fetch_object($resql); + + if ($obj->code == 'phy') $foundphy++; + if ($obj->code == 'mor') $foundmor++; + + $data[$obj->code]['nbactive'] = $obj->nb; $i++; } @@ -102,30 +133,38 @@ dol_fiche_head($head, 'statsbyproperties', $langs->trans("Statistics"), -1, 'use // Print title if (!count($data)) { - print $langs->trans("NoValidatedMemberYet").'
'; + print ''.$langs->trans("NoValidatedMemberYet").'
'; print '
'; } else { - print $langs->trans("MembersByNature").'
'; + print ''.$langs->trans("MembersByNature").'
'; print '
'; } // Print array print ''; print ''; -print ''; -print ''; +print ''; +print ''; +print ''; print ''; +print ''; print ''; print ''; -if (!$foundphy) $data[] = array('label'=>'phy', 'nb'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); -if (!$foundmor) $data[] = array('label'=>'mor', 'nb'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); +if (!$foundphy) $data[] = array('label'=>'phy', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); +if (!$foundmor) $data[] = array('label'=>'mor', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); foreach ($data as $val) { + $nb = $val['nb']; + $nbsubscriptions = $val['nbsubscriptions']; + $nbactive = $val['nbactive']; + print ''; print ''; - print ''; + print ''; + print ''; print ''; + print ''; print ''; print ''; } diff --git a/htdocs/adherents/stats/geo.php b/htdocs/adherents/stats/geo.php index 62f4cd63dca..edb37a9d4a8 100644 --- a/htdocs/adherents/stats/geo.php +++ b/htdocs/adherents/stats/geo.php @@ -74,12 +74,12 @@ if ($mode) { $tab = 'statscountry'; $data = array(); - $sql .= "SELECT COUNT(d.rowid) as nb, MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate, c.code, c.label"; + $sql .= "SELECT COUNT(DISTINCT d.rowid) as nb, COUNT(s.rowid) as nbsubscriptions, MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate, c.code, c.label"; $sql .= " FROM ".MAIN_DB_PREFIX."adherent as d"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c on d.country = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."subscription as s ON s.fk_adherent = d.rowid"; $sql .= " WHERE d.entity IN (".getEntity('adherent').")"; - $sql .= " AND d.statut = 1"; + $sql .= " AND d.statut != -1"; $sql .= " GROUP BY c.label, c.code"; //print $sql; } @@ -90,14 +90,14 @@ if ($mode) { $tab = 'statsstate'; $data = array(); - $sql .= "SELECT COUNT(d.rowid) as nb, MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate, co.code, co.label, c.nom as label2"; // + $sql .= "SELECT COUNT(DISTINCT d.rowid) as nb, COUNT(s.rowid) as nbsubscriptions, MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate, co.code, co.label, c.nom as label2"; // $sql .= " FROM ".MAIN_DB_PREFIX."adherent as d"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as c on d.state_id = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_regions as r on c.fk_region = r.code_region"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co on d.country = co.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."subscription as s ON s.fk_adherent = d.rowid"; $sql .= " WHERE d.entity IN (".getEntity('adherent').")"; - $sql .= " AND d.statut = 1"; + $sql .= " AND d.statut != -1"; $sql .= " GROUP BY co.label, co.code, c.nom"; //print $sql; } @@ -107,14 +107,14 @@ if ($mode) { $tab = 'statsregion'; //onglet $data = array(); //tableau de donnée - $sql .= "SELECT COUNT(d.rowid) as nb, MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate, co.code, co.label, r.nom as label2"; + $sql .= "SELECT COUNT(DISTINCT d.rowid) as nb, COUNT(s.rowid) as nbsubscriptions, MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate, co.code, co.label, r.nom as label2"; $sql .= " FROM ".MAIN_DB_PREFIX."adherent as d"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as c on d.state_id = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_regions as r on c.fk_region = r.code_region"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co on d.country = co.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."subscription as s ON s.fk_adherent = d.rowid"; $sql .= " WHERE d.entity IN (".getEntity('adherent').")"; - $sql .= " AND d.statut = 1"; + $sql .= " AND d.statut != -1"; $sql .= " GROUP BY co.label, co.code, r.nom"; //+ //print $sql; } @@ -124,12 +124,12 @@ if ($mode) { $tab = 'statstown'; $data = array(); - $sql .= "SELECT COUNT(d.rowid) as nb, MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate, c.code, c.label, d.town as label2"; + $sql .= "SELECT COUNT(DISTINCT d.rowid) as nb, COUNT(s.rowid) as nbsubscriptions, MAX(d.datevalid) as lastdate, MAX(s.dateadh) as lastsubscriptiondate, c.code, c.label, d.town as label2"; $sql .= " FROM ".MAIN_DB_PREFIX."adherent as d"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c on d.country = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."subscription as s ON s.fk_adherent = d.rowid"; $sql .= " WHERE d.entity IN (".getEntity('adherent').")"; - $sql .= " AND d.statut = 1"; + $sql .= " AND d.statut != -1"; $sql .= " GROUP BY c.label, c.code, d.town"; //print $sql; } @@ -204,12 +204,12 @@ if ($mode && !count($data)) { print $langs->trans("NoValidatedMemberYet").'
'; print '
'; } else { - if ($mode == 'memberbycountry') print $langs->trans("MembersByCountryDesc").'
'; - elseif ($mode == 'memberbystate') print $langs->trans("MembersByStateDesc").'
'; - elseif ($mode == 'memberbytown') print $langs->trans("MembersByTownDesc").'
'; - elseif ($mode == 'memberbyregion') print $langs->trans("MembersByRegion").'
'; //+ + if ($mode == 'memberbycountry') print ''.$langs->trans("MembersByCountryDesc").'
'; + elseif ($mode == 'memberbystate') print ''.$langs->trans("MembersByStateDesc").'
'; + elseif ($mode == 'memberbytown') print ''.$langs->trans("MembersByTownDesc").'
'; + elseif ($mode == 'memberbyregion') print ''.$langs->trans("MembersByRegion").'
'; //+ else { - print $langs->trans("MembersStatisticsDesc").'
'; + print ''.$langs->trans("MembersStatisticsDesc").'
'; print '
'; print ''.$langs->trans("MembersStatisticsByCountries").'
'; print '
'; @@ -277,7 +277,7 @@ if ($mode) { print ''; print ''; if ($label2) print ''; - print ''; + print ''; print ''; print ''; print ''; diff --git a/htdocs/adherents/stats/index.php b/htdocs/adherents/stats/index.php index 9177b4783a2..c6748538264 100644 --- a/htdocs/adherents/stats/index.php +++ b/htdocs/adherents/stats/index.php @@ -176,9 +176,9 @@ foreach ($data as $val) { $oldyear--; print ''; print ''; print ''; print ''; diff --git a/htdocs/adherents/subscription/card.php b/htdocs/adherents/subscription/card.php index b7e54238c4c..3fad8c9db14 100644 --- a/htdocs/adherents/subscription/card.php +++ b/htdocs/adherents/subscription/card.php @@ -370,7 +370,7 @@ if ($rowid && $action != 'edit') { $genallowed = $user->rights->facture->lire; $delallowed = $user->rights->facture->creer; - print $formfile->showdocuments('facture', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + print $formfile->showdocuments('facture', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); $somethingshown = $formfile->numoffiles; */ // Show links to link elements diff --git a/htdocs/admin/bank.php b/htdocs/admin/bank.php index 9b66b8e5c7f..b43daca20d9 100644 --- a/htdocs/admin/bank.php +++ b/htdocs/admin/bank.php @@ -51,147 +51,147 @@ $type = 'bankaccount'; // Order display of bank account if ($action == 'setbankorder') { - if (dolibarr_set_const($db, "BANK_SHOW_ORDER_OPTION", GETPOST('value', 'alpha'), 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_SHOW_ORDER_OPTION", GETPOST('value', 'alpha'), 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } // Auto report last num releve on conciliate if ($action == 'setreportlastnumreleve') { - if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 1, 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 1, 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } elseif ($action == 'unsetreportlastnumreleve') { - if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 0, 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 0, 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } // Colorize movements if ($action == 'setbankcolorizemovement') { - if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 1, 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 1, 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } elseif ($action == 'unsetbankcolorizemovement') { - if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 0, 'chaine', 0, '', $conf->entity) > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } else { - dol_print_error($db); - } + if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 0, 'chaine', 0, '', $conf->entity) > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } else { + dol_print_error($db); + } } if ($actionsave) { - $db->begin(); + $db->begin(); - $i = 1; $errorsaved = 0; - $error = 0; + $i = 1; $errorsaved = 0; + $error = 0; - // Save colors - while ($i <= 2) - { - $color = GETPOST('BANK_COLORIZE_MOVEMENT_COLOR'.$i, 'alpha'); - if ($color == '-1') $color = ''; + // Save colors + while ($i <= 2) + { + $color = GETPOST('BANK_COLORIZE_MOVEMENT_COLOR'.$i, 'alpha'); + if ($color == '-1') $color = ''; - $res = dolibarr_set_const($db, 'BANK_COLORIZE_MOVEMENT_COLOR'.$i, $color, 'chaine', 0, '', $conf->entity); - if (!$res > 0) $error++; - $i++; - } + $res = dolibarr_set_const($db, 'BANK_COLORIZE_MOVEMENT_COLOR'.$i, $color, 'chaine', 0, '', $conf->entity); + if (!$res > 0) $error++; + $i++; + } - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - $db->rollback(); - if (empty($errorsaved)) setEventMessages($langs->trans("Error"), null, 'errors'); - } + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + $db->rollback(); + if (empty($errorsaved)) setEventMessages($langs->trans("Error"), null, 'errors'); + } } if ($action == 'specimen') { - $modele = GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); - if ($modele == 'sepamandate') { - $object = new CompanyBankAccount($db); - } else { - $object = new Account($db); - } - $object->initAsSpecimen(); + if ($modele == 'sepamandate') { + $object = new CompanyBankAccount($db); + } else { + $object = new Account($db); + } + $object->initAsSpecimen(); - // 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/bank/doc/pdf_".$modele.".modules.php", 0); - if (file_exists($file)) { - $filefound = 1; - $classname = "pdf_".$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/bank/doc/pdf_".$modele.".modules.php", 0); + if (file_exists($file)) { + $filefound = 1; + $classname = "pdf_".$modele; + break; + } + } - if ($filefound) { - require_once $file; + if ($filefound) { + require_once $file; - $module = new $classname($db); + $module = new $classname($db); - if ($module->write_file($object, $langs) > 0) { - header("Location: ".DOL_URL_ROOT."/document.php?modulepart=bank&file=SPECIMEN.pdf"); - return; - } else { - setEventMessages($module->error, null, 'errors'); - dol_syslog($module->error, LOG_ERR); - } - } else { - setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); - dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); - } + if ($module->write_file($object, $langs) > 0) { + header("Location: ".DOL_URL_ROOT."/document.php?modulepart=bank&file=SPECIMEN.pdf"); + return; + } else { + setEventMessages($module->error, null, 'errors'); + dol_syslog($module->error, LOG_ERR); + } + } else { + setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); + dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); + } } // Activate a model if ($action == 'set') { - $ret = addDocumentModel($value, $type, $label, $scandir); + $ret = addDocumentModel($value, $type, $label, $scandir); } elseif ($action == 'del') { - $ret = delDocumentModel($value, $type); - if ($ret > 0) { - if ($conf->global->BANKADDON_PDF == "$value") - dolibarr_del_const($db, 'BANKADDON_PDF', $conf->entity); - } + $ret = delDocumentModel($value, $type); + if ($ret > 0) { + if ($conf->global->BANKADDON_PDF == "$value") + dolibarr_del_const($db, 'BANKADDON_PDF', $conf->entity); + } } // Set default model elseif ($action == 'setdoc') { - if (dolibarr_set_const($db, "BANKADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { - // The constant that was read before the new set - // We therefore requires a variable to have a coherent view - $conf->global->BANKADDON_PDF = $value; - } + if (dolibarr_set_const($db, "BANKADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { + // The constant that was read before the new set + // We therefore requires a variable to have a coherent view + $conf->global->BANKADDON_PDF = $value; + } - // On active le modele - $ret = delDocumentModel($value, $type); - if ($ret > 0) { - $ret = addDocumentModel($value, $type, $label, $scandir); - } + // On active le modele + $ret = delDocumentModel($value, $type); + if ($ret > 0) { + $ret = addDocumentModel($value, $type, $label, $scandir); + } } diff --git a/htdocs/admin/emailcollector_card.php b/htdocs/admin/emailcollector_card.php index 94a3d698c2a..f8129a887a8 100644 --- a/htdocs/admin/emailcollector_card.php +++ b/htdocs/admin/emailcollector_card.php @@ -670,12 +670,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Clone print '
'.$langs->trans("ToClone").'
'; - // Collect now - if (count($object->actions) > 0) { + // Collect now + if (count($object->actions) > 0) { print '
'.$langs->trans("CollectNow").'
'; - } else { - print '
'.$langs->trans("CollectNow").'
'; - } + } else { + print '
'.$langs->trans("CollectNow").'
'; + } print '
'.$langs->trans('Delete').'
'; } @@ -705,7 +705,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; $genallowed = $user->rights->emailcollector->read; // If you can read, you can build the PDF to read content $delallowed = $user->rights->emailcollector->create; // If you can create/edit, you can remove a file on card - print $formfile->showdocuments('emailcollector', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + print $formfile->showdocuments('emailcollector', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); */ /* // Show links to link elements diff --git a/htdocs/admin/expensereport_ik.php b/htdocs/admin/expensereport_ik.php index ebdc1f7ed59..840cf4d2681 100644 --- a/htdocs/admin/expensereport_ik.php +++ b/htdocs/admin/expensereport_ik.php @@ -35,13 +35,11 @@ $langs->loadLangs(array("admin", "trips", "errors", "other", "dict")); if (!$user->admin) accessforbidden(); -//Init error -$error = false; -$message = false; +$error = 0; $action = GETPOST('action', 'alpha'); $id = GETPOST('id', 'int'); -$offset = GETPOST('offset', 'int'); +$ikoffset = GETPOST('ikoffset', 'int'); $coef = GETPOST('coef', 'int'); $fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat'); @@ -59,10 +57,13 @@ if ($action == 'updateik') $expIk->setValues($_POST); $result = $expIk->create($user); - if ($result > 0) setEventMessages('SetupSaved', null, 'mesgs'); - - header('Location: '.$_SERVER['PHP_SELF']); - exit; + if ($result > 0) { + setEventMessages('SetupSaved', null, 'mesgs'); + header('Location: '.$_SERVER['PHP_SELF']); + exit; + } else { + setEventMessages($expIk->error, $expIk->errors, 'errors'); + } } elseif ($action == 'delete') // TODO add confirm { $expIk = new ExpenseReportIk($db); @@ -81,6 +82,7 @@ if ($action == 'updateik') $rangesbycateg = ExpenseReportIk::getAllRanges(); + /* * View */ @@ -90,12 +92,13 @@ llxHeader('', $langs->trans("ExpenseReportsSetup")); $form = new Form($db); $linkback = ''.$langs->trans("BackToModuleList").''; -print load_fiche_titre($langs->trans("ExpenseReportsIkSetup"), $linkback, 'title_setup'); +print load_fiche_titre($langs->trans("ExpenseReportsSetup"), $linkback, 'title_setup'); $head = expensereport_admin_prepare_head(); dol_fiche_head($head, 'expenseik', $langs->trans("ExpenseReportsIk"), -1, 'trip'); -echo $langs->trans('ExpenseReportIkDesc'); +echo ''.$langs->trans('ExpenseReportIkDesc').''; +print '

'; echo ''; @@ -136,21 +139,23 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) echo ''; // Label - echo ''; + echo ''; // Offset - echo ''; // Coef - echo ''; // Total for one - echo ''; + echo ''; // Action echo ''; echo ''; - echo ''; + echo ''; echo ''; echo ''; echo ''; @@ -184,7 +186,7 @@ if ($action != 'edit') echo ''; echo ''; echo ''; - echo ''; + echo ''; echo ''; echo ''; echo ''; @@ -207,7 +209,7 @@ echo '
'.$langs->trans("Nature").''.$langs->trans("NbOfMembers").''.$langs->trans("MemberNature").''.$langs->trans("NbOfMembers").' ('.$langs->trans("AllTime").')'.$langs->trans("NbOfActiveMembers").''.$langs->trans("LastMemberDate").''.$langs->trans("NbOfSubscriptions").''.$langs->trans("LatestSubscriptionDate").'
'.$memberstatic->getmorphylib($val['label']).''.$val['nb'].''.$nb.''.$nbactive.''.dol_print_date($val['lastdate'], 'dayhour').''.$nbsubscriptions.''.dol_print_date($val['lastsubscriptiondate'], 'dayhour').'
'.$label.''.$label2.''.$langs->trans("NbOfMembers").''.$langs->trans("NbOfMembers").' ('.$langs->trans("AllTime").')'.$langs->trans("LastMemberDate").''.$langs->trans("LatestSubscriptionDate").'
'; - print ''; + //print ''; print $oldyear; - print ''; + //print ''; print '00
['.$langs->trans('RangeNum', $tranche++).'] - '.$label.'['.$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->ikoffset; + } echo ''; - if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; + 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)).''.$langs->trans('expenseReportPrintExample', price($range->ik->ikoffset + 5 * $range->ik->coef)).''; @@ -161,8 +166,8 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) echo ''; echo ''; } else { - echo ''.img_edit().''; - if (!empty($range->ik->id)) echo ''.img_delete().''; + echo ''.img_edit().''; + if (!empty($range->ik->id)) echo ''.img_delete().''; // TODO add delete link } } diff --git a/htdocs/admin/expensereport_rules.php b/htdocs/admin/expensereport_rules.php index 337311b85e7..28d5b3341b1 100644 --- a/htdocs/admin/expensereport_rules.php +++ b/htdocs/admin/expensereport_rules.php @@ -138,6 +138,7 @@ $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 */ @@ -147,12 +148,13 @@ llxHeader('', $langs->trans("ExpenseReportsSetup")); $form = new Form($db); $linkback = ''.$langs->trans("BackToModuleList").''; -print load_fiche_titre($langs->trans("ExpenseReportsRulesSetup"), $linkback, 'title_setup'); +print load_fiche_titre($langs->trans("ExpenseReportsSetup"), $linkback, 'title_setup'); $head = expensereport_admin_prepare_head(); dol_fiche_head($head, 'expenserules', $langs->trans("ExpenseReportsRules"), -1, 'trip'); -echo $langs->trans('ExpenseReportRulesDesc'); +echo ''.$langs->trans('ExpenseReportRulesDesc').''; +print '

'; if ($action != 'edit') { @@ -164,7 +166,7 @@ if ($action != 'edit') echo '
'.$langs->trans('ExpenseReportApplyTo').''.$langs->trans('ExpenseReportDomain').''.$langs->trans('Type').''.$langs->trans('ExpenseReportLimitOn').''.$langs->trans('ExpenseReportDateStart').''.$langs->trans('ExpenseReportDateEnd').''.$form->selectarray('code_expense_rules_type', $tab_rules_type, '', 0).''.$form->selectDate(strtotime(date('Y-m-01', dol_now())), 'start', '', '', 0, '', 1, 0).''.$form->selectDate(strtotime(date('Y-m-t', dol_now())), 'end', '', '', 0, '', 1, 0).''.$conf->currency.' '.$conf->currency.''.$form->selectyesno('restrictive', 0, 1).'
'; echo ''; echo ''; -echo ''; +echo ''; echo ''; echo ''; echo ''; @@ -300,11 +302,11 @@ foreach ($rules as $rule) echo ''; - echo ''; + print '
'.$langs->trans('ExpenseReportApplyTo').''.$langs->trans('ExpenseReportDomain').''.$langs->trans('Type').''.$langs->trans('ExpenseReportLimitOn').''.$langs->trans('ExpenseReportDateStart').''.$langs->trans('ExpenseReportDateEnd').''; + echo ''; if ($object->id != $rule->id) { - echo ''.img_edit().' '; - echo ''.img_delete().''; + echo ''.img_edit().' '; + echo ''.img_delete().''; } else { echo ' '; echo ''.$langs->trans('Cancel').''; diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index c8c017c476e..edac3515b05 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -280,14 +280,12 @@ if ($action == 'edit') print ''; print '
'; - //Add user to select destinaries list - print ''.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''; - print $form->selectyesno('MAIN_MAIL_ENABLED_USER_DEST_SELECT', $conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT, 1); - print ''; + print '
'; - // Separator - print ' '; + print ''; + print ''; // Method print ''; - // Separator - print ''; + print '
'.$langs->trans("MAIN_MAIL_SENDMODE").'
'.$langs->trans("MAIN_MAIL_SENDMODE").''; @@ -456,8 +454,12 @@ if ($action == 'edit') print ''; print '
 
'; + + print '
'; + + print ''; + print ''; // From print ''; @@ -473,9 +475,6 @@ if ($action == 'edit') print $form->selectarray('MAIN_MAIL_DEFAULT_FROMTYPE', $liste, $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE, 0); print ''; - // Separator - print ''; - // From print ''; print ''; + // Add user to select destinaries list + print ''; + print '
'.$langs->trans("OtherOptions").'
'.$langs->trans("MAIN_MAIL_EMAIL_FROM", ini_get('sendmail_from') ?ini_get('sendmail_from') : $langs->transnoentities("Undefined")).'
 
'.$langs->trans("MAIN_MAIL_ERRORS_TO").'
'.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''; + print $form->selectyesno('MAIN_MAIL_ENABLED_USER_DEST_SELECT', $conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT, 1); + print '
'; dol_fiche_end(); @@ -520,17 +524,23 @@ if ($action == 'edit') } print ''; - //Add user to select destinaries list - print ''.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''.yn($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT).''; + print ''; - // Separator - print ' '; + print '
'; + + print ''; + print ''; // Method print ''; // Host server @@ -624,8 +634,16 @@ if ($action == 'edit') print ''; } - // Separator - print ''; + print '
'.$langs->trans("MAIN_MAIL_SENDMODE").'
'.$langs->trans("MAIN_MAIL_SENDMODE").''; $text = $listofmethods[$conf->global->MAIN_MAIL_SENDMODE]; if (empty($text)) $text = $langs->trans("Undefined").img_warning(); print $text; + + if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP)) { + print $form->textwithpicto('', $langs->trans("WarningPHPMail").'
'.$langs->trans("WarningPHPMailA").'
'.$langs->trans("WarningPHPMailB").'
'.$langs->trans("WarningPHPMailC"), 1, 'warning'); + } + print '
 
'; + + if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP)) { + print info_admin($langs->trans("WarningPHPMail").'
'.$langs->trans("WarningPHPMailA").'
'.$langs->trans("WarningPHPMailB").'
'.$langs->trans("WarningPHPMailC"), 0, 0, 'warning'); + } + + print '
'; + + print ''; + print ''; // From print ''; @@ -678,9 +696,6 @@ if ($action == 'edit') } print ''; - // Separator - print ''; - // Errors To print ''; print ''; + //Add user to select destinaries list + print ''; + print '
'.$langs->trans("OtherOptions").'
'.$langs->trans("MAIN_MAIL_EMAIL_FROM", ini_get('sendmail_from') ?ini_get('sendmail_from') : $langs->transnoentities("Undefined")).'
 
'.$langs->trans("MAIN_MAIL_ERRORS_TO").''.$conf->global->MAIN_MAIL_ERRORS_TO; @@ -699,6 +714,9 @@ if ($action == 'edit') } print '
'.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''.yn($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT).'
'; dol_fiche_end(); @@ -750,7 +768,7 @@ if ($action == 'edit') $text = ''; if ($conf->global->MAIN_MAIL_SENDMODE == 'mail') { - $text .= $langs->trans("WarningPHPMail"); // To encourage to use SMTPS + //$text .= $langs->trans("WarningPHPMail"); // To encourage to use SMTPS } if ($conf->global->MAIN_MAIL_SENDMODE == 'mail') diff --git a/htdocs/admin/mails_emailing.php b/htdocs/admin/mails_emailing.php index 7e6f9acae93..14dc0f687ae 100644 --- a/htdocs/admin/mails_emailing.php +++ b/htdocs/admin/mails_emailing.php @@ -121,7 +121,7 @@ $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 (version_compare(phpversion(), '7.0', '>=')) $listofmethods['swiftmailer'] = 'Swift Mailer socket library'; if ($action == 'edit') diff --git a/htdocs/admin/mails_ticket.php b/htdocs/admin/mails_ticket.php index 0a452d109ce..a11859efc89 100644 --- a/htdocs/admin/mails_ticket.php +++ b/htdocs/admin/mails_ticket.php @@ -120,7 +120,7 @@ $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 (version_compare(phpversion(), '7.0', '>=')) $listofmethods['swiftmailer'] = 'Swift Mailer socket library'; if ($action == 'edit') diff --git a/htdocs/admin/menus/edit.php b/htdocs/admin/menus/edit.php index b0514dfc975..04c1b79a5bc 100644 --- a/htdocs/admin/menus/edit.php +++ b/htdocs/admin/menus/edit.php @@ -40,8 +40,8 @@ $dirsmartphone = array(); $dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']); foreach ($dirmenus as $dirmenu) { - $dirstandard[] = $dirmenu.'standard'; - $dirsmartphone[] = $dirmenu.'smartphone'; + $dirstandard[] = $dirmenu.'standard'; + $dirsmartphone[] = $dirmenu.'smartphone'; } $action = GETPOST('action', 'aZ09'); @@ -66,192 +66,192 @@ if (GETPOST("menu_handler")) $menu_handler = GETPOST("menu_handler"); if ($action == 'update') { - if (!$cancel) - { - $leftmenu = ''; $mainmenu = ''; - if (GETPOST('menuIdParent', 'alpha') && !is_numeric(GETPOST('menuIdParent', 'alpha'))) - { - $tmp = explode('&', GETPOST('menuIdParent', 'alpha')); - foreach ($tmp as $s) - { - if (preg_match('/fk_mainmenu=/', $s)) - { - $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); - } - if (preg_match('/fk_leftmenu=/', $s)) - { - $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); - } - } - } + if (!$cancel) + { + $leftmenu = ''; $mainmenu = ''; + if (GETPOST('menuIdParent', 'alpha') && !is_numeric(GETPOST('menuIdParent', 'alpha'))) + { + $tmp = explode('&', GETPOST('menuIdParent', 'alpha')); + foreach ($tmp as $s) + { + if (preg_match('/fk_mainmenu=/', $s)) + { + $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); + } + if (preg_match('/fk_leftmenu=/', $s)) + { + $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); + } + } + } - $menu = new Menubase($db); - $result = $menu->fetch(GETPOST('menuId', 'int')); - if ($result > 0) - { - $menu->title = GETPOST('titre', 'alpha'); - $menu->leftmenu = GETPOST('leftmenu', 'aZ09'); - $menu->url = GETPOST('url', 'alpha'); - $menu->langs = GETPOST('langs', 'alpha'); - $menu->position = GETPOST('position', 'int'); - $menu->enabled = GETPOST('enabled', 'alpha'); - $menu->perms = GETPOST('perms', 'alpha'); - $menu->target = GETPOST('target', 'alpha'); - $menu->user = GETPOST('user', 'alpha'); - $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); - if (is_numeric(GETPOST('menuIdParent', 'alpha'))) - { - $menu->fk_menu = GETPOST('menuIdParent', 'alpha'); - } else { - if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; - else $menu->fk_menu = -1; - $menu->fk_mainmenu = $mainmenu; - $menu->fk_leftmenu = $leftmenu; - } + $menu = new Menubase($db); + $result = $menu->fetch(GETPOST('menuId', 'int')); + if ($result > 0) + { + $menu->title = GETPOST('titre', 'alpha'); + $menu->leftmenu = GETPOST('leftmenu', 'aZ09'); + $menu->url = GETPOST('url', 'alpha'); + $menu->langs = GETPOST('langs', 'alpha'); + $menu->position = GETPOST('position', 'int'); + $menu->enabled = GETPOST('enabled', 'alpha'); + $menu->perms = GETPOST('perms', 'alpha'); + $menu->target = GETPOST('target', 'alpha'); + $menu->user = GETPOST('user', 'alpha'); + $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); + if (is_numeric(GETPOST('menuIdParent', 'alpha'))) + { + $menu->fk_menu = GETPOST('menuIdParent', 'alpha'); + } else { + if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; + else $menu->fk_menu = -1; + $menu->fk_mainmenu = $mainmenu; + $menu->fk_leftmenu = $leftmenu; + } - $result = $menu->update($user); - if ($result > 0) - { - setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); - } else { - setEventMessages($menu->error, $menu->errors, 'errors'); - } - } else { - setEventMessages($menu->error, $menu->errors, 'errors'); - } - $action = "edit"; + $result = $menu->update($user); + if ($result > 0) + { + setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); + } else { + setEventMessages($menu->error, $menu->errors, 'errors'); + } + } else { + setEventMessages($menu->error, $menu->errors, 'errors'); + } + $action = "edit"; - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); - exit; - } else { - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); - exit; - } + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); + exit; + } else { + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); + exit; + } } if ($action == 'add') { - if ($cancel) - { - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); - exit; - } + if ($cancel) + { + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); + exit; + } - $leftmenu = ''; $mainmenu = ''; - if (GETPOST('menuId', 'alpha', 3) && !is_numeric(GETPOST('menuId', 'alpha', 3))) - { - $tmp = explode('&', GETPOST('menuId', 'alpha', 3)); - foreach ($tmp as $s) - { - if (preg_match('/fk_mainmenu=/', $s)) - { + $leftmenu = ''; $mainmenu = ''; + if (GETPOST('menuId', 'alpha', 3) && !is_numeric(GETPOST('menuId', 'alpha', 3))) + { + $tmp = explode('&', GETPOST('menuId', 'alpha', 3)); + foreach ($tmp as $s) + { + if (preg_match('/fk_mainmenu=/', $s)) + { $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); - } - if (preg_match('/fk_leftmenu=/', $s)) - { - $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); - } - } - } + } + if (preg_match('/fk_leftmenu=/', $s)) + { + $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); + } + } + } - $langs->load("errors"); + $langs->load("errors"); - $error = 0; - if (!$error && !$_POST['menu_handler']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("MenuHandler")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['type']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Type")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['url']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['titre']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && $_POST['menuId'] && $_POST['type'] == 'top') - { - setEventMessages($langs->trans("ErrorTopMenuMustHaveAParentWithId0"), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['menuId'] && $_POST['type'] == 'left') - { - setEventMessages($langs->trans("ErrorLeftMenuMustHaveAParentId"), null, 'errors'); - $action = 'create'; - $error++; - } + $error = 0; + if (!$error && !$_POST['menu_handler']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("MenuHandler")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['type']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Type")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['url']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['titre']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && $_POST['menuId'] && $_POST['type'] == 'top') + { + setEventMessages($langs->trans("ErrorTopMenuMustHaveAParentWithId0"), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['menuId'] && $_POST['type'] == 'left') + { + setEventMessages($langs->trans("ErrorLeftMenuMustHaveAParentId"), null, 'errors'); + $action = 'create'; + $error++; + } - if (!$error) - { - $menu = new Menubase($db); - $menu->menu_handler = preg_replace('/_menu$/', '', GETPOST('menu_handler', 'aZ09')); - $menu->type = GETPOST('type', 'alpha'); - $menu->title = GETPOST('titre', 'alpha'); - $menu->url = GETPOST('url', 'alpha'); - $menu->langs = GETPOST('langs', 'alpha'); - $menu->position = GETPOST('position', 'int'); - $menu->enabled = GETPOST('enabled', 'alpha'); - $menu->perms = GETPOST('perms', 'alpha'); - $menu->target = GETPOST('target', 'alpha'); - $menu->user = GETPOST('user', 'alpha'); - $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); - if (is_numeric(GETPOST('menuId', 'alpha', 3))) - { - $menu->fk_menu = GETPOST('menuId', 'alpha', 3); - } else { - if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; - else $menu->fk_menu = -1; - $menu->fk_mainmenu = $mainmenu; - $menu->fk_leftmenu = $leftmenu; - } + if (!$error) + { + $menu = new Menubase($db); + $menu->menu_handler = preg_replace('/_menu$/', '', GETPOST('menu_handler', 'aZ09')); + $menu->type = GETPOST('type', 'alpha'); + $menu->title = GETPOST('titre', 'alpha'); + $menu->url = GETPOST('url', 'alpha'); + $menu->langs = GETPOST('langs', 'alpha'); + $menu->position = GETPOST('position', 'int'); + $menu->enabled = GETPOST('enabled', 'alpha'); + $menu->perms = GETPOST('perms', 'alpha'); + $menu->target = GETPOST('target', 'alpha'); + $menu->user = GETPOST('user', 'alpha'); + $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); + if (is_numeric(GETPOST('menuId', 'alpha', 3))) + { + $menu->fk_menu = GETPOST('menuId', 'alpha', 3); + } else { + if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; + else $menu->fk_menu = -1; + $menu->fk_mainmenu = $mainmenu; + $menu->fk_leftmenu = $leftmenu; + } - $result = $menu->create($user); - if ($result > 0) - { - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".GETPOST('menu_handler', 'aZ09')); - exit; - } else { - $action = 'create'; - setEventMessages($menu->error, $menu->errors, 'errors'); - } - } + $result = $menu->create($user); + if ($result > 0) + { + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".GETPOST('menu_handler', 'aZ09')); + exit; + } else { + $action = 'create'; + setEventMessages($menu->error, $menu->errors, 'errors'); + } + } } // delete if ($action == 'confirm_delete' && $_POST["confirm"] == 'yes') { - $this->db->begin(); + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE rowid = ".GETPOST('menuId', 'int'); - $result = $db->query($sql); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE rowid = ".GETPOST('menuId', 'int'); + $result = $db->query($sql); - if ($result == 0) - { - $this->db->commit(); + if ($result == 0) + { + $this->db->commit(); - llxHeader(); - setEventMessages($langs->trans("MenuDeleted"), null, 'mesgs'); - llxFooter(); - exit; - } else { - $this->db->rollback(); + llxHeader(); + setEventMessages($langs->trans("MenuDeleted"), null, 'mesgs'); + llxFooter(); + exit; + } else { + $this->db->rollback(); - $reload = 0; - $_GET["action"] = ''; - } + $reload = 0; + $_GET["action"] = ''; + } } @@ -268,7 +268,7 @@ llxHeader('', $langs->trans("Menu")); if ($action == 'create') { - print ''; - print load_fiche_titre($langs->trans("NewMenu"), '', 'title_setup'); + print load_fiche_titre($langs->trans("NewMenu"), '', 'title_setup'); - print ''; - print ''; + print ''; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - // Id - $parent_rowid = GETPOST('menuId', 'int'); - if (GETPOST('menuId', 'int')) - { - $sql = "SELECT m.rowid, m.mainmenu, m.leftmenu, m.level, m.langs FROM ".MAIN_DB_PREFIX."menu as m WHERE m.rowid = ".GETPOST('menuId', 'int'); - $res = $db->query($sql); - if ($res) - { - while ($menu = $db->fetch_array($res)) - { - $parent_rowid = $menu['rowid']; - $parent_mainmenu = $menu['mainmenu']; - $parent_leftmenu = $menu['leftmenu']; - $parent_langs = $menu['langs']; - $parent_level = $menu['level']; - } - } - } + // Id + $parent_rowid = GETPOST('menuId', 'int'); + if (GETPOST('menuId', 'int')) + { + $sql = "SELECT m.rowid, m.mainmenu, m.leftmenu, m.level, m.langs FROM ".MAIN_DB_PREFIX."menu as m WHERE m.rowid = ".GETPOST('menuId', 'int'); + $res = $db->query($sql); + if ($res) + { + while ($menu = $db->fetch_array($res)) + { + $parent_rowid = $menu['rowid']; + $parent_mainmenu = $menu['mainmenu']; + $parent_leftmenu = $menu['leftmenu']; + $parent_langs = $menu['langs']; + $parent_level = $menu['level']; + } + } + } - // Handler - print ''; - print ''; - print ''; + // Handler + print ''; + print ''; + print ''; - // User - print ''; - print ''; - print ''; + // User + print ''; + print ''; + print ''; - // Type - print ''; + // Type + print ''; - // Mainmenu code - print ''; + // Mainmenu code + print ''; print ''; - print ''; + print ''; - // MenuId Parent - print ''; - if ($parent_rowid) - { - print ''; - } else { - print ''; - } - print ''; + // MenuId Parent + print ''; + if ($parent_rowid) + { + print ''; + } else { + print ''; + } + print ''; - // Title - print ''; + // Title + print ''; - // URL - print ''; + // URL + print ''; - // Langs - print ''; + // Langs + print ''; - // Position - print ''; + // Position + print ''; - // Target - print ''; + // Target + print ''; - // Enabled - print ''; + // Enabled + print ''; - // Perms - print ''; + // Perms + print ''; - print '
'.$langs->trans('MenuHandler').''; - $formadmin->select_menu_families($menu_handler.(preg_match('/_menu/', $menu_handler) ? '' : '_menu'), 'menu_handler', array_merge($dirstandard, $dirsmartphone)); - print ''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuHandler').''; + $formadmin->select_menu_families($menu_handler.(preg_match('/_menu/', $menu_handler) ? '' : '_menu'), 'menu_handler', array_merge($dirstandard, $dirsmartphone)); + print ''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('Type').''; - if ($parent_rowid) - { - print $langs->trans('Left'); - print ''; - } else { - print ''; - } - print ''.$langs->trans('DetailType').'
'.$langs->trans('Type').''; + if ($parent_rowid) + { + print $langs->trans('Left'); + print ''; + } else { + print ''; + } + print ''.$langs->trans('DetailType').'
'.$langs->trans('MainMenuCode').'
'.$langs->trans('MainMenuCode').''; - print $langs->trans("Example").': mytopmenukey'; - print '
'; + print $langs->trans("Example").': mytopmenukey'; + print '
'.$langs->trans('MenuIdParent').''.$parent_rowid.''.$langs->trans('DetailMenuIdParent'); - print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; - print '
'.$langs->trans('MenuIdParent').''.$parent_rowid.''.$langs->trans('DetailMenuIdParent'); + print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; + print '
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled').'
'.$langs->trans('Rights').''.$langs->trans('DetailRight').'
'.$langs->trans('Rights').''.$langs->trans('DetailRight').'
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print '
'; + print '
'; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
'; - print ''; + print ''; } elseif ($action == 'edit') { - print load_fiche_titre($langs->trans("ModifMenu"), '', 'title_setup'); - print '
'; + print load_fiche_titre($langs->trans("ModifMenu"), '', 'title_setup'); + print '
'; - print '
'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - $menu = new Menubase($db); - $result = $menu->fetch(GETPOST('menuId', 'int')); - //var_dump($menu); + $menu = new Menubase($db); + $result = $menu->fetch(GETPOST('menuId', 'int')); + //var_dump($menu); - // Id - print ''; + // Id + print ''; - // Module - print ''; + // Module + print ''; - // Handler - if ($menu->menu_handler == 'all') $handler = $langs->trans('AllMenus'); - else $handler = $menu->menu_handler; - print ''; + // Handler + if ($menu->menu_handler == 'all') $handler = $langs->trans('AllMenus'); + else $handler = $menu->menu_handler; + print ''; - // User - print ''; + // User + print ''; - // Type - print ''; + // Type + print ''; - // Mainmenu code - if ($menu->type == 'top') - { - print ''; - /*if ($parent_rowid) + // Mainmenu code + if ($menu->type == 'top') + { + print ''; + /*if ($parent_rowid) { print ''; } else {*/ - print ''; - //} - print ''; - } + print ''; + //} + print ''; + } - // MenuId Parent - print ''; - $valtouse = $menu->fk_menu; - if ($menu->fk_mainmenu) $valtouse = 'fk_mainmenu='.$menu->fk_mainmenu; - if ($menu->fk_leftmenu) $valtouse .= '&fk_leftmenu='.$menu->fk_leftmenu; - print ''; - print ''; + // MenuId Parent + print ''; + $valtouse = $menu->fk_menu; + if ($menu->fk_mainmenu) $valtouse = 'fk_mainmenu='.$menu->fk_mainmenu; + if ($menu->fk_leftmenu) $valtouse .= '&fk_leftmenu='.$menu->fk_leftmenu; + print ''; + print ''; - // Niveau - //print ''; + // Niveau + //print ''; - // Title - print ''; + // Title + print ''; - // Url - print ''; + // Url + print ''; - // Langs - print ''; + // Langs + print ''; - // Position - print ''; + // Position + print ''; - // Target - print ''; + // Target + print ''; - // Enabled - print ''; + // Enabled + print ''; - // Perms - print ''; + // Perms + print ''; - print '
'.$langs->trans('Id').''.$menu->id.''.$langs->trans('DetailId').'
'.$langs->trans('Id').''.$menu->id.''.$langs->trans('DetailId').'
'.$langs->trans('MenuModule').''.$menu->module.''.$langs->trans('DetailMenuModule').'
'.$langs->trans('MenuModule').''.$menu->module.''.$langs->trans('DetailMenuModule').'
'.$langs->trans('MenuHandler').''.$handler.''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuHandler').''.$handler.''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('Type').''.$langs->trans(ucfirst($menu->type)).''.$langs->trans('DetailType').'
'.$langs->trans('Type').''.$langs->trans(ucfirst($menu->type)).''.$langs->trans('DetailType').'
'.$langs->trans('MainMenuCode').'
'.$langs->trans('MainMenuCode').''.$parent_rowid.'mainmenu).'">'; - print $langs->trans("Example").': mytopmenukey'; - print '
mainmenu).'">'; + print $langs->trans("Example").': mytopmenukey'; + print '
'.$langs->trans('MenuIdParent'); - print ''.$langs->trans('DetailMenuIdParent'); - print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; - print '
'.$langs->trans('MenuIdParent'); + print ''.$langs->trans('DetailMenuIdParent'); + print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; + print '
'.$langs->trans('Level').''.$menu->level.''.$langs->trans('DetailLevel').'
'.$langs->trans('Level').''.$menu->level.''.$langs->trans('DetailLevel').'
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled'); - if (!empty($menu->enabled)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->enabled, 1)).')'; - print '
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled'); + if (!empty($menu->enabled)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->enabled, 1)).')'; + print '
'.$langs->trans('Rights').''.$langs->trans('DetailRight'); - if (!empty($menu->perms)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->perms, 1)).')'; - print '
'.$langs->trans('Rights').''.$langs->trans('DetailRight'); + if (!empty($menu->perms)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->perms, 1)).')'; + print '
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - // Bouton - print '
'; + // Bouton + print '
'; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
'; - print ''; + print ''; - print '
'; + print '
'; } // End of page diff --git a/htdocs/admin/system/dolibarr.php b/htdocs/admin/system/dolibarr.php index fdf0f5aed1f..9288c2e2f1b 100644 --- a/htdocs/admin/system/dolibarr.php +++ b/htdocs/admin/system/dolibarr.php @@ -367,8 +367,7 @@ foreach ($configfileparameters as $key => $value) print ""; if ($newkey == 'dolibarr_main_db_pass') print preg_replace('/./i', '*', ${$newkey}); elseif ($newkey == 'dolibarr_main_url_root' && preg_match('/__auto__/', ${$newkey})) print ${$newkey}.' => '.constant('DOL_MAIN_URL_ROOT'); - elseif ($newkey == 'dolibarr_main_document_root_alt') - { + elseif ($newkey == 'dolibarr_main_document_root_alt') { $tmparray = explode(',', ${$newkey}); $i = 0; foreach ($tmparray as $value2) @@ -382,8 +381,7 @@ foreach ($configfileparameters as $key => $value) } ++$i; } - } elseif ($newkey == 'dolibarr_main_instance_unique_id') - { + } elseif ($newkey == 'dolibarr_main_instance_unique_id') { //print $conf->file->instance_unique_id; global $dolibarr_main_cookie_cryptkey; $valuetoshow = ${$newkey} ? ${$newkey} : $dolibarr_main_cookie_cryptkey; // Use $dolibarr_main_instance_unique_id first then $dolibarr_main_cookie_cryptkey @@ -392,6 +390,13 @@ foreach ($configfileparameters as $key => $value) print img_warning("EditConfigFileToAddEntry", 'dolibarr_main_instance_unique_id'); } print '   ('.$langs->trans("HashForPing").'='.md5('dolibarr'.$valuetoshow).')'; + } elseif ($newkey == 'dolibarr_main_prod') { + print ${$newkey}; + + $valuetoshow = ${$newkey}; + if (empty($valuetoshow)) { + print img_warning($langs->trans('SwitchThisForABetterSecurity')); + } } else { print ${$newkey}; } diff --git a/htdocs/admin/system/modules.php b/htdocs/admin/system/modules.php index 1e5de3b9a46..c909084f1d6 100644 --- a/htdocs/admin/system/modules.php +++ b/htdocs/admin/system/modules.php @@ -25,68 +25,93 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +if (!$user->admin) { + accessforbidden(); +} + // Load translation files required by the page $langs->loadLangs(array("install", "other", "admin")); -if (!$user->admin) - accessforbidden(); +$optioncss = GETPOST('optioncss', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'moduleoverview'; +$search_name = GETPOST("search_name", 'alpha'); +$search_id = GETPOST("search_id", 'alpha'); +$search_version = GETPOST("search_version", 'alpha'); +$search_permission = GETPOST("search_permission", 'alpha'); + +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); + +if (!$sortfield) $sortfield = "id"; +if (!$sortorder) $sortorder = "asc"; + +// Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks +$hookmanager->initHooks(array('moduleoverview')); +$form = new Form($db); +$object = new stdClass(); + +// Definition of fields for lists +$arrayfields = array( + 'name'=>array('label'=>$langs->trans("Modules"), 'checked'=>1, 'position'=>10), + 'version'=>array('label'=>$langs->trans("Version"), 'checked'=>1, 'position'=>20), + 'id'=>array('label'=>$langs->trans("IdModule"), 'checked'=>1, 'position'=>30), + 'permission'=>array('label'=>$langs->trans("IdPermissions"), 'checked'=>1, 'position'=>40) +); + +$arrayfields = dol_sort_array($arrayfields, 'position'); /* - * View + * Actions */ -llxHeader(); +$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'); -print load_fiche_titre($langs->trans("AvailableModules"), '', 'title_setup'); +if (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; +} -print ''.$langs->trans("ToActivateModule").'
'; -print "
\n"; +// Load list of modules +$moduleList = array(); $modules = array(); -$modules_names = array(); $modules_files = array(); $modules_fullpath = array(); $modulesdir = dolGetModulesDirs(); +$rights_ids = array(); -// Load list of modules -$i = 0; -foreach ($modulesdir as $dir) -{ +foreach ($modulesdir as $dir) { $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') { $modName = substr($file, 0, dol_strlen($file) - 10); - if ($modName) - { + if ($modName) { //print 'xx'.$dir.$file.'
'; - if (in_array($file, $modules_files)) - { + if (in_array($file, $modules_files)) { // File duplicate print "Warning duplicate file found : ".$file." (Found ".$dir.$file.", already found ".$modules_fullpath[$file].")
"; - } else { + } + else { // File to load $res = include_once $dir.$file; - if (class_exists($modName)) - { + if (class_exists($modName)) { try { $objMod = new $modName($db); $modules[$objMod->numero] = $objMod; - $modules_names[$objMod->numero] = $objMod->name; $modules_files[$objMod->numero] = $file; $modules_fullpath[$file] = $dir.$file; - $picto[$objMod->numero] = (isset($objMod->picto) && $objMod->picto) ? $objMod->picto : 'generic'; - } catch (Exception $e) - { + } + catch (Exception $e) { dol_syslog("Failed to load ".$dir.$file." ".$e->getMessage(), LOG_ERR); } - } else { + } + else { print "Warning bad descriptor file : ".$dir.$file." (Class ".$modName." not found into file)
"; } } @@ -97,60 +122,280 @@ foreach ($modulesdir as $dir) } } -print '
'; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -$var = false; -$sortorder = $modules_names; -ksort($sortorder); -$rights_ids = array(); -foreach ($sortorder as $numero=>$name) -{ - $idperms = ""; - // Module - print '"; - // Version - print ''; - // Id - print ''; - // Permissions - if ($modules[$numero]->rights) - { - foreach ($modules[$numero]->rights as $rights) - { - $idperms .= ($idperms ? ", " : "").$rights[0]; + else { + $newModule->picto = img_object($alt, 'generic', 'width="14px"'); + } + + $permission = array(); + if ($module->rights) { + foreach ($module->rights as $rights) { + if (empty($rights[0])) { + continue; + } + + $permission[] = $rights[0]; + array_push($rights_ids, $rights[0]); } } - print ''; - print "\n"; + + $newModule->permission = $permission; + + // pre-filter list + if ($search_name && !stristr($newModule->name, $search_name)) continue; + if ($search_version && !stristr($newModule->version, $search_version)) continue; + if ($search_id && !stristr($newModule->id, $search_id)) continue; + + if ($search_permission) { + $found = false; + + foreach ($newModule->permission as $permission) { + if (stristr($permission, $search_permission)) { + $found = true; + break; + } + } + + if (!$found) continue; + } + + $moduleList[] = $newModule; } + + + +/* + * View + */ + +llxHeader(); + +print ''; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($langs->trans("AvailableModules"), $page, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $massactionbutton, -1, '', 'title_setup', 0, '', '', 0, 1, 1); + +print ''.$langs->trans("ToActivateModule").''; +print '
'; +print '
'; + +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + +print '
'; +print '
'.$langs->trans("Modules").''.$langs->trans("Version").''.$langs->trans("IdModule").''.$langs->trans("IdPermissions").'
'; - $alt = $name.' - '.$modules_files[$numero]; - if (!empty($picto[$numero])) - { - if (preg_match('/^\//', $picto[$numero])) print img_picto($alt, $picto[$numero], 'width="14px"', 1); - else print img_object($alt, $picto[$numero], 'width="14px"'); - } else { - print img_object($alt, $picto[$numero], 'width="14px"'); +// create pre-filtered list for modules +foreach ($modules as $key=>$module) { + $newModule = new stdClass(); + + $newModule->name = $module->getName(); + $newModule->version = $module->getVersion(); + $newModule->id = $key; + + $alt = $module->name.' - '.$modules_files[$key]; + + if (!empty($module->picto)) { + if (preg_match('/^\//', $module->picto)) $newModule->picto = img_picto($alt, $module->picto, 'width="14px"', 1); + else $newModule->picto = img_object($alt, $module->picto, 'width="14px"'); } - print ' '.$modules[$numero]->getName(); - print "'.$modules[$numero]->getVersion().''.$numero.''.($idperms ? $idperms : " ").'
'; + +// Lines with input filters +print ''; + +if ($arrayfields['name']['checked']) { + print ''; +} +if ($arrayfields['version']['checked']) { + print ''; +} +if ($arrayfields['id']['checked']) { + print ''; +} +if ($arrayfields['permission']['checked']) { + print ''; +} + +print ''; + +print ''; + +print ''; + +if ($arrayfields['name']['checked']) { + print_liste_field_titre($arrayfields['name']['label'], $_SERVER["PHP_SELF"], "name", "", "", "", $sortfield, $sortorder); +} +if ($arrayfields['version']['checked']) { + print_liste_field_titre($arrayfields['version']['label'], $_SERVER["PHP_SELF"], "version", "", "", "", $sortfield, $sortorder); +} +if ($arrayfields['id']['checked']) { + print_liste_field_titre($arrayfields['id']['label'], $_SERVER["PHP_SELF"], "id", "", "", "", $sortfield, $sortorder); +} +if ($arrayfields['permission']['checked']) { + print_liste_field_titre($arrayfields['permission']['label'], $_SERVER["PHP_SELF"], "permission", "", "", "", $sortfield, $sortorder); +} + +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); +print ''; + +// sort list +if ($sortfield == "name" && $sortorder == "asc") usort($moduleList, function (stdClass $a, stdClass $b) { + return strcasecmp($a->name, $b->name); }); +if ($sortfield == "name" && $sortorder == "desc") usort($moduleList, function (stdClass $a, stdClass $b) { + return strcasecmp($b->name, $a->name); }); +if ($sortfield == "version" && $sortorder == "asc") usort($moduleList, function (stdClass $a, stdClass $b) { + return strcasecmp($a->version, $b->version); }); +if ($sortfield == "version" && $sortorder == "desc") usort($moduleList, function (stdClass $a, stdClass $b) { + return strcasecmp($b->version, $a->version); }); +if ($sortfield == "id" && $sortorder == "asc") usort($moduleList, "compareIdAsc"); +if ($sortfield == "id" && $sortorder == "desc") usort($moduleList, "compareIdDesc"); +if ($sortfield == "permission" && $sortorder == "asc") usort($moduleList, "comparePermissionIdsAsc"); +if ($sortfield == "permission" && $sortorder == "desc") usort($moduleList, "comparePermissionIdsDesc"); + +foreach ($moduleList as $module) { + print ''; + + if ($arrayfields['name']['checked']) { + print '"; + } + + if ($arrayfields['version']['checked']) { + print ''; + } + + if ($arrayfields['id']['checked']) { + print ''; + } + + if ($arrayfields['permission']['checked']) { + $idperms = ''; + + foreach ($module->permission as $permission) { + $idperms .= ($idperms ? ", " : "").$permission; + $translationKey = "Permission".$permission; + + if (!empty($conf->global->MAIN_SHOW_PERMISSION)) { + if (empty($langs->tab_translate[$translationKey])) { + $tooltip = 'Missing translation (key '.$translationkey.' not found in admin.lang)'; + $idperms .= ' Warning'; + } + } + } + + print ''; + } + + print ''; + print ''; +} + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; +$searchpicto = $form->showFilterButtons(); +print $searchpicto; +print '
'; + print $module->picto; + print ' '.$module->name; + print "'.$module->version.''.$module->id.''.($idperms ? $idperms : " ").'
'; print '
'; +print ''; print '
'; + sort($rights_ids); $old = ''; -foreach ($rights_ids as $right_id) -{ - if ($old == $right_id) print "Warning duplicate id on permission : ".$right_id."
"; + +foreach ($rights_ids as $right_id) { + if ($old == $right_id) { + print "Warning duplicate id on permission : ".$right_id."
"; + } + $old = $right_id; } // End of page llxFooter(); $db->close(); + + + /** + * Compare two modules by their ID for a ascending order + * + * @param stdClass $a First module + * @param stdClass $b Second module + * @return int Compare result (-1, 0, 1) + */ +function compareIdAsc(stdClass $a, stdClass $b) +{ + if ($a->id == $b->id) return 0; + + return $a->id > $b->id ? -1 : 1; +} + + /** + * Compare two modules by their ID for a descending order + * + * @param stdClass $a First module + * @param stdClass $b Second module + * @return int Compare result (-1, 0, 1) + */ +function compareIdDesc(stdClass $a, stdClass $b) +{ + if ($a->id == $b->id) return 0; + + return $b->id > $a->id ? -1 : 1; +} + + /** + * Compare two modules by their ID for a ascending order + * + * @param stdClass $a First module + * @param stdClass $b Second module + * @return int Compare result (-1, 0, 1) + */ +function comparePermissionIdsAsc(stdClass $a, stdClass $b) +{ + if (empty($a->permission) && empty($b->permission)) return compareIdAsc($a, $b); + + if (empty($a->permission)) return 1; + if (empty($b->permission)) return -1; + + if ($a->permission[0] == $b->permission[0]) return 0; + + return $a->permission[0] > $b->permission[0] ? -1 : 1; +} + + /** + * Compare two modules by their permissions for a descending order + * + * @param stdClass $a First module + * @param stdClass $b Second module + * @return int Compare result (-1, 0, 1) + */ +function comparePermissionIdsDesc(stdClass $a, stdClass $b) +{ + if (empty($a->permission) && empty($b->permission)) return compareIdDesc($a, $b); + + if (empty($a->permission)) return -1; + if (empty($b->permission)) return 1; + + if ($a->permission[0] == $b->permission[0]) return 0; + + return $a->permission[0] > $b->permission[0] ? 1 : -1; +} diff --git a/htdocs/admin/workflow.php b/htdocs/admin/workflow.php index 311531a52de..671bacee080 100644 --- a/htdocs/admin/workflow.php +++ b/htdocs/admin/workflow.php @@ -1,8 +1,8 @@ - * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2005-2016 Laurent Destailleur - * Copyright (C) 2005-2012 Regis Houssin +/* Copyright (C) 2004 Rodolphe Quiedeville + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2005-2016 Laurent Destailleur + * Copyright (C) 2005-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 @@ -19,19 +19,20 @@ */ /** - * \file htdocs/admin/workflow.php - * \ingroup company - * \brief Workflows setup page + * \file htdocs/admin/workflow.php + * \ingroup company + * \brief Workflows setup page */ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -// Load translation files required by the page -$langs->loadLangs(array("admin", "workflow", "propal", "workflow", "orders", "supplier_proposal", "receptions")); - +// security check if (!$user->admin) accessforbidden(); +// Load translation files required by the page +$langs->loadLangs(array("admin", "workflow", "propal", "workflow", "orders", "supplier_proposal", "receptions", "errors")); + $action = GETPOST('action', 'alpha'); @@ -39,157 +40,199 @@ $action = GETPOST('action', 'alpha'); * Actions */ -if (preg_match('/set(.*)/', $action, $reg)) -{ - if (!dolibarr_set_const($db, $reg[1], '1', 'chaine', 0, '', $conf->entity) > 0) - { - dol_print_error($db); - } +if (preg_match('/set(.*)/', $action, $reg)) { + if (!dolibarr_set_const($db, $reg[1], '1', 'chaine', 0, '', $conf->entity) > 0) { + dol_print_error($db); + } } -if (preg_match('/del(.*)/', $action, $reg)) -{ - if (!dolibarr_set_const($db, $reg[1], '0', 'chaine', 0, '', $conf->entity) > 0) - { - dol_print_error($db); - } +if (preg_match('/del(.*)/', $action, $reg)) { + if (!dolibarr_set_const($db, $reg[1], '0', 'chaine', 0, '', $conf->entity) > 0) { + dol_print_error($db); + } } +// List of workflow we can enable +clearstatcache(); + +$workflowcodes = array( + // Automatic creation + 'WORKFLOW_PROPAL_AUTOCREATE_ORDER'=>array( + 'family'=>'create', + 'position'=>10, + 'enabled'=>(!empty($conf->propal->enabled) && !empty($conf->commande->enabled)), + 'picto'=>'order' + ), + 'WORKFLOW_ORDER_AUTOCREATE_INVOICE'=>array( + 'family'=>'create', + 'position'=>20, + 'enabled'=>(!empty($conf->commande->enabled) && !empty($conf->facture->enabled)), + 'picto'=>'bill' + ), + + 'separator1'=>array('family'=>'separator', 'position'=>25), + + // Automatic classification of proposal + 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array( + 'family'=>'classify_proposal', + 'position'=>30, + 'enabled'=>(!empty($conf->propal->enabled) && !empty($conf->commande->enabled)), + 'picto'=>'propal', + 'warning'=>'' + ), + 'WORKFLOW_INVOICE_CLASSIFY_BILLED_PROPAL'=>array( + 'family'=>'classify_proposal', + 'position'=>31, + 'enabled'=>(!empty($conf->propal->enabled) && !empty($conf->facture->enabled)), + 'picto'=>'propal', + 'warning'=>'' + ), + + // Automatic classification of order + 'WORKFLOW_ORDER_CLASSIFY_SHIPPED_SHIPPING'=>array( + 'family'=>'classify_order', + 'position'=>40, + 'enabled'=>(!empty($conf->expedition->enabled) && !empty($conf->commande->enabled)), + 'picto'=>'order' + ), + 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER'=>array( + 'family'=>'classify_order', + 'position'=>41, + 'enabled'=>(!empty($conf->facture->enabled) && !empty($conf->commande->enabled)), + 'picto'=>'order', + 'warning'=>'' + ), // For this option, if module invoice is disabled, it does not exists, so "Classify billed" for order must be done manually from order card. + + 'separator2'=>array('family'=>'separator', 'position'=>50), + + // Automatic classification supplier proposal + 'WORKFLOW_ORDER_CLASSIFY_BILLED_SUPPLIER_PROPOSAL'=>array( + 'family'=>'classify_supplier_proposal', + 'position'=>60, + 'enabled'=>(!empty($conf->supplier_proposal->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))), + 'picto'=>'propal', + 'warning'=>'' + ), + + // Automatic classification supplier order + 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_SUPPLIER_ORDER'=>array( + 'family'=>'classify_supplier_order', + 'position'=>62, + 'enabled'=>(!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)), + 'picto'=>'order', + 'warning'=>'' + ), + + // Automatic classification reception + 'WORKFLOW_BILL_ON_RECEPTION'=>array( + 'family'=>'classify_reception', + 'position'=>64, + 'enabled'=>(!empty($conf->reception->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))), + 'picto'=>'bill' + ), +); + +if (!empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow'])) { + foreach ($conf->modules_parts['workflow'] as $workflow) { + $workflowcodes = array_merge($workflowcodes, $workflow); + } +} + +// remove not available workflows (based on activated modules and global defined keys) +$workflowcodes = array_filter($workflowcodes, function ($var) { + return $var['enabled']; }); /* - * View + * View */ -llxHeader('', $langs->trans("WorkflowSetup"), ''); +llxHeader('', $langs->trans("WorkflowSetup"), "EN:Module_Workflow_En|FR:Module_Workflow|ES:Módulo_Workflow"); $linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("WorkflowSetup"), $linkback, 'title_setup'); -print ''.$langs->trans("WorkflowDesc").'
'; -print "
"; +print ''.$langs->trans("WorkflowDesc").''; +print '
'; +print '
'; -// List of workflow we can enable +// current module setup don't support any automatic workflow of this module +if (count($workflowcodes) < 1) { + print $langs->trans("ThereIsNoWorkflowToModify"); -clearstatcache(); - -$workflowcodes = array( - // Automatic creation - 'WORKFLOW_PROPAL_AUTOCREATE_ORDER'=>array('family'=>'create', 'position'=>10, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'), - 'WORKFLOW_ORDER_AUTOCREATE_INVOICE'=>array('family'=>'create', 'position'=>20, 'enabled'=>'! empty($conf->commande->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'bill'), - 'separator1'=>array('family'=>'separator', 'position'=>25), - // Automatic classification of proposal - 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>30, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'propal', 'warning'=>''), - 'WORKFLOW_INVOICE_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>31, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'propal', 'warning'=>''), - 'separator2'=>array('family'=>'separator', 'position'=>35), - // Automatic classification of order - 'WORKFLOW_ORDER_CLASSIFY_SHIPPED_SHIPPING'=>array('family'=>'classify_order', 'position'=>40, 'enabled'=>'! empty($conf->expedition->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'), - 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER'=>array('family'=>'classify_order', 'position'=>41, 'enabled'=>'! empty($conf->facture->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order', 'warning'=>''), // For this option, if module invoice is disabled, it does not exists, so "Classify billed" for order must be done manually from order card. - 'separator3'=>array('family'=>'separator', 'position'=>50), - // Automatic classification supplier proposal - 'WORKFLOW_ORDER_CLASSIFY_BILLED_SUPPLIER_PROPOSAL'=>array('family'=>'classify_supplier_proposal', 'position'=>60, 'enabled'=>'! empty($conf->supplier_proposal->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))', 'picto'=>'propal', 'warning'=>''), - 'separator4'=>array('family'=>'separator', 'position'=>61), - // Automatic classification supplier order - 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_SUPPLIER_ORDER'=>array('family'=>'classify_supplier_order', 'position'=>62, 'enabled'=>'!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)', 'picto'=>'order', 'warning'=>''), - 'separator5'=>array('family'=>'separator', 'position'=>63), - // Automatic classification reception - 'WORKFLOW_BILL_ON_RECEPTION'=>array('family'=>'classify_reception', 'position'=>64, 'enabled'=>'! empty($conf->reception->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))', 'picto'=>'bill'), - 'separator6'=>array('family'=>'separator', 'position'=>90), - // Automatic classification of intervention - 'WORKFLOW_TICKET_CLOSE_INTERVENTION'=>array('family'=>'classify_intervention', 'position'=>100, 'enabled'=>'! empty($conf->ticket->enabled) && !empty($conf->ficheinter->enabled)', 'picto'=>'intervention'), -); - -if (!empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow'])) -{ - foreach ($conf->modules_parts['workflow'] as $workflow) - { - $workflowcodes = array_merge($workflowcodes, $workflow); - } + llxFooter(); + $db->close(); + return; } // Sort on position $workflowcodes = dol_sort_array($workflowcodes, 'position'); -$nbqualified = 0; +print ''; + $oldfamily = ''; -print '
'."\n"; - -foreach ($workflowcodes as $key => $params) -{ - $picto = $params['picto']; - $enabled = $params['enabled']; - $family = $params['family']; - - if ($family == 'separator') - { - print '

'; - print ''."\n"; +foreach ($workflowcodes as $key => $params) { + if ($params['family'] == 'separator') { + print '
'; + print '
'; + print ''; continue; } - if (!verifCond($enabled)) continue; - - $nbqualified++; - - - if ($oldfamily != $family) - { - print ''."\n"; - print ' '; - print ' '; - print "\n"; - $oldfamily = $family; - } - print "\n"; - print "\n"; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + + $oldfamily = $params['family']; + } + + print ''; + print ''; + + print ''; + print ''; } -if ($nbqualified == 0) -{ - print '
'; - $reg = array(); - if ($family == 'create') { - print $langs->trans("AutomaticCreation"); - } elseif (preg_match('/classify_(.*)/', $family, $reg)) - { - print $langs->trans("AutomaticClassification"); - if ($reg[1] == 'proposal') print ' - '.$langs->trans('Proposal'); - if ($reg[1] == 'order') print ' - '.$langs->trans('Order'); - if ($reg[1] == 'supplier_proposal') print ' - '.$langs->trans('SupplierProposal'); - if ($reg[1] == 'supplier_order') print ' - '.$langs->trans('SupplierOrder'); - if ($reg[1] == 'reception') print ' - '.$langs->trans('Reception'); - if ($reg[1] == 'intervention') print ' - '.$langs->trans('Intervention'); + if ($oldfamily != $params['family']) { + if ($params['family'] == 'create') { + $header = $langs->trans("AutomaticCreation"); + } elseif (preg_match('/classify_(.*)/', $params['family'], $reg)) { + $header = $langs->trans("AutomaticClassification"); + if ($reg[1] == 'proposal') $header .= ' - '.$langs->trans('Proposal'); + if ($reg[1] == 'order') $header .= ' - '.$langs->trans('Order'); + if ($reg[1] == 'supplier_proposal') $header .= ' - '.$langs->trans('SupplierProposal'); + if ($reg[1] == 'supplier_order') $header .= ' - '.$langs->trans('SupplierOrder'); + if ($reg[1] == 'reception') $header .= ' - '.$langs->trans('Reception'); } else { - print $langs->trans("Description"); + $header = $langs->trans("Description"); } - print ''.$langs->trans("Status").'
".img_object('', $picto, 'class="paddingright"').$langs->trans('desc'.$key); - if (!empty($params['warning'])) - { - $langs->load("errors"); - print ' '.img_warning($langs->transnoentitiesnoconv($params['warning'])); - } - print "'; - if (!empty($conf->use_javascript_ajax)) - { - print ajax_constantonoff($key); - } else { - if (!empty($conf->global->$key)) - { - print ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - } else { - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print ''; - } - } - print '
'.$header.''.$langs->trans("Status").'
'; + print img_object('', $params['picto']); + print ' '.$langs->trans('desc'.$key); + + if (!empty($params['warning'])) { + print ' '.img_warning($langs->transnoentitiesnoconv($params['warning'])); + } + + print ''; + + if (!empty($conf->use_javascript_ajax)) { + print ajax_constantonoff($key); + } else { + if (!empty($conf->global->$key)) { + print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + } else { + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; + } + } + + print '
'.$langs->trans("ThereIsNoWorkflowToModify"); -} print '
'; // End of page diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index 83bd00555d6..554edbb892e 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -32,7 +32,7 @@ class DolibarrApi /** * @var DoliDb $db Database object */ - protected static $db; + protected $db; /** * @var Restler $r Restler object diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index 69fef80fd6b..9605f46f219 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -196,7 +196,7 @@ class Documents extends DolibarrApi throw new RestException(404, 'Invoice not found'); } - $templateused = $doctemplate ? $doctemplate : $this->invoice->modelpdf; + $templateused = $doctemplate ? $doctemplate : $this->invoice->model_pdf; $result = $this->invoice->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { throw new RestException(500, 'Error generating document'); @@ -210,7 +210,7 @@ class Documents extends DolibarrApi if (!$result) { throw new RestException(404, 'Order not found'); } - $templateused = $doctemplate ? $doctemplate : $this->order->modelpdf; + $templateused = $doctemplate ? $doctemplate : $this->order->model_pdf; $result = $this->order->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { throw new RestException(500, 'Error generating document'); @@ -224,7 +224,7 @@ class Documents extends DolibarrApi if (!$result) { throw new RestException(404, 'Proposal not found'); } - $templateused = $doctemplate ? $doctemplate : $this->propal->modelpdf; + $templateused = $doctemplate ? $doctemplate : $this->propal->model_pdf; $result = $this->propal->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { throw new RestException(500, 'Error generating document'); diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index 5dade088fd0..58b8954762c 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -1413,7 +1413,7 @@ class Setup extends DolibarrApi * @url GET conf/{constantname} * * @throws RestException 403 Forbidden - * @throws RestException 500 Error Bad or unknown value for constantname + * @throws RestException 404 Error Bad or unknown value for constantname */ public function getConf($constantname) { @@ -1425,7 +1425,7 @@ class Setup extends DolibarrApi } if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) { - throw new RestException(500, 'Error Bad or unknown value for constantname'); + throw new RestException(404, 'Error Bad or unknown value for constantname'); } if (preg_match('/(_pass|_pw|password|secret|_key|key$)/i', $constantname)) { throw new RestException(403, 'Forbidden'); diff --git a/htdocs/asset/card.php b/htdocs/asset/card.php index 8606751ba85..8a6cb9b5e94 100644 --- a/htdocs/asset/card.php +++ b/htdocs/asset/card.php @@ -346,7 +346,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; $genallowed = $user->rights->asset->read; // If you can read, you can build the PDF to read content $delallowed = $user->rights->asset->create; // If you can create/edit, you can remove a file on card - print $formfile->showdocuments('asset', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + print $formfile->showdocuments('asset', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); */ // Show links to link elements diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 44311f1a580..7bb252394c3 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -368,7 +368,7 @@ class BlockedLog $this->object_data = new stdClass(); // Add fields to exclude $arrayoffieldstoexclude = array( - 'table_element', 'fields', 'ref_previous', 'ref_next', 'origin', 'origin_id', 'oldcopy', 'picto', 'error', 'errors', 'modelpdf', 'last_main_doc', 'civility_id', 'contact', 'contact_id', + 'table_element', 'fields', 'ref_previous', 'ref_next', 'origin', 'origin_id', 'oldcopy', 'picto', 'error', 'errors', 'model_pdf', 'modelpdf', 'last_main_doc', 'civility_id', 'contact', 'contact_id', 'table_element_line', 'ismultientitymanaged', 'isextrafieldmanaged', 'linkedObjectsIds', 'linkedObjects', @@ -476,7 +476,7 @@ class BlockedLog $this->object_data->ref = $object->ref; $this->object_data->date = $datepayment; $this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code'); - $this->object_data->payment_num = ($object->num_paiement ? $object->num_paiement : $object->num_payment); + $this->object_data->payment_num = $object->num_payment; //$this->object_data->fk_account = $object->fk_account; $this->object_data->note = $object->note; //var_dump($this->object_data);exit; diff --git a/htdocs/bom/bom_card.php b/htdocs/bom/bom_card.php index 079fcb608ab..1230a0e3269 100644 --- a/htdocs/bom/bom_card.php +++ b/htdocs/bom/bom_card.php @@ -707,7 +707,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed = $user->rights->bom->read; // If you can read, you can build the PDF to read content $delallowed = $user->rights->bom->write; // If you can create/edit, you can remove a file on card - print $formfile->showdocuments('bom', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang); + print $formfile->showdocuments('bom', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang); // Show links to link elements $linktoelem = $form->showLinkToObjectBlock($object, null, array('bom')); diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index d180c00426f..bd67f311d19 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -745,7 +745,7 @@ class BOM extends CommonObject $result = ''; - $label = ''.$langs->trans("BillOfMaterials").''; + $label = img_picto('', $this->picto).' '.$langs->trans("BillOfMaterials").''; $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; if (isset($this->status)) { @@ -934,8 +934,8 @@ class BOM extends CommonObject if (!dol_strlen($modele)) { $modele = 'standard'; - if ($this->modelpdf) { - $modele = $this->modelpdf; + if ($this->model_pdf) { + $modele = $this->model_pdf; } elseif (!empty($conf->global->BOM_ADDON_PDF)) { $modele = $conf->global->BOM_ADDON_PDF; } diff --git a/htdocs/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php index 3253d6d5d3e..6b8e9af94f1 100644 --- a/htdocs/cashdesk/validation_verif.php +++ b/htdocs/cashdesk/validation_verif.php @@ -294,9 +294,8 @@ switch ($action) // Add the payment $payment = new Paiement($db); $payment->datepaye = $now; - $payment->bank_account = $conf_fkaccount; $payment->amounts[$invoice->id] = $obj_facturation->amountWithTax(); - $payment->note = $langs->trans("Payment").' '.$langs->trans("Invoice").' '.$obj_facturation->numInvoice(); + $payment->note_public = $langs->trans("Payment").' '.$langs->trans("Invoice").' '.$obj_facturation->numInvoice(); $payment->paiementid = $invoice->mode_reglement_id; $payment->num_paiement = ''; $payment->num_payment = ''; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index a181586815f..d24bf74e99f 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -1043,7 +1043,7 @@ if ($action == 'create') }*/ print ''; - // Realised by + // Done by if (!empty($conf->global->AGENDA_ENABLE_DONEBY)) { print ''.$langs->trans("ActionDoneBy").''; diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 5514172182e..dc82c0cfaa4 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -33,9 +33,6 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncommreminder.class.php'; - - - /** * Class to manage agenda events (actions) */ @@ -498,7 +495,7 @@ class ActionComm extends CommonObject $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_private)."', "; - $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? $this->contact_id : "null").", "; // deprecated, use ->socpeopleassigned + $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? $this->contact_id : "null").", "; // deprecated, use ->socpeopleassigned $sql .= (isset($user->id) && $user->id > 0 ? $user->id : "null").", "; $sql .= ($userownerid > 0 ? $userownerid : "null").", "; $sql .= ($userdoneid > 0 ? $userdoneid : "null").", "; @@ -632,173 +629,173 @@ class ActionComm extends CommonObject //$this->fetch_userassigned(); $this->fetchResources(); - $this->id = 0; + $this->id = 0; - // Create clone + // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($fuser); - if ($result < 0) $error++; + if ($result < 0) $error++; - if (!$error) - { - // Hook of thirdparty module - if (is_object($hookmanager)) - { - $parameters = array('objFrom'=>$objFrom); - $action = ''; - $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $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'=>$objFrom); + $action = ''; + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) $error++; + } - // Call trigger - $result = $this->call_trigger('ACTION_CLONE', $fuser); - if ($result < 0) { $error++; } - // End call triggers - } + // Call trigger + $result = $this->call_trigger('ACTION_CLONE', $fuser); + if ($result < 0) { $error++; } + // End call triggers + } - unset($this->context['createfromclone']); + unset($this->context['createfromclone']); - // End - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } + // End + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * Load object from database - * - * @param int $id Id of action to get - * @param string $ref Ref of action to get - * @param string $ref_ext Ref ext to get + /** + * Load object from database + * + * @param int $id Id of action to get + * @param string $ref Ref of action to get + * @param string $ref_ext Ref ext to get * @param string $email_msgid Email msgid - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '') - { - global $langs; + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '') + { + global $langs; - $sql = "SELECT a.id,"; - $sql .= " a.id as ref,"; - $sql .= " a.entity,"; - $sql .= " a.ref_ext,"; - $sql .= " a.datep,"; - $sql .= " a.datep2,"; - $sql .= " a.durationp,"; // deprecated - $sql .= " a.datec,"; - $sql .= " a.tms as datem,"; - $sql .= " a.code, a.label, a.note,"; - $sql .= " a.fk_soc,"; - $sql .= " a.fk_project,"; - $sql .= " a.fk_user_author, a.fk_user_mod,"; - $sql .= " a.fk_user_action, a.fk_user_done,"; - $sql .= " a.fk_contact, a.percent as percentage,"; - $sql .= " a.fk_element as elementid, a.elementtype,"; - $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,"; - $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,"; - $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; - $sql .= " s.nom as socname,"; - $sql .= " u.firstname, u.lastname as lastname"; - $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; - $sql .= " WHERE "; - if ($ref) $sql .= " a.id = ".((int) $ref); // No field ref, we use id - elseif ($ref_ext) $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'"; - elseif ($email_msgid) $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'"; - else $sql .= " a.id = ".((int) $id); + $sql = "SELECT a.id,"; + $sql .= " a.id as ref,"; + $sql .= " a.entity,"; + $sql .= " a.ref_ext,"; + $sql .= " a.datep,"; + $sql .= " a.datep2,"; + $sql .= " a.durationp,"; // deprecated + $sql .= " a.datec,"; + $sql .= " a.tms as datem,"; + $sql .= " a.code, a.label, a.note,"; + $sql .= " a.fk_soc,"; + $sql .= " a.fk_project,"; + $sql .= " a.fk_user_author, a.fk_user_mod,"; + $sql .= " a.fk_user_action, a.fk_user_done,"; + $sql .= " a.fk_contact, a.percent as percentage,"; + $sql .= " a.fk_element as elementid, a.elementtype,"; + $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,"; + $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,"; + $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; + $sql .= " s.nom as socname,"; + $sql .= " u.firstname, u.lastname as lastname"; + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id "; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; + $sql .= " WHERE "; + if ($ref) $sql .= " a.id = ".((int) $ref); // No field ref, we use id + elseif ($ref_ext) $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'"; + elseif ($email_msgid) $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'"; + else $sql .= " a.id = ".((int) $id); - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->id; + $this->id = $obj->id; $this->entity = $obj->entity; - $this->ref = $obj->ref; - $this->ref_ext = $obj->ref_ext; + $this->ref = $obj->ref; + $this->ref_ext = $obj->ref_ext; - // Properties of parent table llx_c_actioncomm - $this->type_id = $obj->type_id; - $this->type_code = $obj->type_code; - $this->type_color = $obj->type_color; - $this->type_picto = $obj->type_picto; - $transcode = $langs->trans("Action".$obj->type_code); - $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label); - $transcode = $langs->trans("Action".$obj->type_code.'Short'); - $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : ''); + // Properties of parent table llx_c_actioncomm + $this->type_id = $obj->type_id; + $this->type_code = $obj->type_code; + $this->type_color = $obj->type_color; + $this->type_picto = $obj->type_picto; + $transcode = $langs->trans("Action".$obj->type_code); + $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label); + $transcode = $langs->trans("Action".$obj->type_code.'Short'); + $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : ''); $this->code = $obj->code; - $this->label = $obj->label; - $this->datep = $this->db->jdate($obj->datep); - $this->datef = $this->db->jdate($obj->datep2); + $this->label = $obj->label; + $this->datep = $this->db->jdate($obj->datep); + $this->datef = $this->db->jdate($obj->datep2); - $this->datec = $this->db->jdate($obj->datec); - $this->datem = $this->db->jdate($obj->datem); + $this->datec = $this->db->jdate($obj->datec); + $this->datem = $this->db->jdate($obj->datem); - $this->note = $obj->note; // deprecated - $this->note_private = $obj->note; - $this->percentage = $obj->percentage; + $this->note = $obj->note; // deprecated + $this->note_private = $obj->note; + $this->percentage = $obj->percentage; - $this->authorid = $obj->fk_user_author; - $this->usermodid = $obj->fk_user_mod; + $this->authorid = $obj->fk_user_author; + $this->usermodid = $obj->fk_user_mod; - if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning - $this->author->id = $obj->fk_user_author; // deprecated - $this->author->firstname = $obj->firstname; // deprecated - $this->author->lastname = $obj->lastname; // deprecated - if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning - $this->usermod->id = $obj->fk_user_mod; // deprecated + if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning + $this->author->id = $obj->fk_user_author; // deprecated + $this->author->firstname = $obj->firstname; // deprecated + $this->author->lastname = $obj->lastname; // deprecated + if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning + $this->usermod->id = $obj->fk_user_mod; // deprecated - $this->userownerid = $obj->fk_user_action; - $this->userdoneid = $obj->fk_user_done; - $this->priority = $obj->priority; - $this->fulldayevent = $obj->fulldayevent; - $this->location = $obj->location; - $this->transparency = $obj->transparency; + $this->userownerid = $obj->fk_user_action; + $this->userdoneid = $obj->fk_user_done; + $this->priority = $obj->priority; + $this->fulldayevent = $obj->fulldayevent; + $this->location = $obj->location; + $this->transparency = $obj->transparency; - $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working - $this->contact_id = $obj->fk_contact; // To have fetch_contact method working - $this->fk_project = $obj->fk_project; // To have fetch_projet method working + $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working + $this->contact_id = $obj->fk_contact; // To have fetch_contact method working + $this->fk_project = $obj->fk_project; // To have fetch_projet method working - //$this->societe->id = $obj->fk_soc; // deprecated - //$this->contact->id = $obj->fk_contact; // deprecated + //$this->societe->id = $obj->fk_soc; // deprecated + //$this->contact->id = $obj->fk_contact; // deprecated - $this->fk_element = $obj->elementid; - $this->elementid = $obj->elementid; - $this->elementtype = $obj->elementtype; + $this->fk_element = $obj->elementid; + $this->elementid = $obj->elementid; + $this->elementtype = $obj->elementtype; - $this->fetchResources(); - } - $this->db->free($resql); - } else { - $this->error = $this->db->lasterror(); - return -1; - } + $this->fetchResources(); + } + $this->db->free($resql); + } else { + $this->error = $this->db->lasterror(); + return -1; + } - return $num; - } + return $num; + } - /** - * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event - * - * @return int <0 if KO, >0 if OK - */ - public function fetchResources() - { - $this->userassigned = array(); - $this->socpeopleassigned = array(); + /** + * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event + * + * @return int <0 if KO, >0 if OK + */ + public function fetchResources() + { + $this->userassigned = array(); + $this->socpeopleassigned = array(); - $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency'; + $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency'; $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources'; $sql .= ' WHERE fk_actioncomm = '.$this->id; $sql .= " AND element_type IN ('user', 'socpeople')"; @@ -1390,7 +1387,7 @@ class ActionComm extends CommonObject if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL'); } - $tooltip = ''.$langs->trans('Action').''; + $tooltip = img_picto('', $this->picto).' '.$langs->trans('Action').''; if (!empty($this->ref)) $tooltip .= '
'.$langs->trans('Ref').': '.$this->ref; if (!empty($label)) @@ -1937,168 +1934,168 @@ class ActionComm extends CommonObject return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); } - /** - * Is the action delayed? - * - * @return bool - */ - public function hasDelay() - { - global $conf; + /** + * Is the action delayed? + * + * @return bool + */ + public function hasDelay() + { + global $conf; - $now = dol_now(); + $now = dol_now(); - return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay)); - } + 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, $user; + /** + * 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, $user; - $error = 0; - $this->output = ''; + $error = 0; + $this->output = ''; $this->error = ''; $nbMailSend = 0; $errorsMsg = array(); - if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible. + if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible. { $langs->load("agenda"); $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda")); return 0; } if (empty($conf->global->AGENDA_REMINDER_EMAIL)) - { - $langs->load("agenda"); - $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda")); - return 0; - } + { + $langs->load("agenda"); + $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda")); + return 0; + } - $now = dol_now(); + $now = dol_now(); - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); - $this->db->begin(); + $this->db->begin(); - //Select all action comm reminder - $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; + //Select all action comm reminder + $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; $sql .= " WHERE typeremind = 'email' AND status = 0"; $sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'"; $sql .= $this->db->order("dateremind", "ASC"); - $resql = $this->db->query($sql); + $resql = $this->db->query($sql); - if ($resql) { - $formmail = new FormMail($this->db); - $actionCommReminder = new ActionCommReminder($this->db); + if ($resql) { + $formmail = new FormMail($this->db); + $actionCommReminder = new ActionCommReminder($this->db); - while ($obj = $this->db->fetch_object($resql)){ - $res = $actionCommReminder->fetch($obj->id); - if ($res < 0) { - $error++; - $errorsMsg[] = "Failed to load invoice ActionComm Reminder"; - } + while ($obj = $this->db->fetch_object($resql)) { + $res = $actionCommReminder->fetch($obj->id); + if ($res < 0) { + $error++; + $errorsMsg[] = "Failed to load invoice ActionComm Reminder"; + } - if (!$error) - { - //Select email template - $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1); + if (!$error) + { + //Select email template + $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1); - // Load event - $res = $this->fetch($actionCommReminder->fk_actioncomm); - if ($res > 0) - { - // PREPARE EMAIL + // Load event + $res = $this->fetch($actionCommReminder->fk_actioncomm); + if ($res > 0) + { + // PREPARE EMAIL - // Make substitution in email content - $substitutionarray = getCommonSubstitutionArray($langs, 0, '', $this); + // Make substitution in email content + $substitutionarray = getCommonSubstitutionArray($langs, 0, '', $this); - complete_substitutions_array($substitutionarray, $langs, $this); + complete_substitutions_array($substitutionarray, $langs, $this); - // Content - $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray); + // Content + $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray); - //Topic - $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->trans('EventReminder')); + //Topic + $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->trans('EventReminder')); - // Recipient - $recipient = new User($this->db); - $res = $recipient->fetch($actionCommReminder->fk_user); - if ($res > 0 && !empty($recipient->email)) $to = $recipient->email; - else { - $errorsMsg[] = "Failed to load recipient"; - $error++; - } + // Recipient + $recipient = new User($this->db); + $res = $recipient->fetch($actionCommReminder->fk_user); + if ($res > 0 && !empty($recipient->email)) $to = $recipient->email; + else { + $errorsMsg[] = "Failed to load recipient"; + $error++; + } - // Sender - $from = $conf->global->MAIN_MAIL_EMAIL_FROM; - if (empty($from)) { - $errorsMsg[] = "Failed to load recipient"; - $error++; - } + // Sender + $from = $conf->global->MAIN_MAIL_EMAIL_FROM; + if (empty($from)) { + $errorsMsg[] = "Failed to load recipient"; + $error++; + } - // Errors Recipient - $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO; + // Errors Recipient + $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO; - // Mail Creation - $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', ''); + // Mail Creation + $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', ''); - // Sending Mail - if ($cMailFile->sendfile()) - { - $actionCommReminder->status = $actionCommReminder::STATUS_DONE; - $res = $actionCommReminder->update($user); - if ($res < 0) - { - $errorsMsg[] = "Failed to update status of ActionComm Reminder"; - $error++; - break; // This is to avoid to have this error on all the selected email. If we fails here for one record, it may fails for others. We must solve first. - } else { - $nbMailSend++; - } - } else { - $errorsMsg[] = $cMailFile->error.' : '.$to; - $error++; - } - } else { - $error++; - } - } - } - } else { - $error++; - } + // Sending Mail + if ($cMailFile->sendfile()) + { + $actionCommReminder->status = $actionCommReminder::STATUS_DONE; + $res = $actionCommReminder->update($user); + if ($res < 0) + { + $errorsMsg[] = "Failed to update status of ActionComm Reminder"; + $error++; + break; // This is to avoid to have this error on all the selected email. If we fails here for one record, it may fails for others. We must solve first. + } else { + $nbMailSend++; + } + } else { + $errorsMsg[] = $cMailFile->error.' : '.$to; + $error++; + } + } else { + $error++; + } + } + } + } else { + $error++; + } - if (!$error) - { - // 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"; + if (!$error) + { + // 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"; $sql .= " WHERE dateremind < '".$this->db->idate($now - (3600 * 24 * 32))."'"; - $resql = $this->db->query($sql); + $resql = $this->db->query($sql); - if (!$resql) { - $errorsMsg[] = 'Failed to delete old reminders'; - //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind. - } - } + if (!$resql) { + $errorsMsg[] = 'Failed to delete old reminders'; + //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind. + } + } - if (!$error) { - $this->output = 'Nb of emails sent : '.$nbMailSend; - $this->db->commit(); - return 0; - } - else { - $this->db->rollback(); - $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error; - return $error; - } - } + if (!$error) { + $this->output = 'Nb of emails sent : '.$nbMailSend; + $this->db->commit(); + return 0; + } + else { + $this->db->rollback(); + $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error; + return $error; + } + } /** * Udpate the percent value of a event with the given id diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index 64c24c9c8e8..135f91c56f4 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -150,7 +150,7 @@ if (GETPOST("viewlist", 'alpha') || $action == 'show_list') $param .= '&'.$key.'='.urlencode($val); } } - if (! preg_match('/action=/', $param)) $param .= ($param ? '&' : '').'action=show_list'; + if (!preg_match('/action=/', $param)) $param .= ($param ? '&' : '').'action=show_list'; //print $param; header("Location: ".DOL_URL_ROOT.'/comm/action/list.php?'.$param); exit; @@ -398,6 +398,8 @@ if ($action == 'show_month') $tabactive = 'cardmonth'; if ($action == 'show_week') $tabactive = 'cardweek'; if ($action == 'show_day') $tabactive = 'cardday'; if ($action == 'show_list') $tabactive = 'cardlist'; +if ($action == 'show_pertuser') $tabactive = 'cardperuser'; +if ($action == 'show_pertype') $tabactive = 'cardpertype'; $paramnoaction = preg_replace('/action=[a-z_]+/', '', $param); @@ -636,518 +638,518 @@ dol_syslog("comm/action/index.php", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); + $num = $db->num_rows($resql); - $MAXONSAMEPAGE = 10000; // Useless to have more. Protection to avoid memory overload when high number of event (for example after a mass import) - $i = 0; - while ($i < $num && $i < $MAXONSAMEPAGE) - { - $obj = $db->fetch_object($resql); + $MAXONSAMEPAGE = 10000; // Useless to have more. Protection to avoid memory overload when high number of event (for example after a mass import) + $i = 0; + while ($i < $num && $i < $MAXONSAMEPAGE) + { + $obj = $db->fetch_object($resql); - // Discard auto action if option is on - if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') - { - $i++; - continue; - } + // Discard auto action if option is on + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') + { + $i++; + continue; + } - // Create a new object action - $event = new ActionComm($db); + // Create a new object action + $event = new ActionComm($db); - $event->id = $obj->id; - $event->ref = $event->id; + $event->id = $obj->id; + $event->ref = $event->id; - $event->datep = $db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin - $event->datef = $db->jdate($obj->datep2); + $event->datep = $db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin + $event->datef = $db->jdate($obj->datep2); //var_dump($obj->datep); - //var_dump($event->datep); + //var_dump($event->datep); - $event->type_code = $obj->type_code; - $event->type_label = $obj->type_label; - $event->type_color = $obj->type_color; + $event->type_code = $obj->type_code; + $event->type_label = $obj->type_label; + $event->type_color = $obj->type_color; - $event->libelle = $obj->label; // deprecated - $event->label = $obj->label; - $event->percentage = $obj->percent; - $event->authorid = $obj->fk_user_author; // user id of creator - $event->userownerid = $obj->fk_user_action; // user id of owner - $event->fetch_userassigned(); // This load $event->userassigned - $event->priority = $obj->priority; - $event->fulldayevent = $obj->fulldayevent; - $event->location = $obj->location; - $event->transparency = $obj->transparency; - $event->fk_element = $obj->fk_element; - $event->elementtype = $obj->elementtype; + $event->libelle = $obj->label; // deprecated + $event->label = $obj->label; + $event->percentage = $obj->percent; + $event->authorid = $obj->fk_user_author; // user id of creator + $event->userownerid = $obj->fk_user_action; // user id of owner + $event->fetch_userassigned(); // This load $event->userassigned + $event->priority = $obj->priority; + $event->fulldayevent = $obj->fulldayevent; + $event->location = $obj->location; + $event->transparency = $obj->transparency; + $event->fk_element = $obj->fk_element; + $event->elementtype = $obj->elementtype; - $event->fk_project = $obj->fk_project; + $event->fk_project = $obj->fk_project; - $event->thirdparty_id = $obj->fk_soc; - $event->contact_id = $obj->fk_contact; + $event->thirdparty_id = $obj->fk_soc; + $event->contact_id = $obj->fk_contact; - // Defined date_start_in_calendar and date_end_in_calendar property - // They are date start and end of action but modified to not be outside calendar view. - $event->date_start_in_calendar = $event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; - else $event->date_end_in_calendar = $event->datep; - // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { - $event->ponctuel = 1; - } + // Defined date_start_in_calendar and date_end_in_calendar property + // They are date start and end of action but modified to not be outside calendar view. + $event->date_start_in_calendar = $event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; + else $event->date_end_in_calendar = $event->datep; + // Define ponctual property + if ($event->date_start_in_calendar == $event->date_end_in_calendar) + { + $event->ponctuel = 1; + } - // Check values - if ($event->date_end_in_calendar < $firstdaytoshow || - $event->date_start_in_calendar >= $lastdaytoshow) - { - // This record is out of visible range - } else { - if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; - if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); + // Check values + if ($event->date_end_in_calendar < $firstdaytoshow || + $event->date_start_in_calendar >= $lastdaytoshow) + { + // This record is out of visible range + } else { + if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; + if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); - // Add an entry in actionarray for each day - $daycursor = $event->date_start_in_calendar; - $annee = date('Y', $daycursor); - $mois = date('m', $daycursor); - $jour = date('d', $daycursor); + // Add an entry in actionarray for each day + $daycursor = $event->date_start_in_calendar; + $annee = date('Y', $daycursor); + $mois = date('m', $daycursor); + $jour = date('d', $daycursor); - // Loop on each day covered by action to prepare an index to show on calendar - $loop = true; $j = 0; - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - do { - //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.'
'; + // Loop on each day covered by action to prepare an index to show on calendar + $loop = true; $j = 0; + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + do { + //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.'
'; - $eventarray[$daykey][] = $event; - $j++; + $eventarray[$daykey][] = $event; + $j++; - $daykey += 60 * 60 * 24; - if ($daykey > $event->date_end_in_calendar) $loop = false; - } while ($loop); + $daykey += 60 * 60 * 24; + if ($daykey > $event->date_end_in_calendar) $loop = false; + } while ($loop); - //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef); - //print ' startincalendar='.dol_print_date($event->date_start_in_calendar).'-endincalendar='.dol_print_date($event->date_end_in_calendar).') was added in '.$j.' different index key of array
'; - } - $i++; - } + //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef); + //print ' startincalendar='.dol_print_date($event->date_start_in_calendar).'-endincalendar='.dol_print_date($event->date_end_in_calendar).') was added in '.$j.' different index key of array
'; + } + $i++; + } } else { - dol_print_error($db); + dol_print_error($db); } // Complete $eventarray with birthdates if ($showbirthday) { - // Add events in array - $sql = 'SELECT sp.rowid, sp.lastname, sp.firstname, sp.birthday'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp'; - $sql .= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))'; - $sql .= " AND sp.entity IN (".getEntity('socpeople').")"; - if ($action == 'show_day') - { - $sql .= ' AND MONTH(birthday) = '.$month; - $sql .= ' AND DAY(birthday) = '.$day; - } else { - $sql .= ' AND MONTH(birthday) = '.$month; - } - $sql .= ' ORDER BY birthday'; + // Add events in array + $sql = 'SELECT sp.rowid, sp.lastname, sp.firstname, sp.birthday'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp'; + $sql .= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))'; + $sql .= " AND sp.entity IN (".getEntity('socpeople').")"; + if ($action == 'show_day') + { + $sql .= ' AND MONTH(birthday) = '.$month; + $sql .= ' AND DAY(birthday) = '.$day; + } else { + $sql .= ' AND MONTH(birthday) = '.$month; + } + $sql .= ' ORDER BY birthday'; - dol_syslog("comm/action/index.php", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - $event = new ActionComm($db); + dol_syslog("comm/action/index.php", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $event = new ActionComm($db); - $event->id = $obj->rowid; // We put contact id in action id for birthdays events - $event->ref = $event->id; + $event->id = $obj->rowid; // We put contact id in action id for birthdays events + $event->ref = $event->id; - $datebirth = dol_stringtotime($obj->birthday, 1); - //print 'ee'.$obj->birthday.'-'.$datebirth; - $datearray = dol_getdate($datebirth, true); - $event->datep = dol_mktime(0, 0, 0, $datearray['mon'], $datearray['mday'], $year, true); // For full day events, date are also GMT but they wont but converted during output - $event->datef = $event->datep; - $event->type_code = 'BIRTHDAY'; - $event->label = $langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname); - $event->percentage = 100; - $event->fulldayevent = 1; + $datebirth = dol_stringtotime($obj->birthday, 1); + //print 'ee'.$obj->birthday.'-'.$datebirth; + $datearray = dol_getdate($datebirth, true); + $event->datep = dol_mktime(0, 0, 0, $datearray['mon'], $datearray['mday'], $year, true); // For full day events, date are also GMT but they wont but converted during output + $event->datef = $event->datep; + $event->type_code = 'BIRTHDAY'; + $event->label = $langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname); + $event->percentage = 100; + $event->fulldayevent = 1; - $event->date_start_in_calendar = $event->datep; - $event->date_end_in_calendar = $event->datef; - $event->ponctuel = 0; + $event->date_start_in_calendar = $event->datep; + $event->date_end_in_calendar = $event->datef; + $event->ponctuel = 0; - // Add an entry in actionarray for each day - $daycursor = $event->date_start_in_calendar; - $annee = date('Y', $daycursor); - $mois = date('m', $daycursor); - $jour = date('d', $daycursor); + // Add an entry in actionarray for each day + $daycursor = $event->date_start_in_calendar; + $annee = date('Y', $daycursor); + $mois = date('m', $daycursor); + $jour = date('d', $daycursor); - $loop = true; - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - do { - $eventarray[$daykey][] = $event; - $daykey += 60 * 60 * 24; - if ($daykey > $event->date_end_in_calendar) $loop = false; - } while ($loop); - $i++; - } - } else { - dol_print_error($db); - } + $loop = true; + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + do { + $eventarray[$daykey][] = $event; + $daykey += 60 * 60 * 24; + if ($daykey > $event->date_end_in_calendar) $loop = false; + } while ($loop); + $i++; + } + } else { + dol_print_error($db); + } } if ($conf->global->AGENDA_SHOW_HOLIDAYS) { - $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status"; - $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; - $sql .= " WHERE u.rowid = x.fk_user"; - $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user) - $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved) + $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status"; + $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE u.rowid = x.fk_user"; + $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user) + $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved) - if ($action == 'show_day') - { - // Request only leaves for the current selected day - $sql .= " AND '".$year."-".$month."-".$day."' BETWEEN x.date_debut AND x.date_fin"; - } elseif ($action == 'show_week') - { - // TODO: Add filter to reduce database request - } elseif ($action == 'show_month') - { - // TODO: Add filter to reduce database request - } + if ($action == 'show_day') + { + // Request only leaves for the current selected day + $sql .= " AND '".$year."-".$month."-".$day."' BETWEEN x.date_debut AND x.date_fin"; + } elseif ($action == 'show_week') + { + // TODO: Add filter to reduce database request + } elseif ($action == 'show_month') + { + // TODO: Add filter to reduce database request + } - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); + while ($i < $num) + { + $obj = $db->fetch_object($resql); - $dateStartArray = dol_getdate(dol_stringtotime($obj->date_start, 1), true); - $dateEndArray = dol_getdate(dol_stringtotime($obj->date_end, 1), true); + $dateStartArray = dol_getdate(dol_stringtotime($obj->date_start, 1), true); + $dateEndArray = dol_getdate(dol_stringtotime($obj->date_end, 1), true); - $event = new ActionComm($db); + $event = new ActionComm($db); - // Need the id of the leave object for link to it - $event->id = $obj->rowid; - $event->ref = $event->id; + // Need the id of the leave object for link to it + $event->id = $obj->rowid; + $event->ref = $event->id; - $event->type_code = 'HOLIDAY'; - $event->datep = dol_mktime(0, 0, 0, $dateStartArray['mon'], $dateStartArray['mday'], $dateStartArray['year'], true); - $event->datef = dol_mktime(0, 0, 0, $dateEndArray['mon'], $dateEndArray['mday'], $dateEndArray['year'], true); - $event->date_start_in_calendar = $event->datep; - $event->date_end_in_calendar = $event->datef; + $event->type_code = 'HOLIDAY'; + $event->datep = dol_mktime(0, 0, 0, $dateStartArray['mon'], $dateStartArray['mday'], $dateStartArray['year'], true); + $event->datef = dol_mktime(0, 0, 0, $dateEndArray['mon'], $dateEndArray['mday'], $dateEndArray['year'], true); + $event->date_start_in_calendar = $event->datep; + $event->date_end_in_calendar = $event->datef; - if ($obj->status == 3) - { - // Show no symbol for leave with state "leave approved" - $event->percentage = -1; - } elseif ($obj->status == 2) - { - // Show TO-DO symbol for leave with state "leave wait for approval" - $event->percentage = 0; - } + if ($obj->status == 3) + { + // Show no symbol for leave with state "leave approved" + $event->percentage = -1; + } elseif ($obj->status == 2) + { + // Show TO-DO symbol for leave with state "leave wait for approval" + $event->percentage = 0; + } - if ($obj->halfday == 1) - { - $event->label = $obj->lastname.' ('.$langs->trans("Morning").')'; - } elseif ($obj->halfday == -1) - { - $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')'; - } else { - $event->label = $obj->lastname; - } + if ($obj->halfday == 1) + { + $event->label = $obj->lastname.' ('.$langs->trans("Morning").')'; + } elseif ($obj->halfday == -1) + { + $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')'; + } else { + $event->label = $obj->lastname; + } - $annee = date('Y', $event->date_start_in_calendar); - $mois = date('m', $event->date_start_in_calendar); - $jour = date('d', $event->date_start_in_calendar); - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + $annee = date('Y', $event->date_start_in_calendar); + $mois = date('m', $event->date_start_in_calendar); + $jour = date('d', $event->date_start_in_calendar); + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - do { - $eventarray[$daykey][] = $event; + do { + $eventarray[$daykey][] = $event; - $daykey += 60 * 60 * 24; - } while ($daykey <= $event->date_end_in_calendar); + $daykey += 60 * 60 * 24; + } while ($daykey <= $event->date_end_in_calendar); - $i++; - } - } + $i++; + } + } } // Complete $eventarray with external import Ical if (count($listofextcals)) { - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php'; - foreach ($listofextcals as $extcal) - { - $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics - $namecal = $extcal['name']; - $offsettz = $extcal['offsettz']; - $colorcal = $extcal['color']; - $buggedfile = $extcal['buggedfile']; - //print "url=".$url." namecal=".$namecal." colorcal=".$colorcal." buggedfile=".$buggedfile; - $ical = new ICal(); - $ical->parse($url); + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php'; + foreach ($listofextcals as $extcal) + { + $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics + $namecal = $extcal['name']; + $offsettz = $extcal['offsettz']; + $colorcal = $extcal['color']; + $buggedfile = $extcal['buggedfile']; + //print "url=".$url." namecal=".$namecal." colorcal=".$colorcal." buggedfile=".$buggedfile; + $ical = new ICal(); + $ical->parse($url); - // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ... - //var_dump($ical->cal); exit; - $icalevents = array(); - if (is_array($ical->get_event_list())) $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] - if (is_array($ical->get_freebusy_list())) $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] + // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ... + //var_dump($ical->cal); exit; + $icalevents = array(); + if (is_array($ical->get_event_list())) $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] + if (is_array($ical->get_freebusy_list())) $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] - if (count($icalevents) > 0) - { - // Duplicate all repeatable events into new entries - $moreicalevents = array(); - foreach ($icalevents as $icalevent) - { - if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event - { - //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; - //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1); - if ($icalevent['DTSTART;VALUE=DATE']) //fullday event - { - $datecurstart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); - $datecurend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day - } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime'])) - { - $datecurstart = $icalevent['DTSTART']['unixtime']; - $datecurend = $icalevent['DTEND']['unixtime']; - if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) - { - //var_dump($ical->cal); - $tmpcurstart = $datecurstart; - $tmpcurend = $datecurend; - $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART']; - $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART']; - //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']); - // Edit datecurstart and datecurend - if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; - else $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; - if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; - else $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; - } - // datecurstart and datecurend are now GMT date - //var_dump($datecurstart); var_dump($datecurend); exit; - } else { - // Not a recongized record - dol_syslog("Found a not recognized repeatable record with unknown date start", LOG_ERR); - continue; - } - //print 'xx'.$datecurstart;exit; + if (count($icalevents) > 0) + { + // Duplicate all repeatable events into new entries + $moreicalevents = array(); + foreach ($icalevents as $icalevent) + { + if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event + { + //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; + //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1); + if ($icalevent['DTSTART;VALUE=DATE']) //fullday event + { + $datecurstart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); + $datecurend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day + } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime'])) + { + $datecurstart = $icalevent['DTSTART']['unixtime']; + $datecurend = $icalevent['DTEND']['unixtime']; + if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) + { + //var_dump($ical->cal); + $tmpcurstart = $datecurstart; + $tmpcurend = $datecurend; + $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART']; + $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART']; + //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']); + // Edit datecurstart and datecurend + if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; + else $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; + else $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + } + // datecurstart and datecurend are now GMT date + //var_dump($datecurstart); var_dump($datecurend); exit; + } else { + // Not a recongized record + dol_syslog("Found a not recognized repeatable record with unknown date start", LOG_ERR); + continue; + } + //print 'xx'.$datecurstart;exit; - $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']); - $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1); - $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT']; - if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show - if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show + $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']); + $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1); + $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT']; + if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show + if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show - $numofevent = 0; - while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) - { - if ($datecurend >= $firstdaytoshow) // We add event - { - $newevent = $icalevent; - unset($newevent['RRULE']); - if ($icalevent['DTSTART;VALUE=DATE']) - { - $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d'); - $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d'); - } else { - $newevent['DTSTART'] = $datecurstart; - $newevent['DTEND'] = $datecurend; - } - $moreicalevents[] = $newevent; - } - // Jump on next occurence - $numofevent++; - $savdatecurstart = $datecurstart; - if ($icalevent['RRULE']['FREQ'] == 'DAILY') - { - $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'd'); - $datecurend = dol_time_plus_duree($datecurend, $interval, 'd'); - } - if ($icalevent['RRULE']['FREQ'] == 'WEEKLY') - { - $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w'); - $datecurend = dol_time_plus_duree($datecurend, $interval, 'w'); - } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY') - { - $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'm'); - $datecurend = dol_time_plus_duree($datecurend, $interval, 'm'); - } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY') - { - $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y'); - $datecurend = dol_time_plus_duree($datecurend, $interval, 'y'); - } - // Test to avoid infinite loop ($datecurstart must increase) - if ($savdatecurstart >= $datecurstart) - { - dol_syslog("Found a rule freq ".$icalevent['RRULE']['FREQ']." not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR); - $datecurstart += 3600 * 24 * 7; - $datecurend += 3600 * 24 * 7; - } - } - } - } - $icalevents = array_merge($icalevents, $moreicalevents); + $numofevent = 0; + while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) + { + if ($datecurend >= $firstdaytoshow) // We add event + { + $newevent = $icalevent; + unset($newevent['RRULE']); + if ($icalevent['DTSTART;VALUE=DATE']) + { + $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d'); + $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d'); + } else { + $newevent['DTSTART'] = $datecurstart; + $newevent['DTEND'] = $datecurend; + } + $moreicalevents[] = $newevent; + } + // Jump on next occurence + $numofevent++; + $savdatecurstart = $datecurstart; + if ($icalevent['RRULE']['FREQ'] == 'DAILY') + { + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'd'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'd'); + } + if ($icalevent['RRULE']['FREQ'] == 'WEEKLY') + { + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'w'); + } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY') + { + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'm'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'm'); + } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY') + { + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'y'); + } + // Test to avoid infinite loop ($datecurstart must increase) + if ($savdatecurstart >= $datecurstart) + { + dol_syslog("Found a rule freq ".$icalevent['RRULE']['FREQ']." not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR); + $datecurstart += 3600 * 24 * 7; + $datecurend += 3600 * 24 * 7; + } + } + } + } + $icalevents = array_merge($icalevents, $moreicalevents); - // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray - foreach ($icalevents as $icalevent) - { - //var_dump($icalevent); + // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray + foreach ($icalevents as $icalevent) + { + //var_dump($icalevent); - //print $icalevent['SUMMARY'].'->'.var_dump($icalevent).'
';exit; - if (!empty($icalevent['RRULE'])) continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule. + //print $icalevent['SUMMARY'].'->'.var_dump($icalevent).'
';exit; + if (!empty($icalevent['RRULE'])) continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule. - // Create a new object action - $event = new ActionComm($db); - $addevent = false; - if (isset($icalevent['DTSTART;VALUE=DATE'])) // fullday event - { - // For full day events, date are also GMT but they wont but converted using tz during output - $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); - $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day - //print 'x'.$datestart.'-'.$dateend;exit; - //print dol_print_date($dateend,'dayhour','gmt'); - $event->fulldayevent = 1; - $addevent = true; - } elseif (!is_array($icalevent['DTSTART'])) // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch) - { - $datestart = $icalevent['DTSTART']; - $dateend = $icalevent['DTEND']; + // Create a new object action + $event = new ActionComm($db); + $addevent = false; + if (isset($icalevent['DTSTART;VALUE=DATE'])) // fullday event + { + // For full day events, date are also GMT but they wont but converted using tz during output + $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); + $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day + //print 'x'.$datestart.'-'.$dateend;exit; + //print dol_print_date($dateend,'dayhour','gmt'); + $event->fulldayevent = 1; + $addevent = true; + } elseif (!is_array($icalevent['DTSTART'])) // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch) + { + $datestart = $icalevent['DTSTART']; + $dateend = $icalevent['DTEND']; - $datestart += +($offsettz * 3600); - $dateend += +($offsettz * 3600); + $datestart += +($offsettz * 3600); + $dateend += +($offsettz * 3600); - $addevent = true; - //var_dump($offsettz); - //var_dump(dol_print_date($datestart, 'dayhour', 'gmt')); - } elseif (isset($icalevent['DTSTART']['unixtime'])) // File contains a local timezone + a TZ (for example when using bluemind) - { - $datestart = $icalevent['DTSTART']['unixtime']; - $dateend = $icalevent['DTEND']['unixtime']; + $addevent = true; + //var_dump($offsettz); + //var_dump(dol_print_date($datestart, 'dayhour', 'gmt')); + } elseif (isset($icalevent['DTSTART']['unixtime'])) // File contains a local timezone + a TZ (for example when using bluemind) + { + $datestart = $icalevent['DTSTART']['unixtime']; + $dateend = $icalevent['DTEND']['unixtime']; - $datestart += +($offsettz * 3600); - $dateend += +($offsettz * 3600); + $datestart += +($offsettz * 3600); + $dateend += +($offsettz * 3600); - // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight' - if ($buggedfile === 'uselocalandtznodaylight') // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2 - { - // TODO - } - // $buggedfile is set to uselocalandtzdaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtzdaylight' (for example with bluemind) - if ($buggedfile === 'uselocalandtzdaylight') // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer - { - $localtzs = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTSTART']['TZID'])); - $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID'])); - $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs); - $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze); + // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight' + if ($buggedfile === 'uselocalandtznodaylight') // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2 + { + // TODO + } + // $buggedfile is set to uselocalandtzdaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtzdaylight' (for example with bluemind) + if ($buggedfile === 'uselocalandtzdaylight') // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer + { + $localtzs = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTSTART']['TZID'])); + $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID'])); + $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs); + $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze); $tmps = -1 * $localtzs->getOffset($localdts); $tmpe = -1 * $localtze->getOffset($localdte); $datestart += $tmps; $dateend += $tmpe; //var_dump($datestart); - } - $addevent = true; - } + } + $addevent = true; + } - if ($addevent) - { - $event->id = $icalevent['UID']; - $event->ref = $event->id; + if ($addevent) + { + $event->id = $icalevent['UID']; + $event->ref = $event->id; - $userId = $userstatic->findUserIdByEmail($namecal); - if (!empty($userId) && $userId > 0) - { - $event->userassigned[$userId] = $userId; - $event->percentage = -1; - } - else { - $event->type_code = "ICALEVENT"; - } + $userId = $userstatic->findUserIdByEmail($namecal); + if (!empty($userId) && $userId > 0) + { + $event->userassigned[$userId] = $userId; + $event->percentage = -1; + } + else { + $event->type_code = "ICALEVENT"; + } - $event->icalname = $namecal; - $event->icalcolor = $colorcal; - $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output. - $event->datep = $datestart + $usertime; - $event->datef = $dateend + $usertime; + $event->icalname = $namecal; + $event->icalcolor = $colorcal; + $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output. + $event->datep = $datestart + $usertime; + $event->datef = $dateend + $usertime; - if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY']; - elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); - else $event->label = $langs->trans("ExtSiteNoLabel"); + if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY']; + elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); + else $event->label = $langs->trans("ExtSiteNoLabel"); - // Priority (see https://www.kanzaki.com/docs/ical/priority.html) - // LOW = 0 to 4 - // MEDIUM = 5 - // HIGH = 6 to 9 - if ($icalevent['PRIORITY']) $event->priority = $icalevent['PRIORITY']; + // Priority (see https://www.kanzaki.com/docs/ical/priority.html) + // LOW = 0 to 4 + // MEDIUM = 5 + // HIGH = 6 to 9 + if ($icalevent['PRIORITY']) $event->priority = $icalevent['PRIORITY']; - // Transparency (see https://www.kanzaki.com/docs/ical/transp.html) - if ($icalevent['TRANSP']) - { - if ($icalevent['TRANSP'] == "TRANSPARENT") $event->transparency = 0; // 0 = available / free - if ($icalevent['TRANSP'] == "OPAQUE") $event->transparency = 1; // 1 = busy + // Transparency (see https://www.kanzaki.com/docs/ical/transp.html) + if ($icalevent['TRANSP']) + { + if ($icalevent['TRANSP'] == "TRANSPARENT") $event->transparency = 0; // 0 = available / free + if ($icalevent['TRANSP'] == "OPAQUE") $event->transparency = 1; // 1 = busy - // TODO: MS outlook states - // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:TRANSPARENT => Available / Free - // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:OPAQUE => Work another place - // X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE + TRANSP:OPAQUE => With reservations - // X-MICROSOFT-CDO-BUSYSTATUS:BUSY + TRANSP:OPAQUE => Busy - // X-MICROSOFT-CDO-BUSYSTATUS:OOF + TRANSP:OPAQUE => Away from the office / off-site - } + // TODO: MS outlook states + // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:TRANSPARENT => Available / Free + // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:OPAQUE => Work another place + // X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE + TRANSP:OPAQUE => With reservations + // X-MICROSOFT-CDO-BUSYSTATUS:BUSY + TRANSP:OPAQUE => Busy + // X-MICROSOFT-CDO-BUSYSTATUS:OOF + TRANSP:OPAQUE => Away from the office / off-site + } - if ($icalevent['LOCATION']) $event->location = $icalevent['LOCATION']; + if ($icalevent['LOCATION']) $event->location = $icalevent['LOCATION']; - $event->date_start_in_calendar = $event->datep; + $event->date_start_in_calendar = $event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; - else $event->date_end_in_calendar = $event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; + else $event->date_end_in_calendar = $event->datep; - // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { - $event->ponctuel = 1; - //print 'x'.$datestart.'-'.$dateend;exit; - } + // Define ponctual property + if ($event->date_start_in_calendar == $event->date_end_in_calendar) + { + $event->ponctuel = 1; + //print 'x'.$datestart.'-'.$dateend;exit; + } - // Add event into $eventarray if date range are ok. - if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) - { - //print 'x'.$datestart.'-'.$dateend;exit; - //print 'x'.$datestart.'-'.$dateend;exit; - //print 'x'.$datestart.'-'.$dateend;exit; - // This record is out of visible range - } else { - if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; - if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); + // Add event into $eventarray if date range are ok. + if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) + { + //print 'x'.$datestart.'-'.$dateend;exit; + //print 'x'.$datestart.'-'.$dateend;exit; + //print 'x'.$datestart.'-'.$dateend;exit; + // This record is out of visible range + } else { + if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; + if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); - // Add an entry in actionarray for each day - $daycursor = $event->date_start_in_calendar; - $annee = date('Y', $daycursor); - $mois = date('m', $daycursor); - $jour = date('d', $daycursor); + // Add an entry in actionarray for each day + $daycursor = $event->date_start_in_calendar; + $annee = date('Y', $daycursor); + $mois = date('m', $daycursor); + $jour = date('d', $daycursor); - // Loop on each day covered by action to prepare an index to show on calendar - $loop = true; $j = 0; - // daykey must be date that represent day box in calendar so must be a user time - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, true, 0); - do { - //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' '; - $eventarray[$daykey][] = $event; - $daykey += 60 * 60 * 24; $daykeygmt += 60 * 60 * 24; // Add one day - if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop = false; - } while ($loop); - } - } - } - } - } + // Loop on each day covered by action to prepare an index to show on calendar + $loop = true; $j = 0; + // daykey must be date that represent day box in calendar so must be a user time + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, true, 0); + do { + //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' '; + $eventarray[$daykey][] = $event; + $daykey += 60 * 60 * 24; $daykeygmt += 60 * 60 * 24; // Add one day + if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop = false; + } while ($loop); + } + } + } + } + } } @@ -1192,48 +1194,48 @@ print $s; if (empty($action) || $action == 'show_month') // View by month { - $newparam = $param; // newparam is for birthday links - $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done - $newparam = preg_replace('/action=show_month&?/i', '', $newparam); - $newparam = preg_replace('/action=show_week&?/i', '', $newparam); - $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter - $newparam .= '&viewcal=1'; + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter + $newparam .= '&viewcal=1'; - print '
'; - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); - print '
'; + print '
'; + print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print '
'; - print '
'; - print ''; - print ' '; + print '
'; + print '
'; + print ' '; // Column title of weeks numbers echo ' '; - $i = 0; - while ($i < 7) - { - print ' '."\n"; - $i++; - } - echo ' '."\n"; + $i = 0; + while ($i < 7) + { + print ' '."\n"; + $i++; + } + echo ' '."\n"; - $todayarray = dol_getdate($now, 'fast'); - $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']); + $todayarray = dol_getdate($now, 'fast'); + $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']); - // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month) - //var_dump($eventarray); - for ($iter_week = 0; $iter_week < 6; $iter_week++) { - echo " \n"; + // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month) + //var_dump($eventarray); + for ($iter_week = 0; $iter_week < 6; $iter_week++) { + echo " \n"; // Get date of the current day, format 'yyyy-mm-dd' if ($tmpday <= 0) // If number of the current day is in previous month { @@ -1252,130 +1254,130 @@ if (empty($action) || $action == 'show_month') // View by month // Show the week number, and define column width echo ' '; - for ($iter_day = 0; $iter_day < 7; $iter_day++) { - if ($tmpday <= 0) { - /* Show days before the beginning of the current month (previous month) */ - $style = 'cal_other_month cal_past'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; - echo ' \n"; - } elseif ($tmpday <= $max_day_in_month) { - /* Show days of the current month */ - $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year); - $style = 'cal_current_month'; - if ($iter_day == 6) $style .= ' cal_current_month_right'; - $today = 0; - if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; - if ($today) $style = 'cal_today'; - if ($curtime < $todaytms) $style .= ' cal_past'; + for ($iter_day = 0; $iter_day < 7; $iter_day++) { + if ($tmpday <= 0) { + /* Show days before the beginning of the current month (previous month) */ + $style = 'cal_other_month cal_past'; + if ($iter_day == 6) $style .= ' cal_other_month_right'; + echo ' \n"; + } elseif ($tmpday <= $max_day_in_month) { + /* Show days of the current month */ + $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year); + $style = 'cal_current_month'; + if ($iter_day == 6) $style .= ' cal_current_month_right'; + $today = 0; + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; + if ($today) $style = 'cal_today'; + if ($curtime < $todaytms) $style .= ' cal_past'; //var_dump($todayarray['mday']."==".$tmpday." && ".$todayarray['mon']."==".$month." && ".$todayarray['year']."==".$year.' -> '.$style); - echo ' \n"; - } else { - /* Show days after the current month (next month) */ - $style = 'cal_other_month'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; - echo ' \n"; - } - $tmpday++; - } - echo " \n"; - } - print "
#'; - $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7); - if (!empty($conf->dol_optimize_smallscreen)) - { - $labelshort = array(0=>'SundayMin', 1=>'MondayMin', 2=>'TuesdayMin', 3=>'WednesdayMin', 4=>'ThursdayMin', 5=>'FridayMin', 6=>'SaturdayMin'); - print $langs->trans($labelshort[$numdayinweek]); - } else print $langs->trans("Day".$numdayinweek); - print '
'; + $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7); + if (!empty($conf->dol_optimize_smallscreen)) + { + $labelshort = array(0=>'SundayMin', 1=>'MondayMin', 2=>'TuesdayMin', 3=>'WednesdayMin', 4=>'ThursdayMin', 5=>'FridayMin', 6=>'SaturdayMin'); + print $langs->trans($labelshort[$numdayinweek]); + } else print $langs->trans("Day".$numdayinweek); + print '
'.$numweek0.''; - show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); - echo " '; + show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); + echo " '; - show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); - echo " '; - show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); - echo "
\n"; + echo ' '; + show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); + echo " \n"; + } else { + /* Show days after the current month (next month) */ + $style = 'cal_other_month'; + if ($iter_day == 6) $style .= ' cal_other_month_right'; + echo ' '; + show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); + echo "\n"; + } + $tmpday++; + } + echo " \n"; + } + print "\n"; print '
'; print ''; print ''; print ''; } elseif ($action == 'show_week') { - // View by week - $newparam = $param; // newparam is for birthday links - $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done - $newparam = preg_replace('/action=show_month&?/i', '', $newparam); - $newparam = preg_replace('/action=show_week&?/i', '', $newparam); - $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter - $newparam .= '&viewweek=1'; + // View by week + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter + $newparam .= '&viewweek=1'; - print '
'; - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); - print '
'; + print '
'; + print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print '
'; - print '
'; - print ''; - print ' '; - $i = 0; - while ($i < 7) { - echo ' \n"; - $i++; - } - echo " \n"; + print '
'; + print '
'.$langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7))."
'; + print ' '; + $i = 0; + while ($i < 7) { + echo ' \n"; + $i++; + } + echo " \n"; - echo " \n"; + echo " \n"; - for ($iter_day = 0; $iter_day < 7; $iter_day++) { - // Show days of the current week + for ($iter_day = 0; $iter_day < 7; $iter_day++) { + // Show days of the current week $curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd'); $tmparray = dol_getdate($curtime, true); $tmpday = $tmparray['mday']; $tmpmonth = $tmparray['mon']; $tmpyear = $tmparray['year']; - $style = 'cal_current_month'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; - $today = 0; - $todayarray = dol_getdate($now, 'fast'); - if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; - if ($today) $style = 'cal_today'; + $style = 'cal_current_month'; + if ($iter_day == 6) $style .= ' cal_other_month_right'; + $today = 0; + $todayarray = dol_getdate($now, 'fast'); + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; + if ($today) $style = 'cal_today'; - echo ' \n"; - } - echo " \n"; + echo ' \n"; + } + echo " \n"; - print "
'.$langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7))."
'; - show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); - echo "
'; + show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); + echo "
\n"; + print "\n"; print '
'; - echo ''; - echo ''; - echo ''; + echo ''; + echo ''; + echo ''; } else // View by day { - $newparam = $param; // newparam is for birthday links - $newparam = preg_replace('/action=show_month&?/i', '', $newparam); - $newparam = preg_replace('/action=show_week&?/i', '', $newparam); - $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam); - $newparam .= '&viewday=1'; - // Code to show just one day - $style = 'cal_current_month cal_current_month_oneday'; - $today = 0; - $todayarray = dol_getdate($now, 'fast'); - if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; - //if ($today) $style='cal_today'; + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam); + $newparam .= '&viewday=1'; + // Code to show just one day + $style = 'cal_current_month cal_current_month_oneday'; + $today = 0; + $todayarray = dol_getdate($now, 'fast'); + if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; + //if ($today) $style='cal_today'; - $timestamp = dol_mktime(12, 0, 0, $month, $day, $year); - $arraytimestamp = dol_getdate($timestamp); + $timestamp = dol_mktime(12, 0, 0, $month, $day, $year); + $arraytimestamp = dol_getdate($timestamp); - print '
'; - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); - print '
'; + print '
'; + print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print '
'; - print '
'; - echo ''; + print '
'; + echo '
'; - echo ' '; - echo ' \n"; - echo " \n"; + echo ' '; + echo ' \n"; + echo " \n"; - /* + /* echo '
'; echo '
'; echo '
'; @@ -1460,401 +1462,401 @@ $db->close(); */ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint = 0, $maxnbofchar = 16, $newparam = '', $showinfo = 0, $minheight = 60, $nonew = 0) { - global $user, $conf, $langs; - global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form - global $theme_datacolor; - global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused; + global $user, $conf, $langs; + global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form + global $theme_datacolor; + global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused; - $dateint = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); + $dateint = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); - print "\n"; + print "\n"; - // Line with title of day - $curtime = dol_mktime(0, 0, 0, $month, $day, $year); - print '
'."\n"; + // Line with title of day + $curtime = dol_mktime(0, 0, 0, $month, $day, $year); + print '
'."\n"; - if ($nonew <= 0) - { - print '
'; - if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) - { - $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; + if ($nonew <= 0) + { + print '
'; + if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) + { + $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; - //$param='month='.$monthshown.'&year='.$year; - $hourminsec = '100000'; - print ''; - print img_picto($langs->trans("NewAction"), 'edit_add.png'); - print ''; - } - print '
'."\n"; - } + //$param='month='.$monthshown.'&year='.$year; + $hourminsec = '100000'; + print ''; + print img_picto($langs->trans("NewAction"), 'edit_add.png'); + print ''; + } + print '
'."\n"; + } - if ($nonew < 0) - { - print '
'; - return; - } + if ($nonew < 0) + { + print '
'; + return; + } - // Line with td contains all div of each events - print '
'; - print '
'; + // Line with td contains all div of each events + print '
'; + print '
'; - //$curtime = dol_mktime (0, 0, 0, $month, $day, $year); - $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array(); - $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); + //$curtime = dol_mktime (0, 0, 0, $month, $day, $year); + $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array(); + $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); - $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 - $nextindextouse = is_array($colorindexused) ?count($colorindexused) : 0; // At first run this is 0, so fist user has 0, next 1, ... + $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 + $nextindextouse = is_array($colorindexused) ?count($colorindexused) : 0; // At first run this is 0, so fist user has 0, next 1, ... //var_dump($colorindexused); - foreach ($eventarray as $daykey => $notused) - { - $annee = date('Y', $daykey); - $mois = date('m', $daykey); - $jour = date('d', $daykey); - if ($day == $jour && $month == $mois && $year == $annee) - { - foreach ($eventarray[$daykey] as $index => $event) - { - if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA)) - { - $keysofuserassigned = array_keys($event->userassigned); - $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar); + foreach ($eventarray as $daykey => $notused) + { + $annee = date('Y', $daykey); + $mois = date('m', $daykey); + $jour = date('d', $daykey); + if ($day == $jour && $month == $mois && $year == $annee) + { + foreach ($eventarray[$daykey] as $index => $event) + { + if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA)) + { + $keysofuserassigned = array_keys($event->userassigned); + $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar); - // Define $color (Hex string like '0088FF') and $cssclass of event - $color = -1; $cssclass = ''; $colorindex = -1; - if (in_array($user->id, $keysofuserassigned)) - { - $cssclass = 'family_mytasks'; + // Define $color (Hex string like '0088FF') and $cssclass of event + $color = -1; $cssclass = ''; $colorindex = -1; + if (in_array($user->id, $keysofuserassigned)) + { + $cssclass = 'family_mytasks'; - if (empty($cacheusers[$event->userownerid])) - { - $newuser = new User($db); - $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid] = $newuser; - } - //var_dump($cacheusers[$event->userownerid]->color); + if (empty($cacheusers[$event->userownerid])) + { + $newuser = new User($db); + $newuser->fetch($event->userownerid); + $cacheusers[$event->userownerid] = $newuser; + } + //var_dump($cacheusers[$event->userownerid]->color); - // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) - if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; - } elseif ($event->type_code == 'ICALEVENT') // Event come from external ical file - { - $numical++; - if (!empty($event->icalname)) { - if (!isset($numicals[dol_string_nospecial($event->icalname)])) { - $numicals[dol_string_nospecial($event->icalname)] = 0; - } - $numicals[dol_string_nospecial($event->icalname)]++; - } + // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) + if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; + } elseif ($event->type_code == 'ICALEVENT') // Event come from external ical file + { + $numical++; + if (!empty($event->icalname)) { + if (!isset($numicals[dol_string_nospecial($event->icalname)])) { + $numicals[dol_string_nospecial($event->icalname)] = 0; + } + $numicals[dol_string_nospecial($event->icalname)]++; + } - $color = ($event->icalcolor ? $event->icalcolor : -1); - $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); - } elseif ($event->type_code == 'BIRTHDAY') - { - $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unmovable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); - } else { - $numother++; - $color = ($event->icalcolor ? $event->icalcolor : -1); - $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); + $color = ($event->icalcolor ? $event->icalcolor : -1); + $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); + } elseif ($event->type_code == 'BIRTHDAY') + { + $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unmovable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); + } else { + $numother++; + $color = ($event->icalcolor ? $event->icalcolor : -1); + $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); - if (empty($cacheusers[$event->userownerid])) - { - $newuser = new User($db); - $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid] = $newuser; - } - //var_dump($cacheusers[$event->userownerid]->color); + if (empty($cacheusers[$event->userownerid])) + { + $newuser = new User($db); + $newuser->fetch($event->userownerid); + $cacheusers[$event->userownerid] = $newuser; + } + //var_dump($cacheusers[$event->userownerid]->color); - // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) - if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; - } + // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) + if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; + } - if ($color < 0) // Color was not set on user card. Set color according to color index. - { - // Define color index if not yet defined - $idusertouse = ($event->userownerid ? $event->userownerid : 0); - if (isset($colorindexused[$idusertouse])) - { - $colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user - } else { - $colorindex = $nextindextouse; - $colorindexused[$idusertouse] = $colorindex; - if (!empty($theme_datacolor[$nextindextouse + 1])) $nextindextouse++; // Prepare to use next color - } - //print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'
'; - // Define color - $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); - } - $cssclass = $cssclass.' '.$cssclass.'_day_'.$ymd; + if ($color < 0) // Color was not set on user card. Set color according to color index. + { + // Define color index if not yet defined + $idusertouse = ($event->userownerid ? $event->userownerid : 0); + if (isset($colorindexused[$idusertouse])) + { + $colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user + } else { + $colorindex = $nextindextouse; + $colorindexused[$idusertouse] = $colorindex; + if (!empty($theme_datacolor[$nextindextouse + 1])) $nextindextouse++; // Prepare to use next color + } + //print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'
'; + // Define color + $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); + } + $cssclass = $cssclass.' '.$cssclass.'_day_'.$ymd; - // Defined style to disable drag and drop feature - if ($event->type_code == 'AC_OTH_AUTO') - { - $cssclass .= " unmovable"; - } elseif ($event->type_code == 'ICALEVENT') - { - $cssclass .= " unmovable"; - } elseif ($event->date_end_in_calendar && date('Ymd', $event->date_start_in_calendar) != date('Ymd', $event->date_end_in_calendar)) { - $tmpyearend = date('Y', $event->date_end_in_calendar); - $tmpmonthend = date('m', $event->date_end_in_calendar); - $tmpdayend = date('d', $event->date_end_in_calendar); - if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) - { - $cssclass .= " unmovable"; - } - } else { - if ($user->rights->agenda->allactions->create || - (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) - { - $cssclass .= " movable cursormove"; - } else { - $cssclass .= " unmovable"; - } - } + // Defined style to disable drag and drop feature + if ($event->type_code == 'AC_OTH_AUTO') + { + $cssclass .= " unmovable"; + } elseif ($event->type_code == 'ICALEVENT') + { + $cssclass .= " unmovable"; + } elseif ($event->date_end_in_calendar && date('Ymd', $event->date_start_in_calendar) != date('Ymd', $event->date_end_in_calendar)) { + $tmpyearend = date('Y', $event->date_end_in_calendar); + $tmpmonthend = date('m', $event->date_end_in_calendar); + $tmpdayend = date('d', $event->date_end_in_calendar); + if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) + { + $cssclass .= " unmovable"; + } + } else { + if ($user->rights->agenda->allactions->create || + (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) + { + $cssclass .= " movable cursormove"; + } else { + $cssclass .= " unmovable"; + } + } - $h = ''; $nowrapontd = 1; - if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; } - if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; } + $h = ''; $nowrapontd = 1; + if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; } + if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; } - // Show rect of event - print "\n"; - print ''."\n"; - print '
'; + // Show rect of event + print "\n"; + print ''."\n"; + print '
'; - //var_dump($event->userassigned); - //var_dump($event->transparency); - print '
'.$langs->trans("Day".$arraytimestamp['wday'])."
'.$langs->trans("Day".$arraytimestamp['wday'])."
'; - print ''; - print ''; + // Status - Percent + $withstatus = 0; + if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') + { + $withstatus = 1; + if ($event->percentage >= 0) $withstatus = 2; + } + print '
'; + //var_dump($event->userassigned); + //var_dump($event->transparency); + print ''; + print ''; + print ''; - // Status - Percent - $withstatus = 0; - if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') - { - $withstatus = 1; - if ($event->percentage >= 0) $withstatus = 2; - } - print '
'; - $daterange = ''; + $daterange = ''; - if ($event->type_code == 'BIRTHDAY') // It's a birthday - { - print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'birthday', 'contact'); - } elseif ($event->type_code == 'HOLIDAY') - { - print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'holiday', 'user'); - } elseif ($event->type_code != 'BIRTHDAY' && $event->type_code != 'HOLIDAY') - { - // Picto - if (empty($event->fulldayevent)) - { - //print $event->getNomUrl(2).' '; - } + if ($event->type_code == 'BIRTHDAY') // It's a birthday + { + print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'birthday', 'contact'); + } elseif ($event->type_code == 'HOLIDAY') + { + print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'holiday', 'user'); + } elseif ($event->type_code != 'BIRTHDAY' && $event->type_code != 'HOLIDAY') + { + // Picto + if (empty($event->fulldayevent)) + { + //print $event->getNomUrl(2).' '; + } - // Date - if (empty($event->fulldayevent)) - { - // Show hours (start ... end) - $tmpyearstart = date('Y', $event->date_start_in_calendar); - $tmpmonthstart = date('m', $event->date_start_in_calendar); - $tmpdaystart = date('d', $event->date_start_in_calendar); - $tmpyearend = date('Y', $event->date_end_in_calendar); - $tmpmonthend = date('m', $event->date_end_in_calendar); - $tmpdayend = date('d', $event->date_end_in_calendar); - // Hour start - if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) - { - $daterange .= dol_print_date($event->date_start_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend) - $daterange .= '-'; - //else - //print '...'; - } - } - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend) - { - $daterange .= '...'; - } - } - // Hour end - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) - $daterange .= dol_print_date($event->date_end_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user - } - } else { - if ($showinfo) - { - print $langs->trans("EventOnFullDay")."
\n"; - } - } + // Date + if (empty($event->fulldayevent)) + { + // Show hours (start ... end) + $tmpyearstart = date('Y', $event->date_start_in_calendar); + $tmpmonthstart = date('m', $event->date_start_in_calendar); + $tmpdaystart = date('d', $event->date_start_in_calendar); + $tmpyearend = date('Y', $event->date_end_in_calendar); + $tmpmonthend = date('m', $event->date_end_in_calendar); + $tmpdayend = date('d', $event->date_end_in_calendar); + // Hour start + if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) + { + $daterange .= dol_print_date($event->date_start_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) + { + if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend) + $daterange .= '-'; + //else + //print '...'; + } + } + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) + { + if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend) + { + $daterange .= '...'; + } + } + // Hour end + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) + { + if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) + $daterange .= dol_print_date($event->date_end_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user + } + } else { + if ($showinfo) + { + print $langs->trans("EventOnFullDay")."
\n"; + } + } - // Show title - $titletoshow = $daterange; - $titletoshow .= ($titletoshow ? ' ' : '').($event->label ? $event->label : $event->libelle); + // Show title + $titletoshow = $daterange; + $titletoshow .= ($titletoshow ? ' ' : '').($event->label ? $event->label : $event->libelle); - if ($event->type_code != 'ICALEVENT') { - $savlabel = $event->label ? $event->label : $event->libelle; - $event->label = $titletoshow; - $event->libelle = $titletoshow; - // Note: List of users are inside $event->userassigned. Link may be clickable depending on permissions of user. - $titletoshow = $event->getNomUrl(0, $maxnbofchar, 'cal_event cal_event_title', '', 0, 0); - $event->label = $savlabel; - $event->libelle = $savlabel; - } + if ($event->type_code != 'ICALEVENT') { + $savlabel = $event->label ? $event->label : $event->libelle; + $event->label = $titletoshow; + $event->libelle = $titletoshow; + // Note: List of users are inside $event->userassigned. Link may be clickable depending on permissions of user. + $titletoshow = $event->getNomUrl(0, $maxnbofchar, 'cal_event cal_event_title', '', 0, 0); + $event->label = $savlabel; + $event->libelle = $savlabel; + } - // Loop on each assigned user - $listofusertoshow = ''; - $posuserassigned = 0; - foreach ($event->userassigned as $tmpid => $tmpdata) - { - if (!$posuserassigned && $titletoshow) $listofusertoshow .= '
'; - $posuserassigned++; - if (empty($cacheusers[$tmpid])) - { - $newuser = new User($db); - $newuser->fetch($tmpid); - $cacheusers[$tmpid] = $newuser; - } + // Loop on each assigned user + $listofusertoshow = ''; + $posuserassigned = 0; + foreach ($event->userassigned as $tmpid => $tmpdata) + { + if (!$posuserassigned && $titletoshow) $listofusertoshow .= '
'; + $posuserassigned++; + if (empty($cacheusers[$tmpid])) + { + $newuser = new User($db); + $newuser->fetch($tmpid); + $cacheusers[$tmpid] = $newuser; + } - $listofusertoshow .= $cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom'); - } + $listofusertoshow .= $cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom'); + } - print $titletoshow; - print $listofusertoshow; + print $titletoshow; + print $listofusertoshow; - if ($event->type_code == 'ICALEVENT') print '
('.dol_trunc($event->icalname, $maxnbofchar).')'; + if ($event->type_code == 'ICALEVENT') print '
('.dol_trunc($event->icalname, $maxnbofchar).')'; - $thirdparty_id = ($event->thirdparty_id > 0 ? $event->thirdparty_id : ((is_object($event->societe) && $event->societe->id > 0) ? $event->societe->id : 0)); - $contact_id = ($event->contact_id > 0 ? $event->contact_id : ((is_object($event->contact) && $event->contact->id > 0) ? $event->contact->id : 0)); + $thirdparty_id = ($event->thirdparty_id > 0 ? $event->thirdparty_id : ((is_object($event->societe) && $event->societe->id > 0) ? $event->societe->id : 0)); + $contact_id = ($event->contact_id > 0 ? $event->contact_id : ((is_object($event->contact) && $event->contact->id > 0) ? $event->contact->id : 0)); - // If action related to company / contact - $linerelatedto = ''; - if ($thirdparty_id > 0) - { - if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id])) - { - $thirdparty = new Societe($db); - $thirdparty->fetch($thirdparty_id); - $cachethirdparties[$thirdparty_id] = $thirdparty; - } else $thirdparty = $cachethirdparties[$thirdparty_id]; - if (!empty($thirdparty->id)) $linerelatedto .= $thirdparty->getNomUrl(1, '', 0); - } - if (!empty($contact_id) && $contact_id > 0) - { - if (!is_object($cachecontacts[$contact_id])) - { - $contact = new Contact($db); - $contact->fetch($contact_id); - $cachecontacts[$contact_id] = $contact; - } else $contact = $cachecontacts[$contact_id]; - if ($linerelatedto) $linerelatedto .= ' '; - if (!empty($contact->id)) $linerelatedto .= $contact->getNomUrl(1, '', 0); - } - if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - if ($linerelatedto) $linerelatedto .= '
'; - $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1); - } - if ($linerelatedto) print '
'.$linerelatedto; - } + // If action related to company / contact + $linerelatedto = ''; + if ($thirdparty_id > 0) + { + if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id])) + { + $thirdparty = new Societe($db); + $thirdparty->fetch($thirdparty_id); + $cachethirdparties[$thirdparty_id] = $thirdparty; + } else $thirdparty = $cachethirdparties[$thirdparty_id]; + if (!empty($thirdparty->id)) $linerelatedto .= $thirdparty->getNomUrl(1, '', 0); + } + if (!empty($contact_id) && $contact_id > 0) + { + if (!is_object($cachecontacts[$contact_id])) + { + $contact = new Contact($db); + $contact->fetch($contact_id); + $cachecontacts[$contact_id] = $contact; + } else $contact = $cachecontacts[$contact_id]; + if ($linerelatedto) $linerelatedto .= ' '; + if (!empty($contact->id)) $linerelatedto .= $contact->getNomUrl(1, '', 0); + } + if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + if ($linerelatedto) $linerelatedto .= '
'; + $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1); + } + if ($linerelatedto) print '
'.$linerelatedto; + } - // Show location - if ($showinfo) - { - if ($event->location) - { - print '
'; - print $langs->trans("Location").': '.$event->location; - } - } + // Show location + if ($showinfo) + { + if ($event->location) + { + print '
'; + print $langs->trans("Location").': '.$event->location; + } + } - print '
'; - if ($withstatus) print $event->getLibStatut(3, 1); - else print ' '; - print '
'; - print ''."\n"; - $i++; - } else { - print ''.img_picto("all", "1downarrow_selected.png").' ...'; - print ' +'.(count($eventarray[$daykey]) - $maxprint); - print ''; - break; - //$ok=false; // To avoid to show twice the link - } - } + print '
'; + if ($withstatus) print $event->getLibStatut(3, 1); + else print ' '; + print '
'; + print '
'."\n"; + $i++; + } else { + print ''.img_picto("all", "1downarrow_selected.png").' ...'; + print ' +'.(count($eventarray[$daykey]) - $maxprint); + print ''; + break; + //$ok=false; // To avoid to show twice the link + } + } - break; - } - } - if (!$i) print ' '; + break; + } + } + if (!$i) print ' '; - if (!empty($conf->global->MAIN_JS_SWITCH_AGENDA) && $i > $maxprint && $maxprint) - { - print '
'.img_picto("all", "1downarrow_selected.png").' +'.$langs->trans("More").'...
'; - //print ' +'.(count($eventarray[$daykey])-$maxprint); - print ''."\n"; - } + print ''."\n"; + } - print '
'; // td tr + print ''; // td tr - print ''; // table - print "\n"; + print ''; // table + print "\n"; } diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php index 20ba2928de1..ee47dbc3387 100644 --- a/htdocs/comm/action/list.php +++ b/htdocs/comm/action/list.php @@ -429,7 +429,7 @@ if ($resql) $arrayofselected = is_array($toselect) ? $toselect : array(); // Local calendar - $newtitle = '
'; + $newtitle = '
'; $newtitle .= ' '.$langs->trans("LocalAgenda").'   '; $newtitle .= '
'; //$newtitle=$langs->trans($title); diff --git a/htdocs/comm/action/pertype.php b/htdocs/comm/action/pertype.php index 7eb5b9e5c6d..72b25c9d731 100644 --- a/htdocs/comm/action/pertype.php +++ b/htdocs/comm/action/pertype.php @@ -41,9 +41,9 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; if (!isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW = 3; -$filter = GETPOST("filter", 'alpha', 3); -$filtert = GETPOST("filtert", "int", 3); -$usergroup = GETPOST("usergroup", "int", 3); +$filter = GETPOST("search_filter", 'alpha', 3) ? GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3); +$filtert = GETPOST("search_filtert", "int", 3) ? GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3); +$usergroup = GETPOST("search_usergroup", "int", 3) ? GETPOST("search_usergroup", "int", 3) : GETPOST("usergroup", "int", 3); //if (! ($usergroup > 0) && ! ($filtert > 0)) $filtert = $user->id; //$showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1; $showbirthday = 0; @@ -64,7 +64,7 @@ if (!$sortorder) $sortorder = "ASC"; if (!$sortfield) $sortfield = "a.datec"; // Security check -$socid = GETPOST("socid", "int"); +$socid = GETPOST("search_socid", "int") ?GETPOST("search_socid", "int") : GETPOST("socid", "int"); if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'agenda', 0, '', 'myactions'); if ($socid < 0) $socid = ''; @@ -79,22 +79,23 @@ if (!$user->rights->agenda->allactions->read || $filter == 'mine') // If no per //$action=GETPOST('action','alpha'); $action = 'show_pertype'; -$resourceid = GETPOST("resourceid", "int"); +$resourceid = GETPOST("search_resourceid", "int") ?GETPOST("search_resourceid", "int") : GETPOST("resourceid", "int"); $year = GETPOST("year", "int") ?GETPOST("year", "int") : date("Y"); $month = GETPOST("month", "int") ?GETPOST("month", "int") : date("m"); $week = GETPOST("week", "int") ?GETPOST("week", "int") : date("W"); $day = GETPOST("day", "int") ?GETPOST("day", "int") : date("d"); -$pid = GETPOST("projectid", "int", 3); -$status = GETPOST("status", 'alpha'); -$type = GETPOST("type", 'alpha'); +$pid = GETPOST("search_projectid", "int", 3) ?GETPOST("search_projectid", "int", 3) : GETPOST("projectid", "int", 3); +$status = GETPOST("search_status", 'alpha') ?GETPOST("search_status", 'alpha') : GETPOST("status", 'alpha'); +$type = GETPOST("search_type", 'alpha') ?GETPOST("search_type", 'alpha') : GETPOST("type", 'alpha'); $maxprint = ((GETPOST("maxprint", 'int') != '') ?GETPOST("maxprint", 'int') : $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW); +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) -if (GETPOST('actioncode', 'array')) +if (GETPOST('search_actioncode', 'array')) { - $actioncode = GETPOST('actioncode', 'array', 3); + $actioncode = GETPOST('search_actioncode', 'array', 3); if (!count($actioncode)) $actioncode = '0'; } else { - $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode", "alpha") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE)); + $actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode", "alpha") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE)); } if ($actioncode == '' && empty($actioncodearray)) $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); @@ -107,6 +108,7 @@ if ($dateselect > 0) } $tmp = empty($conf->global->MAIN_DEFAULT_WORKING_HOURS) ? '9-18' : $conf->global->MAIN_DEFAULT_WORKING_HOURS; +$tmp = str_replace(' ', '', $tmp); // FIX 7533 $tmparray = explode('-', $tmp); $begin_h = GETPOST('begin_h', 'int') != '' ?GETPOST('begin_h', 'int') : ($tmparray[0] != '' ? $tmparray[0] : 9); $end_h = GETPOST('end_h', 'int') ?GETPOST('end_h', 'int') : ($tmparray[1] != '' ? $tmparray[1] : 18); @@ -115,14 +117,15 @@ if ($end_h < 1 || $end_h > 24) $end_h = 18; if ($end_h <= $begin_h) $end_h = $begin_h + 1; $tmp = empty($conf->global->MAIN_DEFAULT_WORKING_DAYS) ? '1-5' : $conf->global->MAIN_DEFAULT_WORKING_DAYS; +$tmp = str_replace(' ', '', $tmp); // FIX 7533 $tmparray = explode('-', $tmp); $begin_d = 1; -$end_d = 53; +$end_d = 53; if ($status == '' && !isset($_GET['status']) && !isset($_POST['status'])) $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); if (empty($action) && !isset($_GET['action']) && !isset($_POST['action'])) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); -if (GETPOST('viewcal') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') { +if (GETPOST('viewcal', 'alpha') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') { $action = 'show_month'; $day = ''; } // View by month if (GETPOST('viewweek', 'alpha') || $action == 'show_week') { @@ -150,6 +153,10 @@ if ($action == 'delete_action') { $event = new ActionComm($db); $event->fetch($actionid); + $event->fetch_optionals(); + $event->fetch_userassigned(); + $event->oldcopy = clone $event; + $result = $event->delete(); } @@ -159,6 +166,27 @@ if ($action == 'delete_action') * View */ +$parameters = array( + 'socid' => $socid, + 'status' => $status, + 'year' => $year, + 'month' => $month, + 'day' => $day, + 'type' => $type, + 'maxprint' => $maxprint, + 'filter' => $filter, + 'filtert' => $filtert, + 'showbirthday' => $showbirthday, + 'canedit' => $canedit, + 'optioncss' => $optioncss, + 'actioncode' => $actioncode, + 'pid' => $pid, + 'resourceid' => $resourceid, + 'usergroup' => $usergroup, +); +$reshook = $hookmanager->executeHooks('beforeAgendaPerType', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + $form = new Form($db); $companystatic = new Societe($db); @@ -199,18 +227,26 @@ if ($status == 'done') $title = $langs->trans("DoneActions"); if ($status == 'todo') $title = $langs->trans("ToDoActions"); $param = ''; -if ($actioncode || isset($_GET['actioncode']) || isset($_POST['actioncode'])) $param .= "&actioncode=".$actioncode; -if ($resourceid > 0) $param .= "&resourceid=".$resourceid; -if ($status || isset($_GET['status']) || isset($_POST['status'])) $param .= "&status=".$status; -if ($filter) $param .= "&filter=".$filter; -if ($filtert) $param .= "&filtert=".$filtert; -if ($usergroup) $param .= "&usergroup=".$usergroup; -if ($socid) $param .= "&socid=".$socid; -if ($showbirthday) $param .= "&showbirthday=1"; -if ($pid) $param .= "&projectid=".$pid; -if ($type) $param .= "&type=".$type; -if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser' || $action != 'show_pertype') $param .= '&action='.$action; -$param .= "&maxprint=".$maxprint; +if ($actioncode || isset($_GET['search_actioncode']) || isset($_POST['search_actioncode'])) { + if (is_array($actioncode)) { + foreach ($actioncode as $str_action) $param .= "&search_actioncode[]=".urlencode($str_action); + } else $param .= "&search_actioncode=".urlencode($actioncode); +} +if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid); +if ($status || isset($_GET['status']) || isset($_POST['status'])) $param .= "&search_status=".urlencode($status); +if ($filter) $param .= "&search_filter=".urlencode($filter); +if ($filtert) $param .= "&search_filtert=".urlencode($filtert); +if ($usergroup) $param .= "&search_usergroup=".urlencode($usergroup); +if ($socid) $param .= "&search_socid=".urlencode($socid); +if ($showbirthday) $param .= "&search_showbirthday=1"; +if ($pid) $param .= "&search_projectid=".urlencode($pid); +if ($type) $param .= "&search_type=".urlencode($type); +if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') $param .= '&action='.urlencode($action); +if ($begin_h != '') $param .= '&begin_h='.urlencode($begin_h); +if ($end_h != '') $param .= '&end_h='.urlencode($end_h); +if ($begin_d != '') $param .= '&begin_d='.urlencode($begin_d); +if ($end_d != '') $param .= '&end_d='.urlencode($end_d); +$param .= "&maxprint=".urlencode($maxprint); $prev = dol_get_first_day($year, 1); $prev_year = $year - 1; @@ -238,6 +274,7 @@ $lastdaytoshow = dol_time_plus_duree($firstdaytoshow, 7, 'd'); $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); $tmpday = $first_day; +$picto = 'calendartype'; $nav = "".img_previous($langs->trans("Previous"))."\n"; $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y")." \n"; @@ -245,7 +282,7 @@ $nav .= "".$langs->trans("Today").")"; $picto = 'calendarweek'; -$nav .= '  
'; +/*$nav .= '   '; $nav .= ''; $nav .= ''; $nav .= ''; @@ -260,27 +297,30 @@ $nav .= ''; $nav .= ''; $nav .= ''; $nav .= ''; - +*/ $nav .= $form->selectDate($dateselect, 'dateselect', 0, 0, 1, '', 1, 0); -$nav .= ' '; -$nav .= '
'; +//$nav .= ' '; +$nav .= ' '; +//$nav .= ''; // Must be after the nav definition -$param .= '&year='.$year.'&month='.$month.($day ? '&day='.$day : ''); +$param .= '&year='.urlencode($year).'&month='.urlencode($month).($day ? '&day='.urlencode($day) : ''); //print 'x'.$param; - - -$tabactive = 'cardpertype'; +$tabactive = ''; +if ($action == 'show_month') $tabactive = 'cardmonth'; +if ($action == 'show_week') $tabactive = 'cardweek'; +if ($action == 'show_day') $tabactive = 'cardday'; +if ($action == 'show_list') $tabactive = 'cardlist'; +if ($action == 'show_peruser') $tabactive = 'cardperuser'; +if ($action == 'show_pertype') $tabactive = 'cardpertype'; $paramnoaction = preg_replace('/action=[a-z_]+/', '', $param); $head = calendars_prepare_head($paramnoaction); -dol_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); -print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, $listofextcals, $actioncode, $usergroup, '', $resourceid); -dol_fiche_end(); +print '
'."\n"; $showextcals = $listofextcals; // Legend @@ -334,10 +374,73 @@ if ($conf->use_javascript_ajax) } } +$massactionbutton = ''; + +$viewmode = ''; +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("List"), 'object_list-alt', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewList").''; + +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("ViewCal"), 'object_calendar', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewCal").''; + +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("ViewWeek"), 'object_calendarweek', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewWeek").''; + +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("ViewDay"), 'object_calendarday', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewDay").''; + +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("ViewPerUser"), 'object_calendarperuser', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewPerUser").''; + +$viewmode .= ''; + + +$newcardbutton = ''; +if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) +{ + $tmpforcreatebutton = dol_getdate(dol_now(), true); + + $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$tmpforcreatebutton['year']; + + //$param='month='.$monthshown.'&year='.$year; + $hourminsec = '100000'; + $newcardbutton .= dolGetButtonTitle($langs->trans("AddAction"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.sprintf("%04d%02d%02d", $tmpforcreatebutton['year'], $tmpforcreatebutton['mon'], $tmpforcreatebutton['mday']).$hourminsec.'&backtopage='.urlencode($_SERVER["PHP_SELF"].($newparam ? '?'.$newparam : ''))); +} + +print_barre_liste($langs->trans("Agenda"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, -1, 'object_action', 0, $nav.''.$newcardbutton, '', $limit, 1, 0, 1, $viewmode); $link = ''; -print load_fiche_titre($s, $link.'     '.$nav, ''); +//print load_fiche_titre('', $link.'     '.$nav.' '.$newcardbutton, ''); + +// Local calendar +$newtitle = '
'; +$newtitle .= ' '.$langs->trans("LocalAgenda").'   '; +$newtitle .= '
'; +//$newtitle=$langs->trans($title); + +$s = $newtitle; + +print $s; + +print '
'; +print_actions_filter($form, $canedit, $search_status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); +print '
'; // Get event in an array @@ -377,7 +480,12 @@ if (!empty($actioncode)) if ($actioncode == 'AC_NON_AUTO') $sql .= " AND ca.type != 'systemauto'"; elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND ca.type = 'systemauto'"; else { - $sql .= " AND ca.code IN ('".implode("','", explode(',', $actioncode))."')"; + if (is_array($actioncode)) + { + $sql .= " AND ca.code IN ('".implode("','", $actioncode)."')"; + } else { + $sql .= " AND ca.code IN ('".implode("','", explode(',', $actioncode))."')"; + } } } } @@ -430,7 +538,7 @@ if ($filtert > 0 || $usergroup > 0) $sql .= ' ORDER BY fk_user_action, datep'; //fk_user_action //print $sql; -dol_syslog("comm/action/index.php", LOG_DEBUG); +dol_syslog("comm/action/pertype.php", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -529,6 +637,7 @@ if ($resql) } $i++; } + $db->free($resql); } else { dol_print_error($db); } @@ -536,6 +645,7 @@ if ($resql) $maxnbofchar = 18; $cachethirdparties = array(); $cachecontacts = array(); +$cacheusers = array(); // Define theme_datacolor array $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/theme_vars.inc.php"; @@ -557,11 +667,10 @@ $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter $newparam .= '&viewweek=1'; -echo ''; +print ''; echo ''; echo ''; echo ''; -echo '
'; // Line header with list of days @@ -603,6 +712,7 @@ $sql = "SELECT code, color, libelle as label FROM ".MAIN_DB_PREFIX."c_actioncomm $resql = $db->query($sql); while ($obj = $db->fetch_object($resql)) { + $typeofevents[$obj->code] = $obj->code; $colorsbytype[$obj->code] = $obj->color; $labelbytype[$obj->code] = $obj->label; } @@ -616,7 +726,7 @@ foreach ($typeofevents as $typeofevent) { $var = !$var; echo ""; - echo ''.$username->getNomUrl(1).''; + echo ''.$typeofevent.''; $tmpday = $sav; // Lopp on each day of week @@ -642,7 +752,7 @@ foreach ($typeofevents as $typeofevent) if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; if ($today) $style = 'cal_today_peruser'; - show_day_events_pertype($username, $tmpday, $tmpmonth, $tmpyear, $monthshown, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); + show_day_events_pertype($typeofevent, $tmpday, $tmpmonth, $tmpyear, $mont, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); $i++; } @@ -651,7 +761,7 @@ foreach ($typeofevents as $typeofevent) } echo "\n"; - +echo "
"; if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { @@ -678,6 +788,9 @@ if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) */ } +print "\n".''; +print "\n"; + // Add js code to manage click on a box print ''; - } - } - } + $out .= ''; + $out .= ''; + } + } + } return $out; } @@ -1975,7 +1975,7 @@ class ExtraFields foreach ($extralabels as $key => $value) { if (!empty($onlykey) && $onlykey != '@GETPOSTISSET' && $key != $onlykey) continue; - if (!empty($onlykey) && $onlykey == '@GETPOSTISSET' && ! GETPOSTISSET('options_'.$key)) continue; + if (!empty($onlykey) && $onlykey == '@GETPOSTISSET' && !GETPOSTISSET('options_'.$key)) continue; $key_type = $this->attributes[$object->table_element]['type'][$key]; if ($key_type == 'separate') continue; @@ -1996,8 +1996,8 @@ class ExtraFields if ($this->attributes[$object->table_element]['required'][$key]) // Value is required { // Check if empty without using GETPOST, value can be alpha, int, array, etc... - if ((!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] != 'select' && $_POST["options_".$key] != '0') - || (!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] == 'select') + if ((!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] != 'select' && $_POST["options_".$key] != '0') + || (!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] == 'select') || (is_array($_POST["options_".$key]) && empty($_POST["options_".$key]))) { //print 'ccc'.$value.'-'.$this->attributes[$object->table_element]['required'][$key]; diff --git a/htdocs/core/class/hookmanager.class.php b/htdocs/core/class/hookmanager.class.php index 089e9fb6717..c1d11c9290b 100644 --- a/htdocs/core/class/hookmanager.class.php +++ b/htdocs/core/class/hookmanager.class.php @@ -144,7 +144,7 @@ class HookManager */ public function executeHooks($method, $parameters = array(), &$object = '', &$action = '') { - if (!is_array($this->hooks) || empty($this->hooks)) return ''; + if (!is_array($this->hooks) || empty($this->hooks)) return 0; // No hook available, do nothing. $parameters['context'] = join(':', $this->contextarray); //dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']); @@ -225,14 +225,14 @@ class HookManager // Loop on each hook to qualify modules that have declared context $modulealreadyexecuted = array(); - $resaction = 0; $error = 0; $result = ''; + $resaction = 0; $error = 0; foreach ($this->hooks as $context => $modules) // $this->hooks is an array with context as key and value is an array of modules that handle this context { if (!empty($modules)) { foreach ($modules as $module => $actionclassinstance) { - //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction." result=".$result."
\n"; + //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
\n"; // test to avoid running twice a hook, when a module implements several active contexts if (in_array($module, $modulealreadyexecuted)) continue; @@ -290,7 +290,7 @@ class HookManager } } - //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction." result=".$result."
\n"; + //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
\n"; unset($actionclassinstance->results); unset($actionclassinstance->resprints); @@ -298,6 +298,6 @@ class HookManager } } - return ($error ?-1 : $resaction); + return ($error ? -1 : $resaction); } } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index c6ebb7511bb..3350507e543 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -647,7 +647,7 @@ class Form $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(); @@ -666,11 +666,11 @@ class Form $ret .= ''; - if (empty($conf->dol_optimize_smallscreen)) $ret .= ajax_combobox('.'.$name.'select'); + if (empty($conf->dol_optimize_smallscreen)) $ret .= ajax_combobox('.'.$name.'select'); // Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button $ret .= ''; // Hidden button BEFORE so it is the one used when we submit with ENTER. - $ret .= ''; + $ret .= ''; $ret .= '
'; if (!empty($conf->use_javascript_ajax)) @@ -5591,15 +5591,15 @@ class Form { if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); '; - if ($addnowlink == 1) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H', 'tzuser').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; - } elseif ($addnowlink == 2) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; - } + if ($addnowlink == 1) + { + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H', 'tzuser').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; + } elseif ($addnowlink == 2) + { + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; + } if ($fullday) $reset_scripts .= ' } '; } @@ -5608,15 +5608,15 @@ class Form { if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); '; - if ($addnowlink == 1) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M', 'tzuser').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; - } elseif ($addnowlink == 2) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; - } + if ($addnowlink == 1) + { + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M', 'tzuser').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; + } elseif ($addnowlink == 2) + { + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; + } if ($fullday) $reset_scripts .= ' } '; } // If reset_scripts is not empty, print the link with the reset_scripts in the onClick @@ -5684,20 +5684,20 @@ class Form { global $langs; - $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month'), 'w'=>$langs->trans('Weeks'), 'd'=>$langs->trans('Days'), 'h'=>$langs->trans('Hours'), 'i'=>$langs->trans('Minutes')); + $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month'), 'w'=>$langs->trans('Weeks'), 'd'=>$langs->trans('Days'), 'h'=>$langs->trans('Hours'), 'i'=>$langs->trans('Minutes')); - $retstring = '"; + $retstring = '"; - return $retstring; - } + return $retstring; + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** @@ -6545,23 +6545,23 @@ class Form foreach ($array as $key => $val) { - /* var_dump($val); + /* var_dump($val); var_dump(array_key_exists('enabled', $val)); var_dump(!$val['enabled']);*/ - if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) - { - unset($array[$key]); // We don't want this field - continue; - } - if ($val['label']) - { - if (!empty($val['langfile']) && is_object($langs)) { - $langs->load($val['langfile']); - } + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) + { + unset($array[$key]); // We don't want this field + continue; + } + if ($val['label']) + { + if (!empty($val['langfile']) && is_object($langs)) { + $langs->load($val['langfile']); + } - $lis .= '
  • '; - $listcheckedstring .= (empty($val['checked']) ? '' : $key.','); - } + $lis .= '
  • '; + $listcheckedstring .= (empty($val['checked']) ? '' : $key.','); + } } $out = ' @@ -7538,20 +7538,20 @@ class Form } /** - * Return HTML to show the search and clear seach button + * Return HTML to show the search and clear search button * * @param string $cssclass CSS class * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes - * @param string $massactionname Mass action button name that will launch an action on the selected items + * @param string $massactionname Mass action button name that will launch an action on the selected items * @return string */ - public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction") + public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction") { global $conf, $langs; $out = ''; $id = uniqid(); - if (!empty($conf->use_javascript_ajax)) $out .= '
    '; + if (!empty($conf->use_javascript_ajax)) $out .= '
    '; $out .= ''; - print '
    '; + print '
    '; - print ''; + print '
    '; - // Load shipments already done for same order - $object->loadExpeditions(); + // Load shipments already done for same order + $object->loadExpeditions(); - if ($numAsked) - { - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - if (!empty($conf->stock->enabled)) - { + print ''; + if (!empty($conf->stock->enabled)) + { if (empty($conf->productbatch->enabled)) { - print ''; + print ''; } else { print ''; } - } - print "\n"; - } + } + print "\n"; + } - $indiceAsked = 0; - while ($indiceAsked < $numAsked) - { - $product = new Product($db); + $indiceAsked = 0; + while ($indiceAsked < $numAsked) + { + $product = new Product($db); - $line = $object->lines[$indiceAsked]; + $line = $object->lines[$indiceAsked]; - $parameters = array('i' => $indiceAsked, 'line' => $line, 'num' => $numAsked); - $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + $parameters = array('i' => $indiceAsked, 'line' => $line, 'num' => $numAsked); + $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action); + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (empty($reshook)) - { - // Show product and description - $type = $line->product_type ? $line->product_type : $line->fk_product_type; - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (!empty($line->date_start)) $type = 1; - if (!empty($line->date_end)) $type = 1; + if (empty($reshook)) + { + // Show product and description + $type = $line->product_type ? $line->product_type : $line->fk_product_type; + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($line->date_start)) $type = 1; + if (!empty($line->date_end)) $type = 1; - print ''."\n"; - print ''."\n"; + print ''."\n"; + print ''."\n"; - // Product label - if ($line->fk_product > 0) // If predefined product - { - $product->fetch($line->fk_product); - $product->load_stock('warehouseopen'); // Load all $product->stock_warehouse[idwarehouse]->detail_batch - //var_dump($product->stock_warehouse[1]); + // Product label + if ($line->fk_product > 0) // If predefined product + { + $product->fetch($line->fk_product); + $product->load_stock('warehouseopen'); // Load all $product->stock_warehouse[idwarehouse]->detail_batch + //var_dump($product->stock_warehouse[1]); - print ''; - } else { - print "'; + } else { + print "\n"; - } + // Show range + print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end)); + print "\n"; + } - // Qty - print ''; - $qtyProdCom = $line->qty; + // Qty + print ''; + $qtyProdCom = $line->qty; - // Qty already shipped - print ''; + // Qty already shipped + print ''; - // Qty to ship - $quantityAsked = $line->qty; + // Qty to ship + $quantityAsked = $line->qty; if ($line->product_type == 1 && empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $quantityToBeDelivered = 0; } else { $quantityToBeDelivered = $quantityAsked - $quantityDelivered; } - $warehouse_id = GETPOST('entrepot_id', 'int'); + $warehouse_id = GETPOST('entrepot_id', 'int'); $warehouseObject = null; if ($warehouse_id > 0 || !($line->fk_product > 0) || empty($conf->stock->enabled)) // If warehouse was already selected or if product is not a predefined, we go into this part with no multiwarehouse selection { - print ''; + print ''; //ship from preselected location $stock = + $product->stock_warehouse[$warehouse_id]->real; // Convert to number $deliverableQty = min($quantityToBeDelivered, $stock); @@ -2523,7 +2523,7 @@ if ($action == 'create') $genallowed = $user->rights->expedition->lire; $delallowed = $user->rights->expedition->creer; - print $formfile->showdocuments('expedition', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + print $formfile->showdocuments('expedition', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); // Show links to link elements diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php index 46d964756ff..f601f483d89 100644 --- a/htdocs/expedition/class/expedition.class.php +++ b/htdocs/expedition/class/expedition.class.php @@ -3,7 +3,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke * Copyright (C) 2006-2012 Laurent Destailleur - * Copyright (C) 2011-2017 Juanjo Menent + * Copyright (C) 2011-2020 Juanjo Menent * Copyright (C) 2013 Florian Henry * Copyright (C) 2014 Cedric GROSS * Copyright (C) 2014-2015 Marcos García @@ -1067,7 +1067,7 @@ class Expedition extends CommonObject if (isset($this->trueWeight)) $this->weight = trim($this->trueWeight); if (isset($this->note_private)) $this->note = trim($this->note_private); if (isset($this->note_public)) $this->note = trim($this->note_public); - if (isset($this->modelpdf)) $this->modelpdf = trim($this->modelpdf); + if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); @@ -1508,6 +1508,9 @@ class Expedition extends CommonObject { $this->db->commit(); + // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive + $this->deleteEcmFiles(); + // We delete PDFs $ref = dol_sanitizeFileName($this->ref); if (!empty($conf->expedition->dir_output)) diff --git a/htdocs/expedition/index.php b/htdocs/expedition/index.php index 849e2054cd6..6f21683cc69 100644 --- a/htdocs/expedition/index.php +++ b/htdocs/expedition/index.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2011 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2020 Tobias Sekan * * 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 @@ -84,7 +85,7 @@ if (!$user->rights->societe->client->voir && !$socid) $sql .= $clause." sc.fk_user = ".$user->id; $clause = " AND "; } -$sql .= $clause." e.fk_statut = 0"; +$sql .= $clause." e.fk_statut = ".Expedition::STATUS_DRAFT; $sql .= " AND e.entity IN (".getEntity('expedition').")"; if ($socid) $sql .= " AND c.fk_soc = ".$socid; @@ -96,7 +97,13 @@ if ($resql) print '
    '; print '
    '.$langs->trans("Description").''.$langs->trans("QtyOrdered").''.$langs->trans("QtyShipped").''.$langs->trans("QtyToShip"); + if ($numAsked) + { + print '
    '.$langs->trans("Description").''.$langs->trans("QtyOrdered").''.$langs->trans("QtyShipped").''.$langs->trans("QtyToShip"); if (empty($conf->productbatch->enabled)) { - print '
    '.$langs->trans("Fill").''; - print ' / '; + print '
    '.$langs->trans("Fill").''; + print ' / '; } else { print '
    '; } print ''.$langs->trans("Reset").''; - print '
    '.$langs->trans("Warehouse").' ('.$langs->trans("Stock").')'.$langs->trans("Warehouse").' ('.$langs->trans("Stock").')'.$langs->trans("Warehouse").' / '.$langs->trans("Batch").' ('.$langs->trans("Stock").')
    '; - print ''; // ancre pour retourner sur la ligne + print ''; + print ''; // ancre pour retourner sur la ligne - // Show product and description - $product_static->type = $line->fk_product_type; - $product_static->id = $line->fk_product; - $product_static->ref = $line->ref; - $product_static->status_batch = $line->product_tobatch; - $text = $product_static->getNomUrl(1); - $text .= ' - '.(!empty($line->label) ? $line->label : $line->product_label); - $description = ($conf->global->PRODUIT_DESC_IN_FORM ? '' : dol_htmlentitiesbr($line->desc)); - print $form->textwithtooltip($text, $description, 3, '', '', $i); + // Show product and description + $product_static->type = $line->fk_product_type; + $product_static->id = $line->fk_product; + $product_static->ref = $line->ref; + $product_static->status_batch = $line->product_tobatch; + $text = $product_static->getNomUrl(1); + $text .= ' - '.(!empty($line->label) ? $line->label : $line->product_label); + $description = ($conf->global->PRODUIT_DESC_IN_FORM ? '' : dol_htmlentitiesbr($line->desc)); + print $form->textwithtooltip($text, $description, 3, '', '', $i); - // Show range - print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end)); + // Show range + print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end)); - // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { - print ($line->desc && $line->desc != $line->product_label) ? '
    '.dol_htmlentitiesbr($line->desc) : ''; - } + // Add description in form + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) + { + print ($line->desc && $line->desc != $line->product_label) ? '
    '.dol_htmlentitiesbr($line->desc) : ''; + } - print '
    "; - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + print '"; + if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); + else $text = img_object($langs->trans('Product'), 'product'); - if (!empty($line->label)) { - $text .= ' '.$line->label.''; - print $form->textwithtooltip($text, $line->desc, 3, '', '', $i); - } else { - print $text.' '.nl2br($line->desc); - } + if (!empty($line->label)) { + $text .= ' '.$line->label.''; + print $form->textwithtooltip($text, $line->desc, 3, '', '', $i); + } else { + print $text.' '.nl2br($line->desc); + } - // Show range - print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end)); - print "'.$line->qty; - print ''; - print ''.$line->qty; + print ''; + print ''; - $quantityDelivered = $object->expeditions[$line->id]; - print $quantityDelivered; - print ''; - print ''; + $quantityDelivered = $object->expeditions[$line->id]; + print $quantityDelivered; + print ''; + print '
    '; print ''; - print ''; + print ''; + print ''; if ($num) { @@ -156,13 +163,21 @@ $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); + + print '
    '; + print '
    '.$langs->trans("SendingsToValidate").'
    '; + print $langs->trans("SendingsToValidate").' '; + print ''; + print ''.$num.''; + print ''; + print '
    '; + print ''; + print ''; + print ''; + if ($num) { $i = 0; - print '
    '; - print '
    '; + print $langs->trans("LastSendings").' '; + print ''; + print ''.$num.''; + print ''; + print '
    '; - print ''; - print ''; while ($i < $num) { $obj = $db->fetch_object($resql); @@ -189,8 +204,10 @@ if ($resql) print ''; $i++; } - print "
    '.$langs->trans("LastSendings", $num).'

    "; + } else { + print ''.$langs->trans("None").''; } + print "
    "; $db->free($resql); } else dol_print_error($db); @@ -214,13 +231,21 @@ if ($resql) $langs->load("orders"); $num = $db->num_rows($resql); + + print '
    '; + print ''; + + print ''; + print ''; + print ''; + if ($num) { $i = 0; - print '
    '; - print '
    '.$langs->trans("OrdersToProcess").' '; + print ''; + print ''.$num.''; + print ''; + print '
    '; - print ''; - print ''; while ($i < $num && $i < 10) { $obj = $db->fetch_object($resql); @@ -254,9 +279,11 @@ if ($resql) print ''; print ''; } - - print "
    '.$langs->trans("OrdersToProcess").' '.$num.'

    "; + } else { + print ''.$langs->trans("None").''; } + + print "
    "; } else dol_print_error($db); diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index d4f09f793bc..023b114835a 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2019 Laurent Destailleur + * Copyright (C) 2004-2020 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2015-2017 Alexandre Spangaro * Copyright (C) 2017 Ferran Marcet @@ -115,14 +115,14 @@ $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object- if ($object->id > 0) { - // Check current user can read this expense report - $canread = 0; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; - if (!$canread) - { - accessforbidden(); - } + // Check current user can read this expense report + $canread = 0; + if (!empty($user->rights->expensereport->readall)) $canread = 1; + if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; + if (!$canread) + { + accessforbidden(); + } } @@ -145,243 +145,243 @@ if (empty($reshook)) } $action = ''; - $fk_project = ''; - $date_start = ''; - $date_end = ''; - $date = ''; - $comments = ''; - $vatrate = ''; - $value_unit_ht = ''; - $value_unit = ''; - $qty = 1; - $fk_c_type_fees = -1; + $fk_project = ''; + $date_start = ''; + $date_end = ''; + $date = ''; + $comments = ''; + $vatrate = ''; + $value_unit_ht = ''; + $value_unit = ''; + $qty = 1; + $fk_c_type_fees = -1; } include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; if (GETPOSTISSET('sendit')) // If we just submit a file { - if ($action == 'updateline') $action = 'editline'; // To avoid to make the updateline now - else $action = ''; // To avoid to make the addline now + if ($action == 'updateline') $action = 'editline'; // To avoid to make the updateline now + else $action = ''; // To avoid to make the addline now } - include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + 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 - // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->expensereport->creer) - { - if (1 == 0 && !GETPOST('clone_content', 'alpha') && !GETPOST('clone_receivers', 'alpha')) - { - setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); - } else { - if ($object->id > 0) - { - // Because createFromClone modifies the object, we must clone it so that we can restore it later if it fails - $orig = clone $object; + // Action clone object + if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->expensereport->creer) + { + if (1 == 0 && !GETPOST('clone_content', 'alpha') && !GETPOST('clone_receivers', 'alpha')) + { + setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); + } else { + if ($object->id > 0) + { + // Because createFromClone modifies the object, we must clone it so that we can restore it later if it fails + $orig = clone $object; - $result = $object->createFromClone($user, GETPOST('fk_user_author', 'int')); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $object = $orig; - $action = ''; - } - } - } - } + $result = $object->createFromClone($user, GETPOST('fk_user_author', 'int')); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $object = $orig; + $action = ''; + } + } + } + } - if ($action == 'confirm_delete' && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->supprimer) - { - $object = new ExpenseReport($db); - $result = $object->fetch($id); - $result = $object->delete($user); - if ($result >= 0) - { - header("Location: index.php"); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + if ($action == 'confirm_delete' && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->supprimer) + { + $object = new ExpenseReport($db); + $result = $object->fetch($id); + $result = $object->delete($user); + if ($result >= 0) + { + header("Location: index.php"); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } - if ($action == 'add' && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); + if ($action == 'add' && $user->rights->expensereport->creer) + { + $object = new ExpenseReport($db); - $object->date_debut = $date_start; - $object->date_fin = $date_end; + $object->date_debut = $date_start; + $object->date_fin = $date_end; - $object->fk_user_author = GETPOST('fk_user_author', 'int'); - if (!($object->fk_user_author > 0)) $object->fk_user_author = $user->id; + $object->fk_user_author = GETPOST('fk_user_author', 'int'); + if (!($object->fk_user_author > 0)) $object->fk_user_author = $user->id; - $fuser = new User($db); - $fuser->fetch($object->fk_user_author); + $fuser = new User($db); + $fuser->fetch($object->fk_user_author); - $object->fk_statut = 1; - $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int'); - $object->fk_user_validator = GETPOST('fk_user_validator', 'int'); - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); - // Fill array 'array_options' with data from add form - if (!$error) - { - $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; - } + $object->fk_statut = 1; + $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int'); + $object->fk_user_validator = GETPOST('fk_user_validator', 'int'); + $object->note_public = GETPOST('note_public', 'none'); + $object->note_private = GETPOST('note_private', 'none'); + // Fill array 'array_options' with data from add form + if (!$error) + { + $ret = $extrafields->setOptionalsFromPost(null, $object); + if ($ret < 0) $error++; + } - if (!$error && empty($conf->global->EXPENSEREPORT_ALLOW_OVERLAPPING_PERIODS) && $object->periode_existe($fuser, $object->date_debut, $object->date_fin)) - { - $error++; - setEventMessages($langs->trans("ErrorDoubleDeclaration"), null, 'errors'); - $action = 'create'; - } + if (!$error && empty($conf->global->EXPENSEREPORT_ALLOW_OVERLAPPING_PERIODS) && $object->periode_existe($fuser, $object->date_debut, $object->date_fin)) + { + $error++; + setEventMessages($langs->trans("ErrorDoubleDeclaration"), null, 'errors'); + $action = 'create'; + } - if (!$error) - { - $db->begin(); + if (!$error) + { + $db->begin(); - $id = $object->create($user); - if ($id <= 0) - { - $error++; - } + $id = $object->create($user); + if ($id <= 0) + { + $error++; + } - if (!$error) - { - $db->commit(); - Header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $db->rollback(); - $action = 'create'; - } - } - } + if (!$error) + { + $db->commit(); + Header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); + $action = 'create'; + } + } + } - if ($action == 'update' && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'update' && $user->rights->expensereport->creer) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $object->date_debut = $date_start; - $object->date_fin = $date_end; + $object->date_debut = $date_start; + $object->date_fin = $date_end; - if ($object->fk_statut < 3) - { - $object->fk_user_validator = GETPOST('fk_user_validator', 'int'); - } + if ($object->fk_statut < 3) + { + $object->fk_user_validator = GETPOST('fk_user_validator', 'int'); + } - $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int'); - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); - $object->fk_user_modif = $user->id; + $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int'); + $object->note_public = GETPOST('note_public', 'none'); + $object->note_private = GETPOST('note_private', 'none'); + $object->fk_user_modif = $user->id; - $result = $object->update($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $result = $object->update($user); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } - if ($action == 'update_extras') - { - $object->oldcopy = dol_clone($object); + if ($action == 'update_extras') + { + $object->oldcopy = dol_clone($object); - // Fill array 'array_options' with data from update form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); - if ($ret < 0) $error++; + // Fill array 'array_options' with data from update form + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + if ($ret < 0) $error++; - if (!$error) - { - // Actions on extra fields - $result = $object->insertExtraFields('EXPENSEREPORT_MODIFY'); + if (!$error) + { + // Actions on extra fields + $result = $object->insertExtraFields('EXPENSEREPORT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - } + } - if ($error) - $action = 'edit_extras'; - } + if ($error) + $action = 'edit_extras'; + } - if ($action == "confirm_validate" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) - { - $error = 0; + if ($action == "confirm_validate" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) + { + $error = 0; - $db->begin(); + $db->begin(); - $object = new ExpenseReport($db); - $object->fetch($id); + $object = new ExpenseReport($db); + $object->fetch($id); - $result = $object->setValidate($user); + $result = $object->setValidate($user); - if ($result >= 0) - { - // 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 + if ($result >= 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } - if (!$error && $result > 0 && $object->fk_user_validator > 0) - { - $langs->load("mails"); + if (!$error && $result > 0 && $object->fk_user_validator > 0) + { + $langs->load("mails"); - // TO - $destinataire = new User($db); - $destinataire->fetch($object->fk_user_validator); - $emailTo = $destinataire->email; + // TO + $destinataire = new User($db); + $destinataire->fetch($object->fk_user_validator); + $emailTo = $destinataire->email; - // FROM - $expediteur = new User($db); - $expediteur->fetch($object->fk_user_author); - $emailFrom = $expediteur->email; + // FROM + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_author); + $emailFrom = $expediteur->email; - if ($emailTo && $emailFrom) - { - $filename = array(); $filedir = array(); $mimetype = array(); + if ($emailTo && $emailFrom) + { + $filename = array(); $filedir = array(); $mimetype = array(); - // SUBJECT - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForApproval"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForApproval"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; - $message = $langs->transnoentities("ExpenseReportWaitingForApprovalMessage", $expediteur->getFullName($langs), get_date_range($object->date_debut, $object->date_fin, '', $langs), $link); + $message = $langs->transnoentities("ExpenseReportWaitingForApprovalMessage", $expediteur->getFullName($langs), get_date_range($object->date_debut, $object->date_fin, '', $langs), $link); - // Rebuild pdf - /* + // Rebuild pdf + /* $object->setDocModel($user,""); $resultPDF = expensereport_pdf_create($db,$id,'',"",$langs); @@ -392,38 +392,38 @@ if (empty($reshook)) array_push($mimetype,"application/pdf"); */ - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { - // SEND - $result = $mailfile->sendfile(); - if ($result) - { - $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); - setEventMessages($mesg, null, 'mesgs'); - } else { - $langs->load("other"); - if ($mailfile->error) - { - $mesg = ''; - $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg .= '
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } else { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } - } else { - setEventMessages($mailfile->error, $mailfile->errors, 'errors'); - $action = ''; - } - } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } + if ($mailfile) + { + // SEND + $result = $mailfile->sendfile(); + if ($result) + { + $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); + setEventMessages($mesg, null, 'mesgs'); + } else { + $langs->load("other"); + if ($mailfile->error) + { + $mesg = ''; + $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg .= '
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } else { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } else { + setEventMessages($mailfile->error, $mailfile->errors, 'errors'); + $action = ''; + } + } else { + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action = ''; + } + } if (!$error) { @@ -433,37 +433,37 @@ if (empty($reshook)) } else { $db->rollback(); } - } + } - if ($action == "confirm_save_from_refuse" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); - $object->fetch($id); - $result = $object->set_save_from_refuse($user); + if ($action == "confirm_save_from_refuse" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) + { + $object = new ExpenseReport($db); + $object->fetch($id); + $result = $object->set_save_from_refuse($user); - if ($result > 0) - { - // 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 + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + if ($result > 0) + { + // Send mail // TO $destinataire = new User($db); @@ -477,19 +477,19 @@ if (empty($reshook)) if ($emailFrom && $emailTo) { - $filename = array(); $filedir = array(); $mimetype = array(); + $filename = array(); $filedir = array(); $mimetype = array(); - // SUBJECT - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForReApproval"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForReApproval"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; $dateRefusEx = explode(" ", $object->date_refuse); - $message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link); + $message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link); // Rebuild pdf /* @@ -507,75 +507,75 @@ if (empty($reshook)) */ - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { - // SEND - $result = $mailfile->sendfile(); - if ($result) - { - $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - $langs->load("other"); - if ($mailfile->error) - { - $mesg = ''; - $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg .= '
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } else { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } - } else { - setEventMessages($mailfile->error, $mailfile->errors, 'errors'); - $action = ''; - } - } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + if ($mailfile) + { + // SEND + $result = $mailfile->sendfile(); + if ($result) + { + $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + $langs->load("other"); + if ($mailfile->error) + { + $mesg = ''; + $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg .= '
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } else { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } else { + setEventMessages($mailfile->error, $mailfile->errors, 'errors'); + $action = ''; + } + } else { + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action = ''; + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } - // Approve - if ($action == "confirm_approve" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) - { - $object = new ExpenseReport($db); - $object->fetch($id); + // Approve + if ($action == "confirm_approve" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $result = $object->setApproved($user); + $result = $object->setApproved($user); - if ($result > 0) - { - // 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 + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + if ($result > 0) + { + // Send mail // TO $destinataire = new User($db); @@ -584,7 +584,7 @@ if (empty($reshook)) // CC $emailCC = $conf->global->NDF_CC_EMAILS; - if (empty($emailTo)) $emailTo = $emailCC; + if (empty($emailTo)) $emailTo = $emailCC; // FROM $expediteur = new User($db); @@ -593,21 +593,21 @@ if (empty($reshook)) if ($emailFrom && $emailTo) { - $filename = array(); $filedir = array(); $mimetype = array(); + $filename = array(); $filedir = array(); $mimetype = array(); - // SUBJECT - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportApproved"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportApproved"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; - $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); + $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); - // Rebuilt pdf - /* + // Rebuilt pdf + /* $object->setDocModel($user,""); $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); @@ -621,103 +621,103 @@ if (empty($reshook)) } */ - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { - // SEND - $result = $mailfile->sendfile(); - if ($result) - { - $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - $langs->load("other"); - if ($mailfile->error) - { - $mesg = ''; - $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg .= '
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } else { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } - } else { - setEventMessages($mailfile->error, $mailfile->errors, 'errors'); - $action = ''; - } + if ($mailfile) + { + // SEND + $result = $mailfile->sendfile(); + if ($result) + { + $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + $langs->load("other"); + if ($mailfile->error) + { + $mesg = ''; + $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg .= '
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } else { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } else { + setEventMessages($mailfile->error, $mailfile->errors, 'errors'); + $action = ''; + } } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } else { + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action = ''; + } + } else { setEventMessages($langs->trans("FailedtoSetToApprove"), null, 'warnings'); $action = ''; } } - if ($action == "confirm_refuse" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == "confirm_refuse" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) + { + $object = new ExpenseReport($db); + $object->fetch($id); $detailRefuse = GETPOST('detail_refuse', 'alpha'); - $result = $object->setDeny($user, $detailRefuse); + $result = $object->setDeny($user, $detailRefuse); - if ($result > 0) - { - // 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 + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + if ($result > 0) + { + // Send mail - // TO - $destinataire = new User($db); - $destinataire->fetch($object->fk_user_author); - $emailTo = $destinataire->email; + // TO + $destinataire = new User($db); + $destinataire->fetch($object->fk_user_author); + $emailTo = $destinataire->email; - // FROM - $expediteur = new User($db); - $expediteur->fetch($object->fk_user_refuse); - $emailFrom = $expediteur->email; + // FROM + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_refuse); + $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { - $filename = array(); $filedir = array(); $mimetype = array(); + if ($emailFrom && $emailTo) + { + $filename = array(); $filedir = array(); $mimetype = array(); - // SUBJECT - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportRefused"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportRefused"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; - $message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailRefuse, $link); + $message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailRefuse, $link); - // Rebuilt pdf - /* + // Rebuilt pdf + /* $object->setDocModel($user,""); $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); @@ -731,111 +731,111 @@ if (empty($reshook)) } */ - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { - // SEND - $result = $mailfile->sendfile(); - if ($result) - { - $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - $langs->load("other"); - if ($mailfile->error) - { - $mesg = ''; - $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg .= '
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } else { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } - } else { - setEventMessages($mailfile->error, $mailfile->errors, 'errors'); - $action = ''; - } - } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($langs->trans("FailedtoSetToDeny"), null, 'warnings'); - $action = ''; - } - } + if ($mailfile) + { + // SEND + $result = $mailfile->sendfile(); + if ($result) + { + $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + $langs->load("other"); + if ($mailfile->error) + { + $mesg = ''; + $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg .= '
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } else { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } else { + setEventMessages($mailfile->error, $mailfile->errors, 'errors'); + $action = ''; + } + } else { + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action = ''; + } + } else { + setEventMessages($langs->trans("FailedtoSetToDeny"), null, 'warnings'); + $action = ''; + } + } - //var_dump($user->id == $object->fk_user_validator);exit; - if ($action == "confirm_cancel" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) - { - if (!GETPOST('detail_cancel', 'alpha')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors'); - } else { - $object = new ExpenseReport($db); - $object->fetch($id); + //var_dump($user->id == $object->fk_user_validator);exit; + if ($action == "confirm_cancel" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) + { + if (!GETPOST('detail_cancel', 'alpha')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors'); + } else { + $object = new ExpenseReport($db); + $object->fetch($id); - if ($user->id == $object->fk_user_valid || $user->id == $object->fk_user_author) - { + if ($user->id == $object->fk_user_valid || $user->id == $object->fk_user_author) + { $detailCancel = GETPOST('detail_cancel', 'alpha'); - $result = $object->set_cancel($user, $detailCancel); + $result = $object->set_cancel($user, $detailCancel); - if ($result > 0) - { - // 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 + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + if ($result > 0) + { + // Send mail - // TO - $destinataire = new User($db); - $destinataire->fetch($object->fk_user_author); - $emailTo = $destinataire->email; + // TO + $destinataire = new User($db); + $destinataire->fetch($object->fk_user_author); + $emailTo = $destinataire->email; - // FROM - $expediteur = new User($db); - $expediteur->fetch($object->fk_user_cancel); - $emailFrom = $expediteur->email; + // FROM + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_cancel); + $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { - $filename = array(); $filedir = array(); $mimetype = array(); + if ($emailFrom && $emailTo) + { + $filename = array(); $filedir = array(); $mimetype = array(); - // SUBJECT - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportCanceled"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportCanceled"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; - $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailCancel, $link); + $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailCancel, $link); - // Rebuilt pdf - /* + // Rebuilt pdf + /* $object->setDocModel($user,""); $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); @@ -849,318 +849,318 @@ if (empty($reshook)) } */ - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { - // SEND - $result = $mailfile->sendfile(); - if ($result) - { - $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - $langs->load("other"); - if ($mailfile->error) - { - $mesg = ''; - $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg .= '
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } else { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } - } else { - setEventMessages($mailfile->error, $mailfile->errors, 'errors'); - $action = ''; - } - } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($langs->trans("FailedToSetToCancel"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - } + if ($mailfile) + { + // SEND + $result = $mailfile->sendfile(); + if ($result) + { + $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + $langs->load("other"); + if ($mailfile->error) + { + $mesg = ''; + $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg .= '
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } else { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } else { + setEventMessages($mailfile->error, $mailfile->errors, 'errors'); + $action = ''; + } + } else { + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action = ''; + } + } else { + setEventMessages($langs->trans("FailedToSetToCancel"), null, 'warnings'); + $action = ''; + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } - if ($action == "confirm_setdraft" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); - $object->fetch($id); - if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) - { - $result = $object->setStatut(0); + if ($action == "confirm_setdraft" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) + { + $object = new ExpenseReport($db); + $object->fetch($id); + if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) + { + $result = $object->setStatut(0); - if ($result > 0) - { - // 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 + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } else { - setEventMessages("NOT_AUTHOR", '', 'errors'); - } - } + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + setEventMessages("NOT_AUTHOR", '', 'errors'); + } + } - if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $result = $object->set_unpaid($user); + $result = $object->set_unpaid($user); - if ($result > 0) - { - // 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 + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } + } - if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $result = $object->set_unpaid($user); + $result = $object->set_unpaid($user); - if ($result > 0) - { - // 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 + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } + } - if ($action == 'set_paid' && $id > 0 && $user->rights->expensereport->to_paid) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'set_paid' && $id > 0 && $user->rights->expensereport->to_paid) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $result = $object->set_paid($id, $user); + $result = $object->set_paid($id, $user); - if ($result > 0) - { - // 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 + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + if ($result > 0) + { + // Send mail - // TO - $destinataire = new User($db); - $destinataire->fetch($object->fk_user_author); - $emailTo = $destinataire->email; + // TO + $destinataire = new User($db); + $destinataire->fetch($object->fk_user_author); + $emailTo = $destinataire->email; - // FROM - $expediteur = new User($db); - $expediteur->fetch($user->id); - $emailFrom = $expediteur->email; + // FROM + $expediteur = new User($db); + $expediteur->fetch($user->id); + $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { - $filename = array(); $filedir = array(); $mimetype = array(); + if ($emailFrom && $emailTo) + { + $filename = array(); $filedir = array(); $mimetype = array(); - // SUBJECT - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportPaid"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportPaid"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; - $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); + $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); - // Generate pdf before attachment - $object->setDocModel($user, ""); - $resultPDF = expensereport_pdf_create($db, $object, '', "", $langs); + // Generate pdf before attachment + $object->setDocModel($user, ""); + $resultPDF = expensereport_pdf_create($db, $object, '', "", $langs); - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); - if ($mailfile) - { - // SEND - $result = $mailfile->sendfile(); - if ($result) - { - $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); - setEventMessages($mesg, null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - $langs->load("other"); - if ($mailfile->error) - { - $mesg = ''; - $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); - $mesg .= '
    '.$mailfile->error; - setEventMessages($mesg, null, 'errors'); - } else { - setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); - } - } - } else { - setEventMessages($mailfile->error, $mailfile->errors, 'errors'); - $action = ''; - } - } else { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($langs->trans("FailedToSetPaid"), null, 'warnings'); - $action = ''; - } - } + if ($mailfile) + { + // SEND + $result = $mailfile->sendfile(); + if ($result) + { + $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2)); + setEventMessages($mesg, null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + $langs->load("other"); + if ($mailfile->error) + { + $mesg = ''; + $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo); + $mesg .= '
    '.$mailfile->error; + setEventMessages($mesg, null, 'errors'); + } else { + setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings'); + } + } + } else { + setEventMessages($mailfile->error, $mailfile->errors, 'errors'); + $action = ''; + } + } else { + setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action = ''; + } + } else { + setEventMessages($langs->trans("FailedToSetPaid"), null, 'warnings'); + $action = ''; + } + } - if ($action == "addline" && $user->rights->expensereport->creer) - { - $error = 0; + if ($action == "addline" && $user->rights->expensereport->creer) + { + $error = 0; - // First save uploaded file - $fk_ecm_files = 0; - if (GETPOSTISSET('attachfile')) - { - $arrayoffiles = GETPOST('attachfile', 'array'); - if (is_array($arrayoffiles) && !empty($arrayoffiles[0])) - { - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0]; - $ecmfiles = new EcmFiles($db); - $ecmfiles->fetch(0, '', $relativepath); - $fk_ecm_files = $ecmfiles->id; - } - } + // First save uploaded file + $fk_ecm_files = 0; + if (GETPOSTISSET('attachfile')) + { + $arrayoffiles = GETPOST('attachfile', 'array'); + if (is_array($arrayoffiles) && !empty($arrayoffiles[0])) + { + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0]; + $ecmfiles = new EcmFiles($db); + $ecmfiles->fetch(0, '', $relativepath); + $fk_ecm_files = $ecmfiles->id; + } + } // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary. - if (empty($vatrate)) $vatrate = "0.000"; - $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate)); + if (empty($vatrate)) $vatrate = "0.000"; + $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate)); $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU'); $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU'); if (empty($value_unit)) { - $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU'); + $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU'); } $fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat', 'int'); - $qty = GETPOST('qty', 'int'); - if (empty($qty)) $qty = 1; + $qty = GETPOST('qty', 'int'); + if (empty($qty)) $qty = 1; - if (!($fk_c_type_fees > 0)) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $action = ''; - } + if (!($fk_c_type_fees > 0)) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $action = ''; + } - if ((int) $tmpvat < 0 || $tmpvat == '') - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("VAT")), null, 'errors'); - $action = ''; - } + if ((int) $tmpvat < 0 || $tmpvat == '') + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("VAT")), null, 'errors'); + $action = ''; + } - // Si aucune date n'est rentrée - if (empty($date) || $date == "--") - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - } - // Si aucun prix n'est rentré - if ($value_unit == 0) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PriceUTTC")), null, 'errors'); - } - // Warning if date out of range - if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1))) - { - $langs->load("errors"); - setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); - } + // Si aucune date n'est rentrée + if (empty($date) || $date == "--") + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); + } + // Si aucun prix n'est rentré + if ($value_unit == 0) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PriceUTTC")), null, 'errors'); + } + // Warning if date out of range + if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1))) + { + $langs->load("errors"); + setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); + } - if (!$error) - { - $type = 0; // TODO What if service ? We should take the type product/service from the type of expense report llx_c_type_fees + if (!$error) + { + $type = 0; // TODO What if service ? We should take the type product/service from the type of expense report llx_c_type_fees // Insert line - $result = $object->addline($qty, $value_unit, $fk_c_type_fees, $vatrate, $date, $comments, $fk_project, $fk_c_exp_tax_cat, $type, $fk_ecm_files); + $result = $object->addline($qty, $value_unit, $fk_c_type_fees, $vatrate, $date, $comments, $fk_project, $fk_c_exp_tax_cat, $type, $fk_ecm_files); if ($result > 0) { $ret = $object->fetch($object->id); // Reload to get new records @@ -1176,7 +1176,7 @@ if (empty($reshook)) $outputlangs->setDefaultLang($newlang); } - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } unset($qty); @@ -1191,159 +1191,159 @@ if (empty($reshook)) } else { setEventMessages($object->error, $object->errors, 'errors'); } - } + } - $action = ''; - } + $action = ''; + } - if ($action == 'confirm_delete_line' && GETPOST("confirm", 'alpha') == "yes" && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'confirm_delete_line' && GETPOST("confirm", 'alpha') == "yes" && $user->rights->expensereport->creer) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $object_ligne = new ExpenseReportLine($db); - $object_ligne->fetch(GETPOST("rowid", 'int')); - $total_ht = $object_ligne->total_ht; - $total_tva = $object_ligne->total_tva; + $object_ligne = new ExpenseReportLine($db); + $object_ligne->fetch(GETPOST("rowid", 'int')); + $total_ht = $object_ligne->total_ht; + $total_tva = $object_ligne->total_tva; - $result = $object->deleteline(GETPOST("rowid", 'int'), $user); - if ($result >= 0) - { - if ($result > 0) - { - // 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->deleteline(GETPOST("rowid", 'int'), $user); + if ($result >= 0) + { + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - $object->update_totaux_del($object_ligne->total_ht, $object_ligne->total_tva); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_GET['id']); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $object->update_totaux_del($object_ligne->total_ht, $object_ligne->total_tva); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_GET['id']); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } - if ($action == "updateline" && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == "updateline" && $user->rights->expensereport->creer) + { + $object = new ExpenseReport($db); + $object->fetch($id); - // First save uploaded file - $fk_ecm_files = 0; - if (GETPOSTISSET('attachfile')) - { - $arrayoffiles = GETPOST('attachfile', 'array'); - if (is_array($arrayoffiles) && !empty($arrayoffiles[0])) - { - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0]; - $ecmfiles = new EcmFiles($db); - $ecmfiles->fetch(0, '', $relativepath); - $fk_ecm_files = $ecmfiles->id; - } - } + // First save uploaded file + $fk_ecm_files = 0; + if (GETPOSTISSET('attachfile')) + { + $arrayoffiles = GETPOST('attachfile', 'array'); + if (is_array($arrayoffiles) && !empty($arrayoffiles[0])) + { + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0]; + $ecmfiles = new EcmFiles($db); + $ecmfiles->fetch(0, '', $relativepath); + $fk_ecm_files = $ecmfiles->id; + } + } - $rowid = $_POST['rowid']; - $type_fees_id = GETPOST('fk_c_type_fees', 'int'); + $rowid = $_POST['rowid']; + $type_fees_id = GETPOST('fk_c_type_fees', 'int'); $fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat', 'int'); - $projet_id = $fk_project; - $comments = GETPOST('comments', 'none'); - $qty = GETPOST('qty', 'int'); - $vatrate = GETPOST('vatrate', 'alpha'); + $projet_id = $fk_project; + $comments = GETPOST('comments', 'none'); + $qty = GETPOST('qty', 'int'); + $vatrate = GETPOST('vatrate', 'alpha'); - // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary. - if (empty($vatrate)) $vatrate = "0.000"; - $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate)); + // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary. + if (empty($vatrate)) $vatrate = "0.000"; + $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate)); - $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU'); - $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU'); - if (empty($value_unit)) - { - $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU'); - } + $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU'); + $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU'); + if (empty($value_unit)) + { + $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU'); + } - if (!GETPOST('fk_c_type_fees', 'int') > 0) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $action = ''; - } - if ((int) $tmpvat < 0 || $tmpvat == '') - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Vat")), null, 'errors'); - $action = ''; - } - // Warning if date out of range + if (!GETPOST('fk_c_type_fees', 'int') > 0) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $action = ''; + } + if ((int) $tmpvat < 0 || $tmpvat == '') + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Vat")), null, 'errors'); + $action = ''; + } + // Warning if date out of range if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1))) - { - $langs->load("errors"); - setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); - } + { + $langs->load("errors"); + setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); + } - if (!$error) - { - // TODO Use update method of ExpenseReportLine - $result = $object->updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $id, $fk_c_exp_tax_cat, $fk_ecm_files); - if ($result >= 0) - { - if ($result > 0) - { - // 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 + if (!$error) + { + // TODO Use update method of ExpenseReportLine + $result = $object->updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $id, $fk_c_exp_tax_cat, $fk_ecm_files); + if ($result >= 0) + { + if ($result > 0) + { + // 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->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - $result = $object->recalculer($id); + $result = $object->recalculer($id); - //header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - //exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - } + //header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + //exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } // Actions when printing a doc from card - include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; - // Actions to send emails - $triggersendname = 'EXPENSEREPORT_SENTBYMAIL'; - $autocopy = 'MAIN_MAIL_AUTOCOPY_EXPENSEREPORT_TO'; - $trackid = 'exp'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + // Actions to send emails + $triggersendname = 'EXPENSEREPORT_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_EXPENSEREPORT_TO'; + $trackid = 'exp'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - // Actions to build doc - $upload_dir = $conf->expensereport->dir_output; - $permissiontoadd = $user->rights->expensereport->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + // Actions to build doc + $upload_dir = $conf->expensereport->dir_output; + $permissiontoadd = $user->rights->expensereport->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; } @@ -1399,8 +1399,8 @@ if ($action == 'create') print ''; $defaultselectuser = $user->id; if (GETPOST('fk_user_author', 'int') > 0) $defaultselectuser = GETPOST('fk_user_author', 'int'); - $include_users = 'hierarchyme'; - if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expensereport->writeall_advance)) $include_users = array(); + $include_users = 'hierarchyme'; + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expensereport->writeall_advance)) $include_users = array(); $s = $form->select_dolusers($defaultselectuser, "fk_user_author", 0, "", 0, $include_users, '', '0,'.$conf->entity); print $s; print ''; @@ -1414,11 +1414,11 @@ if ($action == 'create') $include_users = $object->fetch_users_approver_expensereport(); if (empty($include_users)) print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateExpenseReport"); else { - $defaultselectuser = (empty($user->fk_user_expense_validator) ? $user->fk_user : $user->fk_user_expense_validator); // Will work only if supervisor has permission to approve so is inside include_users - if (!empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR)) $defaultselectuser = $conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR; // Can force default approver - if (GETPOST('fk_user_validator', 'int') > 0) $defaultselectuser = GETPOST('fk_user_validator', 'int'); - $s = $form->select_dolusers($defaultselectuser, "fk_user_validator", 1, "", ((empty($defaultselectuser) || empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR_UNCHANGEABLE)) ? 0 : 1), $include_users); - print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate")); + $defaultselectuser = (empty($user->fk_user_expense_validator) ? $user->fk_user : $user->fk_user_expense_validator); // Will work only if supervisor has permission to approve so is inside include_users + if (!empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR)) $defaultselectuser = $conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR; // Can force default approver + if (GETPOST('fk_user_validator', 'int') > 0) $defaultselectuser = GETPOST('fk_user_validator', 'int'); + $s = $form->select_dolusers($defaultselectuser, "fk_user_validator", 1, "", ((empty($defaultselectuser) || empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR_UNCHANGEABLE)) ? 0 : 1), $include_users); + print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate")); } print ''; print ''; @@ -1457,9 +1457,9 @@ if ($action == 'create') // Other attributes $parameters = array('colspan' => ' colspan="3"', 'cols' => 3); $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)) { - print $object->showOptionals($extrafields, 'edit', $parameters); + print $object->showOptionals($extrafields, 'edit', $parameters); } print ''; @@ -1485,7 +1485,7 @@ if ($action == 'create') if (!in_array($object->fk_user_author, $user->getAllChildIds(1))) { if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous) - && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) + && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) { print load_fiche_titre($langs->trans('TripCard'), '', 'trip'); @@ -1494,8 +1494,8 @@ if ($action == 'create') print ''; // End of page - llxFooter(); - $db->close(); + llxFooter(); + $db->close(); exit; } @@ -1528,15 +1528,15 @@ if ($action == 'create') $userfee = new User($db); if ($object->fk_user_author > 0) { - $userfee->fetch($object->fk_user_author); - print $userfee->getNomUrl(-1); + $userfee->fetch($object->fk_user_author); + print $userfee->getNomUrl(-1); } print ''; - // Ref - print ''.$langs->trans("Ref").''; - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', ''); - print ''; + // Ref + print ''.$langs->trans("Ref").''; + print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', ''); + print ''; print ''; print ''.$langs->trans("DateStart").''; @@ -1611,15 +1611,15 @@ if ($action == 'create') // Clone confirmation if ($action == 'clone') { - // Create an array for form - $criteriaforfilter = 'hierarchyme'; - if (!empty($user->rights->expensereport->readall)) $criteriaforfilter = ''; - $formquestion = array( - 'text' => '', - array('type' => 'other', 'name' => 'fk_user_author', 'label' => $langs->trans("SelectTargetUser"), 'value' => $form->select_dolusers((GETPOST('fk_user_author', 'int') > 0 ? GETPOST('fk_user_author', 'int') : $user->id), 'fk_user_author', 0, null, 0, $criteriaforfilter)) - ); - // Paiement incomplet. On demande si motif = escompte ou autre - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneExpenseReport', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + // Create an array for form + $criteriaforfilter = 'hierarchyme'; + if (!empty($user->rights->expensereport->readall)) $criteriaforfilter = ''; + $formquestion = array( + 'text' => '', + array('type' => 'other', 'name' => 'fk_user_author', 'label' => $langs->trans("SelectTargetUser"), 'value' => $form->select_dolusers((GETPOST('fk_user_author', 'int') > 0 ? GETPOST('fk_user_author', 'int') : $user->id), 'fk_user_author', 0, null, 0, $criteriaforfilter)) + ); + // Paiement incomplet. On demande si motif = escompte ou autre + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneExpenseReport', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } if ($action == 'save') @@ -1655,7 +1655,7 @@ if ($action == 'create') if ($action == 'setdraft') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("BrouillonnerTrip"), $langs->trans("ConfirmBrouillonnerTrip"), "confirm_setdraft", "", "", 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("BrouillonnerTrip"), $langs->trans("ConfirmBrouillonnerTrip"), "confirm_setdraft", "", "", 1); } if ($action == 'refuse') // Deny @@ -1730,10 +1730,10 @@ if ($action == 'create') print ''; if ($object->fk_user_author > 0) { - $userauthor = new User($db); - $result = $userauthor->fetch($object->fk_user_author); - if ($result < 0) dol_print_error('', $userauthor->error); - elseif ($result > 0) print $userauthor->getNomUrl(-1); + $userauthor = new User($db); + $result = $userauthor->fetch($object->fk_user_author); + if ($result < 0) dol_print_error('', $userauthor->error); + elseif ($result > 0) print $userauthor->getNomUrl(-1); } print ''; @@ -1773,8 +1773,8 @@ if ($action == 'create') if ($result > 0) print $userfee->getNomUrl(-1); if (empty($userfee->email) || !isValidEmail($userfee->email)) { - $langs->load("errors"); - print img_warning($langs->trans("ErrorBadEMail", $userfee->email)); + $langs->load("errors"); + print img_warning($langs->trans("ErrorBadEMail", $userfee->email)); } } print ''; @@ -1835,7 +1835,7 @@ if ($action == 'create') print ''; } - if ($object->fk_statut == 6) + if ($object->fk_statut == $object::STATUS_CLOSED) { /* TODO this fields are not yet filled print ''; @@ -1924,26 +1924,25 @@ if ($action == 'create') $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; $totalpaid = 0; - while ($i < $num) - { - $objp = $db->fetch_object($resql); + $num = $db->num_rows($resql); + $i = 0; $totalpaid = 0; + while ($i < $num) + { + $objp = $db->fetch_object($resql); - $paymentexpensereportstatic->id = $objp->rowid; - $paymentexpensereportstatic->datepaye = $db->jdate($objp->dp); - $paymentexpensereportstatic->ref = $objp->rowid; - $paymentexpensereportstatic->num_paiement = $objp->num_payment; - $paymentexpensereportstatic->num_payment = $objp->num_payment; - $paymentexpensereportstatic->payment_code = $objp->payment_code; + $paymentexpensereportstatic->id = $objp->rowid; + $paymentexpensereportstatic->datepaye = $db->jdate($objp->dp); + $paymentexpensereportstatic->ref = $objp->rowid; + $paymentexpensereportstatic->num_payment = $objp->num_payment; + $paymentexpensereportstatic->payment_code = $objp->payment_code; - print ''; - print ''; + print ''; + print ''; print $paymentexpensereportstatic->getNomUrl(1); print ''; - print ''.dol_print_date($db->jdate($objp->dp), 'day')."\n"; - $labeltype = $langs->trans("PaymentType".$objp->p_code) != ("PaymentType".$objp->p_code) ? $langs->trans("PaymentType".$objp->p_code) : $objp->payment_type; - print "".$labeltype.' '.$objp->num_payment."\n"; + print ''.dol_print_date($db->jdate($objp->dp), 'day')."\n"; + $labeltype = $langs->trans("PaymentType".$objp->p_code) != ("PaymentType".$objp->p_code) ? $langs->trans("PaymentType".$objp->p_code) : $objp->payment_type; + print "".$labeltype.' '.$objp->num_payment."\n"; if (!empty($conf->banque->enabled)) { $bankaccountstatic->id = $objp->baid; @@ -1964,39 +1963,39 @@ if ($action == 'create') print $bankaccountstatic->getNomUrl(1, 'transactions'); print ''; } - print ''.price($objp->amount).""; - print ''; - print ""; - $totalpaid += $objp->amount; - $i++; - } + print ''.price($objp->amount).""; + print ''; + print ""; + $totalpaid += $objp->amount; + $i++; + } if (!is_null($totalpaid)) { - $totalpaid = price2num($totalpaid); // Round $totalpaid to fix floating problem after addition into loop + $totalpaid = price2num($totalpaid); // Round $totalpaid to fix floating problem after addition into loop } - $remaintopay = price2num($object->total_ttc - $totalpaid); - $resteapayeraffiche = $remaintopay; + $remaintopay = price2num($object->total_ttc - $totalpaid); + $resteapayeraffiche = $remaintopay; - $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; - if ($object->status == ExpenseReport::STATUS_REFUSED) - { - $cssforamountpaymentcomplete = 'amountpaymentneutral'; - $resteapayeraffiche = 0; - } elseif ($object->paid == 0) - { - $cssforamountpaymentcomplete = 'amountpaymentneutral'; - } - print ''.$langs->trans("AlreadyPaid").':'.price($totalpaid).''; - print ''.$langs->trans("AmountExpected").':'.price($object->total_ttc).''; + if ($object->status == ExpenseReport::STATUS_REFUSED) + { + $cssforamountpaymentcomplete = 'amountpaymentneutral'; + $resteapayeraffiche = 0; + } elseif ($object->paid == 0) + { + $cssforamountpaymentcomplete = 'amountpaymentneutral'; + } + print ''.$langs->trans("AlreadyPaid").':'.price($totalpaid).''; + print ''.$langs->trans("AmountExpected").':'.price($object->total_ttc).''; - print ''.$langs->trans("RemainderToPay").':'; - print ''.price($resteapayeraffiche).''; + print ''.$langs->trans("RemainderToPay").':'; + print ''.price($resteapayeraffiche).''; - $db->free($resql); + $db->free($resql); } else { - dol_print_error($db); + dol_print_error($db); } print ""; @@ -2029,8 +2028,8 @@ if ($action == 'create') //print ''.$langs->trans('Piece').''; print ''.$langs->trans('Date').''; if (!empty($conf->projet->enabled)) print ''.$langs->trans('Project').''; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print ''.$langs->trans('CarCategory').''; print ''.$langs->trans('Type').''; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print ''.$langs->trans('CarCategory').''; print ''.$langs->trans('Description').''; print ''.$langs->trans('VAT').''; print ''.$langs->trans('PriceUHT').''; @@ -2041,7 +2040,7 @@ if ($action == 'create') print ''.$langs->trans('AmountHT').''; print ''.$langs->trans('AmountTTC').''; } - // Picture + // Picture print ''; print ''; // Ajout des boutons de modification/suppression @@ -2080,6 +2079,13 @@ if ($action == 'create') } print ''; } + + // Type of fee + print ''; + $labeltype = ($langs->trans(($line->type_fees_code)) == $line->type_fees_code ? $line->type_fees_libelle : $langs->trans($line->type_fees_code)); + print $labeltype; + print ''; + // IK if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { @@ -2087,24 +2093,20 @@ if ($action == 'create') print dol_getIdFromCode($db, $line->fk_c_exp_tax_cat, 'c_exp_tax_cat', 'rowid', 'label'); print ''; } - // Type of fee - print ''; - $labeltype = ($langs->trans(($line->type_fees_code)) == $line->type_fees_code ? $line->type_fees_libelle : $langs->trans($line->type_fees_code)); - print $labeltype; - print ''; + // Comment print ''.dol_nl2br($line->comments).''; // VAT rate print ''.vatrate($line->vatrate, true).''; - // Unit price HT + // Unit price HT print ''; if (!empty($line->value_unit_ht)) { - print price($line->value_unit_ht); + print price($line->value_unit_ht); } else { - $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $line->vatrate)); - $pricenettoshow = price2num($line->value_unit / (1 + $tmpvat / 100), 'MU'); - print $pricenettoshow; + $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $line->vatrate)); + $pricenettoshow = price2num($line->value_unit / (1 + $tmpvat / 100), 'MU'); + print $pricenettoshow; } print ''; @@ -2122,71 +2124,71 @@ if ($action == 'create') print ''; if ($line->fk_ecm_files > 0) { - $modulepart = 'expensereport'; - $maxheightmini = 32; + $modulepart = 'expensereport'; + $maxheightmini = 32; - $result = $ecmfilesstatic->fetch($line->fk_ecm_files); - if ($result > 0) - { - $relativepath = preg_replace('/expensereport\//', '', $ecmfilesstatic->filepath); - $fileinfo = pathinfo($ecmfilesstatic->filepath.'/'.$ecmfilesstatic->filename); - if (image_format_supported($fileinfo['basename']) > 0) - { - $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original - if (!dol_is_file($conf->expensereport->dir_output.'/'.$relativepath.'/'.$minifile)) $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension - //print $file['path'].'/'.$minifile.'
    '; - $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.'/'.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); - if (empty($urlforhref)) { - $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])); - print ''; - } else { - print ''; - } - print ''; - print ''; - } else { - $modulepart = 'expensereport'; - $thumbshown = 0; - if (preg_match('/\.pdf$/i', $ecmfilesstatic->filename)) - { - $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename; - $fileimage = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename.'_preview.png'; - $relativepathimage = $relativepath.'/'.$ecmfilesstatic->filename.'_preview.png'; + $result = $ecmfilesstatic->fetch($line->fk_ecm_files); + if ($result > 0) + { + $relativepath = preg_replace('/expensereport\//', '', $ecmfilesstatic->filepath); + $fileinfo = pathinfo($ecmfilesstatic->filepath.'/'.$ecmfilesstatic->filename); + if (image_format_supported($fileinfo['basename']) > 0) + { + $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original + if (!dol_is_file($conf->expensereport->dir_output.'/'.$relativepath.'/'.$minifile)) $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension + //print $file['path'].'/'.$minifile.'
    '; + $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.'/'.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); + if (empty($urlforhref)) { + $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])); + print ''; + } else { + print ''; + } + print ''; + print ''; + } else { + $modulepart = 'expensereport'; + $thumbshown = 0; + if (preg_match('/\.pdf$/i', $ecmfilesstatic->filename)) + { + $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename; + $fileimage = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename.'_preview.png'; + $relativepathimage = $relativepath.'/'.$ecmfilesstatic->filename.'_preview.png'; - $pdfexists = file_exists($filepdf); - if ($pdfexists) - { - // Conversion du PDF en image png si fichier png non existant - if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) - { - if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here. - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png - if ($ret < 0) $error++; - } - } - } + $pdfexists = file_exists($filepdf); + if ($pdfexists) + { + // Conversion du PDF en image png si fichier png non existant + if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) + { + if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here. + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png + if ($ret < 0) $error++; + } + } + } - if ($pdfexists && !$error) - { - $heightforphotref = 70; - if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; - // If the preview file is found - if (file_exists($fileimage)) - { - $thumbshown = 1; - print ''; - } - } - } + if ($pdfexists && !$error) + { + $heightforphotref = 70; + if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; + // If the preview file is found + if (file_exists($fileimage)) + { + $thumbshown = 1; + print ''; + } + } + } - if (!$thumbshown) - { - print img_mime($ecmfilesstatic->filename); - } - } - } + if (!$thumbshown) + { + print img_mime($ecmfilesstatic->filename); + } + } + } } print ''; @@ -2210,30 +2212,30 @@ if ($action == 'create') if ($action == 'editline' && $line->rowid == GETPOST('rowid', 'int')) { - // Add line with link to add new file or attach line to an existing file - $colspan = 10; - if (!empty($conf->projet->enabled)) $colspan++; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++; + // Add line with link to add new file or attach line to an existing file + $colspan = 10; + if (!empty($conf->projet->enabled)) $colspan++; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++; - print ''; + print ''; - print ''; - print $numline; - print ''; + print ''; + print $numline; + print ''; - print ''; - print ''.$langs->trans("UploadANewFileNow"); - print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); - print ''; - if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) - { - print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); - print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); - print ''; - } + print ''; + print ''.$langs->trans("UploadANewFileNow"); + print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); + print ''; + if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) + { + print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); + print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); + print ''; + } - print ''."\n"; - print ''; + print ''."\n"; + print ''; - $filenamelinked = ''; - if ($line->fk_ecm_files > 0) - { - $result = $ecmfilesstatic->fetch($line->fk_ecm_files); - if ($result > 0) - { - $filenamelinked = $ecmfilesstatic->filename; - } - } + $filenamelinked = ''; + if ($line->fk_ecm_files > 0) + { + $result = $ecmfilesstatic->fetch($line->fk_ecm_files); + if ($result > 0) + { + $filenamelinked = $ecmfilesstatic->filename; + } + } - $tredited = 'tredited'; - include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php'; - include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php'; + $tredited = 'tredited'; + include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php'; + include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php'; print ''; @@ -2285,6 +2287,11 @@ if ($action == 'create') print ''; } + // Select type + print ''; + print select_type_fees_id($line->fk_c_type_fees, 'fk_c_type_fees'); + print ''; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { print ''; @@ -2293,11 +2300,6 @@ if ($action == 'create') print ''; } - // Select type - print ''; - select_type_fees_id($line->fk_c_type_fees, 'fk_c_type_fees'); - print ''; - // Add comments print ''; print ''; @@ -2344,44 +2346,44 @@ if ($action == 'create') } } - // Add a line + // Add a new line if (($object->fk_statut == ExpenseReport::STATUS_DRAFT || $object->fk_statut == ExpenseReport::STATUS_REFUSED) - && $action != 'editline' - && $user->rights->expensereport->creer) + && $action != 'editline' + && $user->rights->expensereport->creer) { - $colspan = 11; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++; - if (!empty($conf->projet->enabled)) $colspan++; - if ($action != 'editline') $colspan++; + $colspan = 11; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++; + if (!empty($conf->projet->enabled)) $colspan++; + if ($action != 'editline') $colspan++; - $nbFiles = $nbLinks = 0; - $arrayoffiles = array(); - if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) - { - 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/link.class.php'; - $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref); - $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$'); - $nbFiles = count($arrayoffiles); - $nbLinks = Link::count($db, $object->element, $object->id); - } + $nbFiles = $nbLinks = 0; + $arrayoffiles = array(); + if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) + { + 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/link.class.php'; + $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref); + $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$'); + $nbFiles = count($arrayoffiles); + $nbLinks = Link::count($db, $object->element, $object->id); + } - // Add line with link to add new file or attach to an existing file - print ''; - print ''; - print ''.$langs->trans("UploadANewFileNow"); - print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); - print ''; - if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) - { - print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); - print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); - print ''; - } + // Add line with link to add new file or attach to an existing file + print ''; + print ''; + print ''.$langs->trans("UploadANewFileNow"); + print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); + print ''; + if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) + { + print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); + print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); + print ''; + } - print ''."\n"; - print ''; + print ''."\n"; + print ''; - include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php'; - include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php'; + include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php'; + include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php'; print ''; print ''; print ''.$langs->trans('Date').''; - if (!empty($conf->projet->enabled)) print ''.$form->textwithpicto($langs->trans('Project'), $langs->trans("ClosedProjectsAreHidden")).''; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print ''.$langs->trans('CarCategory').''; + if (!empty($conf->projet->enabled)) { + print ''.$form->textwithpicto($langs->trans('Project'), $langs->trans("ClosedProjectsAreHidden")).''; + } print ''.$langs->trans('Type').''; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { + print ''.$langs->trans('CarCategory').''; + } print ''.$langs->trans('Description').''; print ''.$langs->trans('VAT').''; print ''.$langs->trans('PriceUHT').''; @@ -2440,19 +2446,19 @@ if ($action == 'create') print ''; } + // Select type + print ''; + print select_type_fees_id($fk_c_type_fees, 'fk_c_type_fees', 1); + print ''; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { print ''; $params = array('fk_expense' => $object->id); - print $form->selectExpenseCategories('', 'fk_c_exp_tax_cat', 1, array(), 'fk_c_type_fees', $userauthor->default_c_exp_tax_cat, $params); + print $form->selectExpenseCategories('', 'fk_c_exp_tax_cat', 1, array(), 'fk_c_type_fees', $userauthor->default_c_exp_tax_cat, $params, 0); print ''; } - // Select type - print ''; - select_type_fees_id($fk_c_type_fees, 'fk_c_type_fees', 1); - print ''; - // Add comments print ''; print ''; @@ -2634,7 +2640,7 @@ if ($action != 'create' && $action != 'edit') if ($user->rights->expensereport->approve && $object->fk_statut == ExpenseReport::STATUS_APPROVED) { - print ''; + print ''; } // If bank module is used @@ -2661,15 +2667,15 @@ if ($action != 'create' && $action != 'edit') if ($user->rights->expensereport->creer && ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) && $object->fk_statut == ExpenseReport::STATUS_APPROVED) { - // Cancel + // Cancel print ''; } - // TODO Replace this. It should be SetUnpaid and should go back to status unpaid not canceled. + // TODO Replace this. It should be SetUnpaid and should go back to status unpaid not canceled. if (($user->rights->expensereport->approve || $user->rights->expensereport->to_paid) && $object->fk_statut == ExpenseReport::STATUS_CLOSED) { - // Cancel - print ''; + // Cancel + print ''; } if ($user->rights->expensereport->to_paid && $object->paid && $object->fk_statut == ExpenseReport::STATUS_CLOSED) @@ -2680,18 +2686,18 @@ if ($action != 'create' && $action != 'edit') // Clone if ($user->rights->expensereport->creer) { - print ''; + print ''; } /* If draft, validated, cancel, and user can create, he can always delete its card before it is approved */ if ($user->rights->expensereport->creer && $user->id == $object->fk_user_author && $object->fk_statut < ExpenseReport::STATUS_APPROVED) { - // Delete + // Delete print ''; } elseif ($user->rights->expensereport->supprimer && $object->fk_statut != ExpenseReport::STATUS_CLOSED) { - // Delete - print ''; + // Delete + print ''; } $parameters = array(); diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index e2ea2b377a4..8770a0ab1a2 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -34,80 +34,80 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.ph */ class ExpenseReport extends CommonObject { - /** + /** * @var string ID to identify managed object */ public $element = 'expensereport'; - /** + /** * @var string Name of table without prefix where object is stored */ public $table_element = 'expensereport'; - public $table_element_line = 'expensereport_det'; - public $fk_element = 'fk_expensereport'; + public $table_element_line = 'expensereport_det'; + public $fk_element = 'fk_expensereport'; - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'trip'; + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'trip'; - public $lines = array(); + public $lines = array(); - public $date_debut; + public $date_debut; - public $date_fin; + public $date_fin; - /** - * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied - * - * @var int Status - */ - public $status; - public $fk_statut; + /** + * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied + * + * @var int Status + */ + public $status; + public $fk_statut; - public $fk_c_paiement; - public $paid; + public $fk_c_paiement; + public $paid; - public $user_author_infos; - public $user_validator_infos; + public $user_author_infos; + public $user_validator_infos; - // ACTIONS + // ACTIONS - // Create - public $date_create; - public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + // Create + public $date_create; + public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - // Update + // Update public $date_modif; - public $fk_user_modif; + public $fk_user_modif; - // Refus - public $date_refuse; - public $detail_refuse; - public $fk_user_refuse; + // Refus + public $date_refuse; + public $detail_refuse; + public $fk_user_refuse; - // Annulation - public $date_cancel; - public $detail_cancel; - public $fk_user_cancel; + // Annulation + public $date_cancel; + public $detail_cancel; + public $fk_user_cancel; - public $fk_user_validator; // User that is defined to approve + public $fk_user_validator; // User that is defined to approve - // Validation - public $date_valid; // User making validation - public $fk_user_valid; - public $user_valid_infos; + // Validation + public $date_valid; // User making validation + public $fk_user_valid; + public $user_valid_infos; - // Approve - public $date_approve; - public $fk_user_approve; // User that has approved + // Approve + public $date_approve; + public $fk_user_approve; // User that has approved - // Paiement - public $user_paid_infos; + // Paiement + public $user_paid_infos; - /** + /** * Draft status */ const STATUS_DRAFT = 0; @@ -185,156 +185,156 @@ class ExpenseReport extends CommonObject ); /** - * Constructor - * - * @param DoliDB $db Handler acces base de donnees - */ - public function __construct($db) - { - $this->db = $db; - $this->total_ht = 0; - $this->total_ttc = 0; - $this->total_tva = 0; - $this->modepaymentid = 0; + * Constructor + * + * @param DoliDB $db Handler acces base de donnees + */ + public function __construct($db) + { + $this->db = $db; + $this->total_ht = 0; + $this->total_ttc = 0; + $this->total_tva = 0; + $this->modepaymentid = 0; - // List of language codes for status - $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); - $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); - $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5'); - } + // List of language codes for status + $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); + $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); + $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5'); + } - /** - * Create object in database - * - * @param User $user User that create - * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Create object in database + * + * @param User $user User that create + * @param int $notrigger Disable triggers + * @return int <0 if KO, >0 if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; - $now = dol_now(); + $now = dol_now(); - $error = 0; + $error = 0; - // Check parameters - if (empty($this->date_debut) || empty($this->date_fin)) - { - $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date')); - return -1; - } + // Check parameters + if (empty($this->date_debut) || empty($this->date_fin)) + { + $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date')); + return -1; + } - $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - if (empty($fuserid)) $fuserid = $user->id; + $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + if (empty($fuserid)) $fuserid = $user->id; - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; - $sql .= "ref"; - $sql .= ",total_ht"; - $sql .= ",total_ttc"; - $sql .= ",total_tva"; - $sql .= ",date_debut"; - $sql .= ",date_fin"; - $sql .= ",date_create"; - $sql .= ",fk_user_author"; - $sql .= ",fk_user_validator"; - $sql .= ",fk_user_approve"; - $sql .= ",fk_user_modif"; - $sql .= ",fk_statut"; - $sql .= ",fk_c_paiement"; - $sql .= ",paid"; - $sql .= ",note_public"; - $sql .= ",note_private"; - $sql .= ",entity"; - $sql .= ") VALUES("; - $sql .= "'(PROV)'"; - $sql .= ", ".$this->total_ht; - $sql .= ", ".$this->total_ttc; - $sql .= ", ".$this->total_tva; - $sql .= ", '".$this->db->idate($this->date_debut)."'"; - $sql .= ", '".$this->db->idate($this->date_fin)."'"; - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", ".$fuserid; - $sql .= ", ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); - $sql .= ", ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); - $sql .= ", ".($this->fk_user_modif > 0 ? $this->fk_user_modif : "null"); - $sql .= ", ".($this->fk_statut > 1 ? $this->fk_statut : 0); - $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null"); - $sql .= ", 0"; - $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); - $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); - $sql .= ", ".$conf->entity; - $sql .= ")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; + $sql .= "ref"; + $sql .= ",total_ht"; + $sql .= ",total_ttc"; + $sql .= ",total_tva"; + $sql .= ",date_debut"; + $sql .= ",date_fin"; + $sql .= ",date_create"; + $sql .= ",fk_user_author"; + $sql .= ",fk_user_validator"; + $sql .= ",fk_user_approve"; + $sql .= ",fk_user_modif"; + $sql .= ",fk_statut"; + $sql .= ",fk_c_paiement"; + $sql .= ",paid"; + $sql .= ",note_public"; + $sql .= ",note_private"; + $sql .= ",entity"; + $sql .= ") VALUES("; + $sql .= "'(PROV)'"; + $sql .= ", ".$this->total_ht; + $sql .= ", ".$this->total_ttc; + $sql .= ", ".$this->total_tva; + $sql .= ", '".$this->db->idate($this->date_debut)."'"; + $sql .= ", '".$this->db->idate($this->date_fin)."'"; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", ".$fuserid; + $sql .= ", ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); + $sql .= ", ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); + $sql .= ", ".($this->fk_user_modif > 0 ? $this->fk_user_modif : "null"); + $sql .= ", ".($this->fk_statut > 1 ? $this->fk_statut : 0); + $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null"); + $sql .= ", 0"; + $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); + $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); + $sql .= ", ".$conf->entity; + $sql .= ")"; - $result = $this->db->query($sql); - if ($result) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - $this->ref = '(PROV'.$this->id.')'; + $result = $this->db->query($sql); + if ($result) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + $this->ref = '(PROV'.$this->id.')'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; - $resql = $this->db->query($sql); - if (!$resql) - { - $this->error = $this->db->lasterror(); - $error++; - } + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + $resql = $this->db->query($sql); + if (!$resql) + { + $this->error = $this->db->lasterror(); + $error++; + } - if (!$error) - { - if (is_array($this->lines) && count($this->lines) > 0) - { - foreach ($this->lines as $line) - { - // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array - //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. - if (!is_object($line)) { - $line = (object) $line; - $newndfline = new ExpenseReportLine($this->db); - $newndfline->fk_expensereport = $line->fk_expensereport; - $newndfline->fk_c_type_fees = $line->fk_c_type_fees; - $newndfline->fk_project = $line->fk_project; - $newndfline->vatrate = $line->vatrate; - $newndfline->vat_src_code = $line->vat_src_code; - $newndfline->comments = $line->comments; - $newndfline->qty = $line->qty; - $newndfline->value_unit = $line->value_unit; - $newndfline->total_ht = $line->total_ht; - $newndfline->total_ttc = $line->total_ttc; - $newndfline->total_tva = $line->total_tva; - $newndfline->date = $line->date; - $newndfline->rule_warning_message = $line->rule_warning_message; - $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat; - $newndfline->fk_ecm_files = $line->fk_ecm_files; - } else { - $newndfline = $line; - } - //$newndfline=new ExpenseReportLine($this->db); - $newndfline->fk_expensereport = $this->id; - $result = $newndfline->insert(); - if ($result < 0) - { - $this->error = $newndfline->error; - $error++; - break; - } - } - } - } + if (!$error) + { + if (is_array($this->lines) && count($this->lines) > 0) + { + foreach ($this->lines as $line) + { + // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array + //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. + if (!is_object($line)) { + $line = (object) $line; + $newndfline = new ExpenseReportLine($this->db); + $newndfline->fk_expensereport = $line->fk_expensereport; + $newndfline->fk_c_type_fees = $line->fk_c_type_fees; + $newndfline->fk_project = $line->fk_project; + $newndfline->vatrate = $line->vatrate; + $newndfline->vat_src_code = $line->vat_src_code; + $newndfline->comments = $line->comments; + $newndfline->qty = $line->qty; + $newndfline->value_unit = $line->value_unit; + $newndfline->total_ht = $line->total_ht; + $newndfline->total_ttc = $line->total_ttc; + $newndfline->total_tva = $line->total_tva; + $newndfline->date = $line->date; + $newndfline->rule_warning_message = $line->rule_warning_message; + $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat; + $newndfline->fk_ecm_files = $line->fk_ecm_files; + } else { + $newndfline = $line; + } + //$newndfline=new ExpenseReportLine($this->db); + $newndfline->fk_expensereport = $this->id; + $result = $newndfline->insert(); + if ($result < 0) + { + $this->error = $newndfline->error; + $error++; + break; + } + } + } + } - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) $error++; - } + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) $error++; + } - if (!$error) - { - $result = $this->update_price(); - if ($result > 0) - { + if (!$error) + { + $result = $this->update_price(); + if ($result > 0) + { if (!$notrigger) { // Call trigger @@ -354,131 +354,131 @@ class ExpenseReport extends CommonObject $this->db->rollback(); return -4; } - } else { - $this->db->rollback(); - return -3; - } - } else { - dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } else { - $this->error = $this->db->lasterror()." sql=".$sql; - $this->db->rollback(); - return -1; - } - } + } else { + $this->db->rollback(); + return -3; + } + } else { + dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } else { + $this->error = $this->db->lasterror()." sql=".$sql; + $this->db->rollback(); + return -1; + } + } - /** - * 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 + * * @param User $user User making the clone - * @param int $fk_user_author Id of new user - * @return int New id of clone - */ - public function createFromClone(User $user, $fk_user_author) - { - global $hookmanager; + * @param int $fk_user_author Id of new user + * @return int New id of clone + */ + public function createFromClone(User $user, $fk_user_author) + { + global $hookmanager; - $error = 0; + $error = 0; - if (empty($fk_user_author)) $fk_user_author = $user->id; + if (empty($fk_user_author)) $fk_user_author = $user->id; - $this->db->begin(); + $this->db->begin(); - // get extrafields so they will be clone - //foreach($this->lines as $line) - //$line->fetch_optionals(); + // get extrafields so they will be clone + //foreach($this->lines as $line) + //$line->fetch_optionals(); - // Load source object - $objFrom = clone $this; + // Load source object + $objFrom = clone $this; - $this->id = 0; - $this->ref = ''; - $this->status = 0; - $this->fk_statut = 0; + $this->id = 0; + $this->ref = ''; + $this->status = 0; + $this->fk_statut = 0; - // Clear fields - $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - $this->fk_user_valid = ''; - $this->date_create = ''; - $this->date_creation = ''; - $this->date_validation = ''; + // Clear fields + $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + $this->fk_user_valid = ''; + $this->date_create = ''; + $this->date_creation = ''; + $this->date_validation = ''; - // Create clone - $this->context['createfromclone'] = 'createfromclone'; - $result = $this->create($user); - if ($result < 0) $error++; + // Create clone + $this->context['createfromclone'] = 'createfromclone'; + $result = $this->create($user); + if ($result < 0) $error++; - if (!$error) - { - // Hook of thirdparty module - if (is_object($hookmanager)) - { - $parameters = array('objFrom'=>$objFrom); - $action = ''; - $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $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'=>$objFrom); + $action = ''; + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) $error++; + } + } - unset($this->context['createfromclone']); + unset($this->context['createfromclone']); - // End - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } + // End + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * update - * - * @param User $user User making change + /** + * update + * + * @param User $user User making change * @param int $notrigger Disable triggers - * @param User $userofexpensereport New user we want to have the expense report on. - * @return int <0 if KO, >0 if OK - */ - public function update($user, $notrigger = 0, $userofexpensereport = null) - { - global $langs; + * @param User $userofexpensereport New user we want to have the expense report on. + * @return int <0 if KO, >0 if OK + */ + public function update($user, $notrigger = 0, $userofexpensereport = null) + { + global $langs; $error = 0; $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$this->total_ht; - $sql .= " , total_ttc = ".$this->total_ttc; - $sql .= " , total_tva = ".$this->total_tva; - $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'"; - $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'"; - if ($userofexpensereport && is_object($userofexpensereport)) - { - $sql .= " , fk_user_author = ".($userofexpensereport->id > 0 ? "'".$userofexpensereport->id."'" : "null"); // Note fk_user_author is not the 'author' but the guy the expense report is for. - } - $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); - $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null"); - $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); - $sql .= " , fk_user_modif = ".$user->id; - $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0'); - $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null"); - $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''"); - $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''"); - $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''"); - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$this->total_ht; + $sql .= " , total_ttc = ".$this->total_ttc; + $sql .= " , total_tva = ".$this->total_tva; + $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'"; + $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'"; + if ($userofexpensereport && is_object($userofexpensereport)) + { + $sql .= " , fk_user_author = ".($userofexpensereport->id > 0 ? "'".$userofexpensereport->id."'" : "null"); // Note fk_user_author is not the 'author' but the guy the expense report is for. + } + $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); + $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null"); + $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); + $sql .= " , fk_user_modif = ".$user->id; + $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0'); + $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null"); + $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''"); + $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''"); + $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''"); + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - if (!$notrigger) + dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_UPDATE', $user); @@ -498,132 +498,132 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->error(); - return -1; - } - } + $this->error = $this->db->error(); + return -1; + } + } - /** - * Load an object from database - * - * @param int $id Id {@min 1} - * @param string $ref Ref {@name ref} - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $ref = '') - { - global $conf; + /** + * Load an object from database + * + * @param int $id Id {@min 1} + * @param string $ref Ref {@name ref} + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $ref = '') + { + global $conf; - $sql = "SELECT d.rowid, d.ref, d.note_public, d.note_private,"; // DEFAULT - $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS - $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS - $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; // TOTAUX (int) - $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime) - $sql .= " d.fk_user_author, d.fk_user_modif, d.fk_user_validator,"; - $sql .= " d.fk_user_valid, d.fk_user_approve,"; - $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid"; - $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d"; - if ($ref) $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'"; - else $sql .= " WHERE d.rowid = ".$id; - //$sql.= $restrict; + $sql = "SELECT d.rowid, d.ref, d.note_public, d.note_private,"; // DEFAULT + $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS + $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS + $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; // TOTAUX (int) + $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime) + $sql .= " d.fk_user_author, d.fk_user_modif, d.fk_user_validator,"; + $sql .= " d.fk_user_valid, d.fk_user_approve,"; + $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d"; + if ($ref) $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'"; + else $sql .= " WHERE d.rowid = ".$id; + //$sql.= $restrict; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $this->id = $obj->rowid; - $this->ref = $obj->ref; - $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->total_tva; - $this->total_ttc = $obj->total_ttc; - $this->note_public = $obj->note_public; - $this->note_private = $obj->note_private; - $this->detail_refuse = $obj->detail_refuse; - $this->detail_cancel = $obj->detail_cancel; + dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $this->id = $obj->rowid; + $this->ref = $obj->ref; + $this->total_ht = $obj->total_ht; + $this->total_tva = $obj->total_tva; + $this->total_ttc = $obj->total_ttc; + $this->note_public = $obj->note_public; + $this->note_private = $obj->note_private; + $this->detail_refuse = $obj->detail_refuse; + $this->detail_cancel = $obj->detail_cancel; - $this->date_debut = $this->db->jdate($obj->date_debut); - $this->date_fin = $this->db->jdate($obj->date_fin); - $this->date_valid = $this->db->jdate($obj->date_valid); - $this->date_approve = $this->db->jdate($obj->date_approve); - $this->date_create = $this->db->jdate($obj->date_create); - $this->date_modif = $this->db->jdate($obj->date_modif); - $this->date_refuse = $this->db->jdate($obj->date_refuse); - $this->date_cancel = $this->db->jdate($obj->date_cancel); + $this->date_debut = $this->db->jdate($obj->date_debut); + $this->date_fin = $this->db->jdate($obj->date_fin); + $this->date_valid = $this->db->jdate($obj->date_valid); + $this->date_approve = $this->db->jdate($obj->date_approve); + $this->date_create = $this->db->jdate($obj->date_create); + $this->date_modif = $this->db->jdate($obj->date_modif); + $this->date_refuse = $this->db->jdate($obj->date_refuse); + $this->date_cancel = $this->db->jdate($obj->date_cancel); - $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - $this->fk_user_modif = $obj->fk_user_modif; - $this->fk_user_validator = $obj->fk_user_validator; - $this->fk_user_valid = $obj->fk_user_valid; - $this->fk_user_refuse = $obj->fk_user_refuse; - $this->fk_user_cancel = $obj->fk_user_cancel; - $this->fk_user_approve = $obj->fk_user_approve; + $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + $this->fk_user_modif = $obj->fk_user_modif; + $this->fk_user_validator = $obj->fk_user_validator; + $this->fk_user_valid = $obj->fk_user_valid; + $this->fk_user_refuse = $obj->fk_user_refuse; + $this->fk_user_cancel = $obj->fk_user_cancel; + $this->fk_user_approve = $obj->fk_user_approve; - $user_author = new User($this->db); - if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author); + $user_author = new User($this->db); + if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author); - $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname); + $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname); - $user_approver = new User($this->db); - if ($this->fk_user_approve > 0) $user_approver->fetch($this->fk_user_approve); - elseif ($this->fk_user_validator > 0) $user_approver->fetch($this->fk_user_validator); // For backward compatibility - $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname); + $user_approver = new User($this->db); + if ($this->fk_user_approve > 0) $user_approver->fetch($this->fk_user_approve); + elseif ($this->fk_user_validator > 0) $user_approver->fetch($this->fk_user_validator); // For backward compatibility + $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname); - $this->fk_statut = $obj->status; // deprecated - $this->status = $obj->status; - $this->fk_c_paiement = $obj->fk_c_paiement; - $this->paid = $obj->paid; + $this->fk_statut = $obj->status; // deprecated + $this->status = $obj->status; + $this->fk_c_paiement = $obj->fk_c_paiement; + $this->paid = $obj->paid; - if ($this->fk_statut == self::STATUS_APPROVED || $this->fk_statut == self::STATUS_CLOSED) - { - $user_valid = new User($this->db); - if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid); - $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname); - } + if ($this->fk_statut == self::STATUS_APPROVED || $this->fk_statut == self::STATUS_CLOSED) + { + $user_valid = new User($this->db); + if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid); + $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname); + } - $this->lines = array(); + $this->lines = array(); - $result = $this->fetch_lines(); + $result = $this->fetch_lines(); - return $result; - } else { - return 0; - } - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } + return $result; + } else { + return 0; + } + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Classify the expense report as paid - * - * @param int $id Id of expense report - * @param user $fuser User making change + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Classify the expense report as paid + * + * @param int $id Id of expense report + * @param user $fuser User making change * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function set_paid($id, $fuser, $notrigger = 0) - { - // phpcs:enable + * @return int <0 if KO, >0 if OK + */ + public function set_paid($id, $fuser, $notrigger = 0) + { + // phpcs:enable $error = 0; $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport"; - $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1"; - $sql .= " WHERE rowid = ".$id." AND fk_statut = ".self::STATUS_APPROVED; + $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport"; + $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1"; + $sql .= " WHERE rowid = ".$id." AND fk_statut = ".self::STATUS_APPROVED; - dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { + dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->affected_rows($resql)) + { if (!$notrigger) { // Call trigger @@ -644,263 +644,263 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->commit(); - return 0; - } - } else { + return 0; + } + } else { $this->db->rollback(); - dol_print_error($this->db); - return -1; - } - } + dol_print_error($this->db); + return -1; + } + } - /** - * Returns the label 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 Label - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->status, $mode); - } + /** + * Returns the label 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 Label + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Returns the label of a statut - * - * @param int $status 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 - */ - public function LibStatut($status, $mode = 0) - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Returns the label of a statut + * + * @param int $status 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 + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + global $langs; - $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]); - $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]); + $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]); + $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]); - $statusType = $this->statuts_logo[$status]; + $statusType = $this->statuts_logo[$status]; - return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); - } + return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); + } - /** - * Load information on object - * - * @param int $id Id of object - * @return void - */ - public function info($id) - { - global $conf; + /** + * Load information on object + * + * @param int $id Id of object + * @return void + */ + public function info($id) + { + global $conf; - $sql = "SELECT f.rowid,"; - $sql .= " f.date_create as datec,"; - $sql .= " f.tms as date_modification,"; - $sql .= " f.date_valid as datev,"; - $sql .= " f.date_approve as datea,"; - //$sql.= " f.fk_user_author as fk_user_creation,"; // This is not user of creation but user the expense is for. - $sql .= " f.fk_user_modif as fk_user_modification,"; - $sql .= " f.fk_user_valid,"; - $sql .= " f.fk_user_approve"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f"; - $sql .= " WHERE f.rowid = ".$id; - $sql .= " AND f.entity = ".$conf->entity; + $sql = "SELECT f.rowid,"; + $sql .= " f.date_create as datec,"; + $sql .= " f.tms as date_modification,"; + $sql .= " f.date_valid as datev,"; + $sql .= " f.date_approve as datea,"; + //$sql.= " f.fk_user_author as fk_user_creation,"; // This is not user of creation but user the expense is for. + $sql .= " f.fk_user_modif as fk_user_modification,"; + $sql .= " f.fk_user_valid,"; + $sql .= " f.fk_user_approve"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f"; + $sql .= " WHERE f.rowid = ".$id; + $sql .= " AND f.entity = ".$conf->entity; - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + $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->date_creation = $this->db->jdate($obj->datec); - $this->date_modification = $this->db->jdate($obj->date_modification); - $this->date_validation = $this->db->jdate($obj->datev); - $this->date_approbation = $this->db->jdate($obj->datea); + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->date_modification); + $this->date_validation = $this->db->jdate($obj->datev); + $this->date_approbation = $this->db->jdate($obj->datea); - $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_creation) - { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_creation); - $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_modification) - { - $muser = new User($this->db); - $muser->fetch($obj->fk_user_modification); - $this->user_modification = $muser; - } - if ($obj->fk_user_approve) - { - $auser = new User($this->db); - $auser->fetch($obj->fk_user_approve); - $this->user_approve = $auser; - } - } - $this->db->free($resql); - } else { - dol_print_error($this->db); - } - } + if ($obj->fk_user_creation) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_creation); + $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_modification) + { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_modification); + $this->user_modification = $muser; + } + if ($obj->fk_user_approve) + { + $auser = new User($this->db); + $auser->fetch($obj->fk_user_approve); + $this->user_approve = $auser; + } + } + $this->db->free($resql); + } else { + dol_print_error($this->db); + } + } - /** - * 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 - */ - public function initAsSpecimen() - { - global $user, $langs, $conf; + /** + * 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 + */ + public function initAsSpecimen() + { + global $user, $langs, $conf; - $now = dol_now(); + $now = dol_now(); - // Initialise parametres - $this->id = 0; - $this->ref = 'SPECIMEN'; - $this->specimen = 1; - $this->date_create = $now; - $this->date_debut = $now; - $this->date_fin = $now; - $this->date_valid = $now; - $this->date_approve = $now; + // Initialise parametres + $this->id = 0; + $this->ref = 'SPECIMEN'; + $this->specimen = 1; + $this->date_create = $now; + $this->date_debut = $now; + $this->date_fin = $now; + $this->date_valid = $now; + $this->date_approve = $now; - $type_fees_id = 2; // TF_TRIP + $type_fees_id = 2; // TF_TRIP - $this->status = 5; - $this->fk_statut = 5; + $this->status = 5; + $this->fk_statut = 5; - $this->fk_user_author = $user->id; - $this->fk_user_validator = $user->id; - $this->fk_user_valid = $user->id; - $this->fk_user_approve = $user->id; + $this->fk_user_author = $user->id; + $this->fk_user_validator = $user->id; + $this->fk_user_valid = $user->id; + $this->fk_user_approve = $user->id; - $this->note_private = 'Private note'; - $this->note_public = 'SPECIMEN'; - $nbp = 5; - $xnbp = 0; - while ($xnbp < $nbp) { - $line = new ExpenseReportLine($this->db); - $line->comments = $langs->trans("Comment")." ".$xnbp; - $line->date = ($now - 3600 * (1 + $xnbp)); - $line->total_ht = 100; - $line->total_tva = 20; - $line->total_ttc = 120; - $line->qty = 1; - $line->vatrate = 20; - $line->value_unit = 120; - $line->fk_expensereport = 0; - $line->type_fees_code = 'TRA'; - $line->fk_c_type_fees = $type_fees_id; + $this->note_private = 'Private note'; + $this->note_public = 'SPECIMEN'; + $nbp = 5; + $xnbp = 0; + while ($xnbp < $nbp) { + $line = new ExpenseReportLine($this->db); + $line->comments = $langs->trans("Comment")." ".$xnbp; + $line->date = ($now - 3600 * (1 + $xnbp)); + $line->total_ht = 100; + $line->total_tva = 20; + $line->total_ttc = 120; + $line->qty = 1; + $line->vatrate = 20; + $line->value_unit = 120; + $line->fk_expensereport = 0; + $line->type_fees_code = 'TRA'; + $line->fk_c_type_fees = $type_fees_id; - $line->projet_ref = 'ABC'; + $line->projet_ref = 'ABC'; - $this->lines[$xnbp] = $line; - $xnbp++; + $this->lines[$xnbp] = $line; + $xnbp++; - $this->total_ht += $line->total_ht; - $this->total_tva += $line->total_tva; - $this->total_ttc += $line->total_ttc; - } - } + $this->total_ht += $line->total_ht; + $this->total_tva += $line->total_tva; + $this->total_ttc += $line->total_ttc; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * fetch_line_by_project - * - * @param int $projectid Project id - * @param User $user User - * @return int <0 if KO, >0 if OK - */ - public function fetch_line_by_project($projectid, $user = '') - { - // phpcs:enable - global $conf, $db, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * fetch_line_by_project + * + * @param int $projectid Project id + * @param User $user User + * @return int <0 if KO, >0 if OK + */ + public function fetch_line_by_project($projectid, $user = '') + { + // phpcs:enable + global $conf, $db, $langs; - $langs->load('trips'); + $langs->load('trips'); - if ($user->rights->expensereport->lire) { - $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de"; - $sql .= " WHERE de.fk_projet = ".$projectid; + if ($user->rights->expensereport->lire) { + $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de"; + $sql .= " WHERE de.fk_projet = ".$projectid; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $i = 0; - $total_HT = 0; - $total_TTC = 0; + dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + $total_HT = 0; + $total_TTC = 0; - while ($i < $num) - { - $objp = $db->fetch_object($result); + while ($i < $num) + { + $objp = $db->fetch_object($result); - $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut"; - $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d"; - $sql2 .= " WHERE d.rowid = '".$objp->fk_expensereport."'"; + $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut"; + $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d"; + $sql2 .= " WHERE d.rowid = '".$objp->fk_expensereport."'"; - $result2 = $db->query($sql2); - $obj = $db->fetch_object($result2); + $result2 = $db->query($sql2); + $obj = $db->fetch_object($result2); - $objp->fk_user_author = $obj->fk_user_author; - $objp->ref = $obj->ref; - $objp->fk_c_expensereport_status = $obj->fk_statut; - $objp->rowid = $obj->rowid; + $objp->fk_user_author = $obj->fk_user_author; + $objp->ref = $obj->ref; + $objp->fk_c_expensereport_status = $obj->fk_statut; + $objp->rowid = $obj->rowid; - $total_HT = $total_HT + $objp->total_ht; - $total_TTC = $total_TTC + $objp->total_ttc; - $author = new User($db); - $author->fetch($objp->fk_user_author); + $total_HT = $total_HT + $objp->total_ht; + $total_TTC = $total_TTC + $objp->total_ttc; + $author = new User($db); + $author->fetch($objp->fk_user_author); - print ''; - print ''.$objp->ref_num.''; - print ''.dol_print_date($objp->date, 'day').''; - print ''.$author->getNomUrl(1).''; - print ''.$objp->comments.''; - print ''.price($objp->total_ht).''; - print ''.price($objp->total_ttc).''; - print ''; + print ''; + print ''.$objp->ref_num.''; + print ''.dol_print_date($objp->date, 'day').''; + print ''.$author->getNomUrl(1).''; + print ''.$objp->comments.''; + print ''.price($objp->total_ht).''; + print ''.price($objp->total_ttc).''; + print ''; - switch ($objp->fk_c_expensereport_status) { - case 4: - print img_picto($langs->trans('StatusOrderCanceled'), 'statut5'); - break; - case 1: - print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0'); - break; - case 2: - print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3'); - break; - case 5: - print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3'); - break; - case 6: - print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4'); - break; - } - /* + switch ($objp->fk_c_expensereport_status) { + case 4: + print img_picto($langs->trans('StatusOrderCanceled'), 'statut5'); + break; + case 1: + print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0'); + break; + case 2: + print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3'); + break; + case 5: + print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3'); + break; + case 6: + print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4'); + break; + } + /* if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5'); if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1'); @@ -908,237 +908,237 @@ class ExpenseReport extends CommonObject if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6'); */ - print ''; - print ''; + print ''; + print ''; - $i++; - } + $i++; + } - print ''.$langs->trans("Number").': '.$i.''; - print ''.$langs->trans("TotalHT").' : '.price($total_HT).''; - print ''.$langs->trans("TotalTTC").' : '.price($total_TTC).''; - print ' '; - print ''; - } else { - $this->error = $db->lasterror(); - return -1; - } - } - } + print ''.$langs->trans("Number").': '.$i.''; + print ''.$langs->trans("TotalHT").' : '.price($total_HT).''; + print ''.$langs->trans("TotalTTC").' : '.price($total_TTC).''; + print ' '; + print ''; + } else { + $this->error = $db->lasterror(); + return -1; + } + } + } - /** - * recalculer - * TODO Replace this with call to update_price if not already done - * - * @param int $id Id of expense report - * @return int <0 if KO, >0 if OK - */ - public function recalculer($id) - { - $sql = 'SELECT tt.total_ht, tt.total_ttc, tt.total_tva'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as tt'; - $sql .= ' WHERE tt.'.$this->fk_element.' = '.$id; + /** + * recalculer + * TODO Replace this with call to update_price if not already done + * + * @param int $id Id of expense report + * @return int <0 if KO, >0 if OK + */ + public function recalculer($id) + { + $sql = 'SELECT tt.total_ht, tt.total_ttc, tt.total_tva'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as tt'; + $sql .= ' WHERE tt.'.$this->fk_element.' = '.$id; - $total_ht = 0; $total_tva = 0; $total_ttc = 0; + $total_ht = 0; $total_tva = 0; $total_ttc = 0; - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num): - $objp = $this->db->fetch_object($result); - $total_ht += $objp->total_ht; - $total_tva += $objp->total_tva; - $i++; - endwhile; + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num): + $objp = $this->db->fetch_object($result); + $total_ht += $objp->total_ht; + $total_tva += $objp->total_tva; + $i++; + endwhile; - $total_ttc = $total_ht + $total_tva; - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$total_ht; - $sql .= " , total_ttc = ".$total_ttc; - $sql .= " , total_tva = ".$total_tva; - $sql .= " WHERE rowid = ".$id; - $result = $this->db->query($sql); - if ($result): - $this->db->free($result); - return 1; - else : - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); - return -3; - endif; - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); - return -3; - } - } + $total_ttc = $total_ht + $total_tva; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$total_ht; + $sql .= " , total_ttc = ".$total_ttc; + $sql .= " , total_tva = ".$total_tva; + $sql .= " WHERE rowid = ".$id; + $result = $this->db->query($sql); + if ($result): + $this->db->free($result); + return 1; + else : + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); + return -3; + endif; + } else { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); + return -3; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * fetch_lines - * - * @return int <0 if OK, >0 if KO - */ - public function fetch_lines() - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * fetch_lines + * + * @return int <0 if OK, >0 if KO + */ + public function fetch_lines() + { + // phpcs:enable + global $conf; - $this->lines = array(); + $this->lines = array(); - $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,'; - $sql .= ' de.'.$this->fk_element.', de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project, de.tva_tx, de.fk_ecm_files,'; - $sql .= ' de.total_ht, de.total_tva, de.total_ttc,'; - $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees,'; - $sql .= ' p.ref as ref_projet, p.title as title_projet'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid'; - $sql .= ' WHERE de.'.$this->fk_element.' = '.$this->id; - if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID)) - { - $sql .= ' ORDER BY de.rang ASC, de.rowid ASC'; - } else { - $sql .= ' ORDER BY de.rang ASC, de.date ASC'; - } + $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,'; + $sql .= ' de.'.$this->fk_element.', de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project, de.tva_tx, de.fk_ecm_files,'; + $sql .= ' de.total_ht, de.total_tva, de.total_ttc,'; + $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees,'; + $sql .= ' p.ref as ref_projet, p.title as title_projet'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid'; + $sql .= ' WHERE de.'.$this->fk_element.' = '.$this->id; + if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID)) + { + $sql .= ' ORDER BY de.rang ASC, de.rowid ASC'; + } else { + $sql .= ' ORDER BY de.rang ASC, de.date ASC'; + } - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $objp = $this->db->fetch_object($resql); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $objp = $this->db->fetch_object($resql); - $deplig = new ExpenseReportLine($this->db); + $deplig = new ExpenseReportLine($this->db); - $deplig->rowid = $objp->rowid; - $deplig->id = $objp->rowid; - $deplig->comments = $objp->comments; - $deplig->qty = $objp->qty; - $deplig->value_unit = $objp->value_unit; - $deplig->date = $objp->date; - $deplig->dates = $this->db->jdate($objp->date); + $deplig->rowid = $objp->rowid; + $deplig->id = $objp->rowid; + $deplig->comments = $objp->comments; + $deplig->qty = $objp->qty; + $deplig->value_unit = $objp->value_unit; + $deplig->date = $objp->date; + $deplig->dates = $this->db->jdate($objp->date); - $deplig->fk_expensereport = $objp->fk_expensereport; - $deplig->fk_c_type_fees = $objp->fk_c_type_fees; - $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; - $deplig->fk_projet = $objp->fk_project; // deprecated - $deplig->fk_project = $objp->fk_project; - $deplig->fk_ecm_files = $objp->fk_ecm_files; + $deplig->fk_expensereport = $objp->fk_expensereport; + $deplig->fk_c_type_fees = $objp->fk_c_type_fees; + $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; + $deplig->fk_projet = $objp->fk_project; // deprecated + $deplig->fk_project = $objp->fk_project; + $deplig->fk_ecm_files = $objp->fk_ecm_files; - $deplig->total_ht = $objp->total_ht; - $deplig->total_tva = $objp->total_tva; - $deplig->total_ttc = $objp->total_ttc; + $deplig->total_ht = $objp->total_ht; + $deplig->total_tva = $objp->total_tva; + $deplig->total_ttc = $objp->total_ttc; - $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees; - $deplig->type_fees_libelle = $objp->libelle_type_fees; + $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees; + $deplig->type_fees_libelle = $objp->libelle_type_fees; $deplig->tva_tx = $objp->tva_tx; - $deplig->vatrate = $objp->tva_tx; - $deplig->projet_ref = $objp->ref_projet; - $deplig->projet_title = $objp->title_projet; + $deplig->vatrate = $objp->tva_tx; + $deplig->projet_ref = $objp->ref_projet; + $deplig->projet_title = $objp->title_projet; - $deplig->rang = $objp->rang; + $deplig->rang = $objp->rang; - $this->lines[$i] = $deplig; + $this->lines[$i] = $deplig; - $i++; - } - $this->db->free($resql); - return 1; - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR); - return -3; - } - } + $i++; + } + $this->db->free($resql); + return 1; + } else { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR); + return -3; + } + } - /** - * delete - * - * @param User $fuser User that delete - * @return int <0 if KO, >0 if OK - */ - public function delete(User $fuser = null) - { - global $user, $langs, $conf; + /** + * delete + * + * @param User $fuser User that delete + * @return int <0 if KO, >0 if OK + */ + public function delete(User $fuser = null) + { + global $user, $langs, $conf; - if (!$rowid) $rowid = $this->id; + if (!$rowid) $rowid = $this->id; - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line.' WHERE '.$this->fk_element.' = '.$rowid; - if ($this->db->query($sql)) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid = '.$rowid; - $resql = $this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); - $this->db->rollback(); - return -6; - } - } else { - $this->error = $this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); - $this->db->rollback(); - return -4; - } - } + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line.' WHERE '.$this->fk_element.' = '.$rowid; + if ($this->db->query($sql)) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid = '.$rowid; + $resql = $this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->error()." sql=".$sql; + dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + $this->db->rollback(); + return -6; + } + } else { + $this->error = $this->db->error()." sql=".$sql; + dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + $this->db->rollback(); + return -4; + } + } - /** - * Set to status validate - * - * @param User $fuser User + /** + * Set to status validate + * + * @param User $fuser User * @param int $notrigger Disable triggers - * @return int <0 if KO, 0 if nothing done, >0 if OK - */ - public function setValidate($fuser, $notrigger = 0) - { - global $conf, $langs, $user; + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + public function setValidate($fuser, $notrigger = 0) + { + global $conf, $langs, $user; $error = 0; $now = dol_now(); - // Protection - if ($this->statut == self::STATUS_VALIDATED) - { - dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); - return 0; - } + // Protection + if ($this->statut == self::STATUS_VALIDATED) + { + dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); + return 0; + } - $this->date_valid = $now; // Required for the getNextNum later. + $this->date_valid = $now; // Required for the getNextNum later. // 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(); - } else { - $num = $this->ref; - } - if (empty($num) || $num < 0) return -1; + 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(); + } else { + $num = $this->ref; + } + if (empty($num) || $num < 0) return -1; - $this->newref = dol_sanitizeFileName($num); + $this->newref = dol_sanitizeFileName($num); $this->db->begin(); - // Validate - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET ref = '".$num."',"; - $sql .= " fk_statut = ".self::STATUS_VALIDATED.","; - $sql .= " date_valid='".$this->db->idate($this->date_valid)."',"; - $sql .= " fk_user_valid = ".$user->id; - $sql .= " WHERE rowid = ".$this->id; + // Validate + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$num."',"; + $sql .= " fk_statut = ".self::STATUS_VALIDATED.","; + $sql .= " date_valid='".$this->db->idate($this->date_valid)."',"; + $sql .= " fk_user_valid = ".$user->id; + $sql .= " WHERE rowid = ".$this->id; - $resql = $this->db->query($sql); - if ($resql) - { + $resql = $this->db->query($sql); + if ($resql) + { if (!$error && !$notrigger) { // Call trigger @@ -1151,42 +1151,42 @@ class ExpenseReport extends CommonObject if (!$error) { - $this->oldref = $this->ref; + $this->oldref = $this->ref; - // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - // Now we rename also files into index - $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expensereport/".$this->db->escape($this->newref)."'"; - $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; + // Now we rename also files into index + $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expensereport/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); if (!$resql) { $error++; $this->error = $this->db->lasterror(); } - // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments + // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->expensereport->dir_output.'/'.$oldref; $dirdest = $conf->expensereport->dir_output.'/'.$newref; if (!$error && file_exists($dirsource)) { - dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest); + dol_syslog(get_class($this)."::setValidate() 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->expensereport->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); - } - } + if (@rename($dirsource, $dirdest)) + { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->expensereport->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); + } + } } } } @@ -1194,8 +1194,8 @@ class ExpenseReport extends CommonObject // Set new ref and current status if (!$error) { - $this->ref = $num; - $this->statut = self::STATUS_VALIDATED; + $this->ref = $num; + $this->statut = self::STATUS_VALIDATED; } if (empty($error)) @@ -1207,81 +1207,81 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } + $this->error = $this->db->lasterror(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * set_save_from_refuse - * - * @param User $fuser User - * @return int <0 if KO, >0 if OK - */ - public function set_save_from_refuse($fuser) - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * set_save_from_refuse + * + * @param User $fuser User + * @return int <0 if KO, >0 if OK + */ + public function set_save_from_refuse($fuser) + { + // phpcs:enable + global $conf, $langs; - // Sélection de la date de début de la NDF - $sql = 'SELECT date_debut'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' WHERE rowid = '.$this->id; + // Sélection de la date de début de la NDF + $sql = 'SELECT date_debut'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' WHERE rowid = '.$this->id; - $result = $this->db->query($sql); + $result = $this->db->query($sql); - $objp = $this->db->fetch_object($result); + $objp = $this->db->fetch_object($result); - $this->date_debut = $this->db->jdate($objp->date_debut); + $this->date_debut = $this->db->jdate($objp->date_debut); - if ($this->fk_statut != self::STATUS_VALIDATED) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET fk_statut = ".self::STATUS_VALIDATED; - $sql .= ' WHERE rowid = '.$this->id; + if ($this->fk_statut != self::STATUS_VALIDATED) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_statut = ".self::STATUS_VALIDATED; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING); - } - } + if ($this->db->query($sql)) + { + return 1; + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } else { + dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING); + } + } - /** - * Set status to approved - * - * @param User $fuser User + /** + * Set status to approved + * + * @param User $fuser User * @param int $notrigger Disable triggers - * @return int <0 if KO, 0 if nothing done, >0 if OK - */ - public function setApproved($fuser, $notrigger = 0) - { - $now = dol_now(); - $error = 0; + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + public function setApproved($fuser, $notrigger = 0) + { + $now = dol_now(); + $error = 0; - // date approval - $this->date_approve = $now; - if ($this->fk_statut != self::STATUS_APPROVED) - { + // date approval + $this->date_approve = $now; + if ($this->fk_statut != self::STATUS_APPROVED) + { $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".$fuser->id.","; - $sql .= " date_approve='".$this->db->idate($this->date_approve)."'"; - $sql .= ' WHERE rowid = '.$this->id; - if ($this->db->query($sql)) - { - if (!$notrigger) + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".$fuser->id.","; + $sql .= " date_approve='".$this->db->idate($this->date_approve)."'"; + $sql .= ' WHERE rowid = '.$this->id; + if ($this->db->query($sql)) + { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser); @@ -1301,46 +1301,46 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING); - } + $this->error = $this->db->lasterror(); + return -1; + } + } else { + dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING); + } - return 0; - } + return 0; + } - /** - * setDeny - * - * @param User $fuser User - * @param string $details Details - * @param int $notrigger Disable triggers - * @return int - */ - public function setDeny($fuser, $details, $notrigger = 0) - { - $now = dol_now(); + /** + * setDeny + * + * @param User $fuser User + * @param string $details Details + * @param int $notrigger Disable triggers + * @return int + */ + public function setDeny($fuser, $details, $notrigger = 0) + { + $now = dol_now(); $error = 0; - // date de refus + // date de refus if ($this->fk_statut != self::STATUS_REFUSED) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".$fuser->id.","; - $sql .= " date_refuse='".$this->db->idate($now)."',"; - $sql .= " detail_refuse='".$this->db->escape($details)."',"; - $sql .= " fk_user_approve = NULL"; - $sql .= ' WHERE rowid = '.$this->id; - if ($this->db->query($sql)) - { - $this->fk_statut = 99; - $this->fk_user_refuse = $fuser->id; - $this->detail_refuse = $details; - $this->date_refuse = $now; + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".$fuser->id.","; + $sql .= " date_refuse='".$this->db->idate($now)."',"; + $sql .= " detail_refuse='".$this->db->escape($details)."',"; + $sql .= " fk_user_approve = NULL"; + $sql .= ' WHERE rowid = '.$this->id; + if ($this->db->query($sql)) + { + $this->fk_statut = 99; + $this->fk_user_refuse = $fuser->id; + $this->detail_refuse = $details; + $this->date_refuse = $now; if (!$notrigger) { @@ -1362,38 +1362,38 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING); - } - } + $this->error = $this->db->lasterror(); + return -1; + } + } else { + dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * set_unpaid - * - * @param User $fuser User + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * set_unpaid + * + * @param User $fuser User * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function set_unpaid($fuser, $notrigger = 0) - { - // phpcs:enable + * @return int <0 if KO, >0 if OK + */ + public function set_unpaid($fuser, $notrigger = 0) + { + // phpcs:enable $error = 0; if ($this->paid) - { + { $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG); if ($this->db->query($sql)) { @@ -1422,39 +1422,39 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -1; } - } else { - dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING); - } - } + } else { + dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * set_cancel - * - * @param User $fuser User - * @param string $detail Detail + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * set_cancel + * + * @param User $fuser User + * @param string $detail Detail * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function set_cancel($fuser, $detail, $notrigger = 0) - { - // phpcs:enable + * @return int <0 if KO, >0 if OK + */ + public function set_cancel($fuser, $detail, $notrigger = 0) + { + // phpcs:enable $error = 0; - $this->date_cancel = $this->db->idate(dol_now()); - if ($this->fk_statut != self::STATUS_CANCELED) - { + $this->date_cancel = $this->db->idate(dol_now()); + if ($this->fk_statut != self::STATUS_CANCELED) + { $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".$fuser->id; - $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'"; - $sql .= " ,detail_cancel='".$this->db->escape($detail)."'"; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".$fuser->id; + $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'"; + $sql .= " ,detail_cancel='".$this->db->escape($detail)."'"; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) + { if (!$notrigger) { // Call trigger @@ -1475,192 +1475,192 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING); - } - } + $this->error = $this->db->error(); + return -1; + } + } else { + dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING); + } + } - /** - * Return next reference of expense report not already used - * - * @return string free ref - */ - public function getNextNumRef() - { - global $langs, $conf; - $langs->load("trips"); + /** + * Return next reference of expense report not already used + * + * @return string free ref + */ + public function getNextNumRef() + { + global $langs, $conf; + $langs->load("trips"); - if (!empty($conf->global->EXPENSEREPORT_ADDON)) - { - $mybool = false; + if (!empty($conf->global->EXPENSEREPORT_ADDON)) + { + $mybool = false; - $file = $conf->global->EXPENSEREPORT_ADDON.".php"; + $file = $conf->global->EXPENSEREPORT_ADDON.".php"; $classname = $conf->global->EXPENSEREPORT_ADDON; // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/expensereport/"); + $dir = dol_buildpath($reldir."core/modules/expensereport/"); - // Load file with numbering class (if found) - $mybool |= @include_once $dir.$file; - } + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } - if ($mybool === false) { - dol_print_error('', "Failed to include file ".$file); - return ''; - } + if ($mybool === false) { + dol_print_error('', "Failed to include file ".$file); + return ''; + } - $obj = new $classname(); - $numref = $obj->getNextValue($this); + $obj = new $classname(); + $numref = $obj->getNextValue($this); - if ($numref != "") - { - return $numref; - } else { + if ($numref != "") + { + return $numref; + } else { $this->error = $obj->error; $this->errors = $obj->errors; - //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); - return -1; - } - } else { - $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined"; - return -2; - } - } + //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); + return -1; + } + } else { + $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined"; + return -2; + } + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $max Max length of shown 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 $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string String with URL - */ - public function getNomUrl($withpicto = 0, $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1) - { - global $langs, $conf; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $max Max length of shown 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 $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1) + { + global $langs, $conf; - $result = ''; + $result = ''; - $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id; + $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id; - if ($short) return $url; + if ($short) return $url; - $label = ''.$langs->trans("ShowExpenseReport").''; - if (!empty($this->ref)) - $label .= '
    '.$langs->trans('Ref').': '.$this->ref; - 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 ($moretitle) $label .= ' - '.$moretitle; + $label = img_picto('', $this->picto).' '.$langs->trans("ExpenseReport").''; + if (!empty($this->ref)) + $label .= '
    '.$langs->trans('Ref').': '.$this->ref; + 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 ($moretitle) $label .= ' - '.$moretitle; - //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'; - //} + //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'; + //} - $ref = $this->ref; - if (empty($ref)) $ref = $this->id; + $ref = $this->ref; + if (empty($ref)) $ref = $this->id; - $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowExpenseReport"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; - } + $linkclose = ''; + if (empty($notooltip)) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowExpenseReport"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; + } - $linkstart = ''; - $linkend = ''; + $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 .= ($max ?dol_trunc($ref, $max) : $ref); - $result .= $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 .= ($max ?dol_trunc($ref, $max) : $ref); + $result .= $linkend; - return $result; - } + return $result; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Update total of an expense report when you add a line. - * - * @param string $ligne_total_ht Amount without taxes - * @param string $ligne_total_tva Amount of all taxes - * @return void - */ - public function update_totaux_add($ligne_total_ht, $ligne_total_tva) - { - // phpcs:enable - $this->total_ht = $this->total_ht + $ligne_total_ht; - $this->total_tva = $this->total_tva + $ligne_total_tva; - $this->total_ttc = $this->total_ht + $this->total_tva; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update total of an expense report when you add a line. + * + * @param string $ligne_total_ht Amount without taxes + * @param string $ligne_total_tva Amount of all taxes + * @return void + */ + public function update_totaux_add($ligne_total_ht, $ligne_total_tva) + { + // phpcs:enable + $this->total_ht = $this->total_ht + $ligne_total_ht; + $this->total_tva = $this->total_tva + $ligne_total_tva; + $this->total_ttc = $this->total_ht + $this->total_tva; - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$this->total_ht; - $sql .= " , total_ttc = ".$this->total_ttc; - $sql .= " , total_tva = ".$this->total_tva; - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$this->total_ht; + $sql .= " , total_ttc = ".$this->total_ttc; + $sql .= " , total_tva = ".$this->total_tva; + $sql .= " WHERE rowid = ".$this->id; - $result = $this->db->query($sql); - if ($result): - return 1; - else : - $this->error = $this->db->error(); - return -1; - endif; - } + $result = $this->db->query($sql); + if ($result): + return 1; + else : + $this->error = $this->db->error(); + return -1; + endif; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Update total of an expense report when you delete a line. - * - * @param string $ligne_total_ht Amount without taxes - * @param string $ligne_total_tva Amount of all taxes - * @return void - */ - public function update_totaux_del($ligne_total_ht, $ligne_total_tva) - { - // phpcs:enable - $this->total_ht = $this->total_ht - $ligne_total_ht; - $this->total_tva = $this->total_tva - $ligne_total_tva; - $this->total_ttc = $this->total_ht + $this->total_tva; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update total of an expense report when you delete a line. + * + * @param string $ligne_total_ht Amount without taxes + * @param string $ligne_total_tva Amount of all taxes + * @return void + */ + public function update_totaux_del($ligne_total_ht, $ligne_total_tva) + { + // phpcs:enable + $this->total_ht = $this->total_ht - $ligne_total_ht; + $this->total_tva = $this->total_tva - $ligne_total_tva; + $this->total_ttc = $this->total_ht + $this->total_tva; - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$this->total_ht; - $sql .= " , total_ttc = ".$this->total_ttc; - $sql .= " , total_tva = ".$this->total_tva; - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$this->total_ht; + $sql .= " , total_ttc = ".$this->total_ttc; + $sql .= " , total_tva = ".$this->total_tva; + $sql .= " WHERE rowid = ".$this->id; - $result = $this->db->query($sql); - if ($result): - return 1; - else : - $this->error = $this->db->error(); - return -1; - endif; - } + $result = $this->db->query($sql); + if ($result): + return 1; + else : + $this->error = $this->db->error(); + return -1; + endif; + } /** * addline @@ -1677,11 +1677,11 @@ class ExpenseReport extends CommonObject * @param int $fk_ecm_files Id of ECM file to link to this expensereport line * @return int <0 if KO, >0 if OK */ - public function addline($qty = 0, $up = 0, $fk_c_type_fees = 0, $vatrate = 0, $date = '', $comments = '', $fk_project = 0, $fk_c_exp_tax_cat = 0, $type = 0, $fk_ecm_files = 0) + public function addline($qty = 0, $up = 0, $fk_c_type_fees = 0, $vatrate = 0, $date = '', $comments = '', $fk_project = 0, $fk_c_exp_tax_cat = 0, $type = 0, $fk_ecm_files = 0) { global $conf, $langs, $mysoc; - dol_syslog(get_class($this)."::addline qty=$qty, up=$up, fk_c_type_fees=$fk_c_type_fees, vatrate=$vatrate, date=$date, fk_project=$fk_project, type=$type, comments=$comments", LOG_DEBUG); + dol_syslog(get_class($this)."::addline qty=$qty, up=$up, fk_c_type_fees=$fk_c_type_fees, vatrate=$vatrate, date=$date, fk_project=$fk_project, type=$type, comments=$comments", LOG_DEBUG); if ($this->fk_statut == self::STATUS_DRAFT) { @@ -1738,28 +1738,28 @@ class ExpenseReport extends CommonObject $this->checkRules($type, $seller); $result = $this->line->insert(0, true); - if ($result > 0) - { - $result = $this->update_price(); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. - if ($result > 0) - { - $this->db->commit(); - return $this->line->id; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = $this->line->error; - dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } + if ($result > 0) + { + $result = $this->update_price(); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. + if ($result > 0) + { + $this->db->commit(); + return $this->line->id; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->error = $this->line->error; + dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } } else { - dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR); + dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR); $this->error = 'ErrorExpenseNotDraft'; - return -3; - } + return -3; + } } /** @@ -1905,329 +1905,329 @@ class ExpenseReport extends CommonObject return false; } - /** - * Update an expense report line - * - * @param int $rowid Line to edit - * @param int $type_fees_id Type payment - * @param int $projet_id Project id - * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)' - * @param string $comments Description - * @param float $qty Qty - * @param double $value_unit Value init - * @param int $date Date - * @param int $expensereport_id Expense report id - * @param int $fk_c_exp_tax_cat Id of category of car + /** + * Update an expense report line + * + * @param int $rowid Line to edit + * @param int $type_fees_id Type payment + * @param int $projet_id Project id + * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)' + * @param string $comments Description + * @param float $qty Qty + * @param double $value_unit Value init + * @param int $date Date + * @param int $expensereport_id Expense report id + * @param int $fk_c_exp_tax_cat Id of category of car * @param int $fk_ecm_files Id of ECM file to link to this expensereport line - * @return int <0 if KO, >0 if OK - */ - public function updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat = 0, $fk_ecm_files = 0) - { - global $user, $mysoc; + * @return int <0 if KO, >0 if OK + */ + public function updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat = 0, $fk_ecm_files = 0) + { + global $user, $mysoc; - if ($this->fk_statut == 0 || $this->fk_statut == 99) - { - $this->db->begin(); + if ($this->fk_statut == 0 || $this->fk_statut == 99) + { + $this->db->begin(); - $type = 0; // TODO What if type is service ? + $type = 0; // TODO What if type is service ? - // We don't know seller and buyer for expense reports - $seller = $mysoc; - $buyer = new Societe($this->db); + // We don't know seller and buyer for expense reports + $seller = $mysoc; + $buyer = new Societe($this->db); - $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller); + $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller); - // Clean vat code - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $vatrate, $reg)) - { - $vat_src_code = $reg[1]; - $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. - } - $vatrate = preg_replace('/\*/', '', $vatrate); + // Clean vat code + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $vatrate, $reg)) + { + $vat_src_code = $reg[1]; + $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. + } + $vatrate = preg_replace('/\*/', '', $vatrate); - $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type); + $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type); - // calcul total of line - //$total_ttc = price2num($qty*$value_unit, 'MT'); + // calcul total of line + //$total_ttc = price2num($qty*$value_unit, 'MT'); - $tx_tva = $vatrate / 100; - $tx_tva = $tx_tva + 1; - $total_ht = price2num($total_ttc / $tx_tva, 'MT'); + $tx_tva = $vatrate / 100; + $tx_tva = $tx_tva + 1; + $total_ht = price2num($total_ttc / $tx_tva, 'MT'); - $total_tva = price2num($total_ttc - $total_ht, 'MT'); - // fin calculs + $total_tva = price2num($total_ttc - $total_ht, 'MT'); + // fin calculs - $this->line = new ExpenseReportLine($this->db); - $this->line->comments = $comments; - $this->line->qty = $qty; - $this->line->value_unit = $value_unit; - $this->line->date = $date; + $this->line = new ExpenseReportLine($this->db); + $this->line->comments = $comments; + $this->line->qty = $qty; + $this->line->value_unit = $value_unit; + $this->line->date = $date; - $this->line->fk_expensereport = $expensereport_id; - $this->line->fk_c_type_fees = $type_fees_id; - $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat; - $this->line->fk_projet = $projet_id; // deprecated - $this->line->fk_project = $projet_id; + $this->line->fk_expensereport = $expensereport_id; + $this->line->fk_c_type_fees = $type_fees_id; + $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat; + $this->line->fk_projet = $projet_id; // deprecated + $this->line->fk_project = $projet_id; - $this->line->vat_src_code = $vat_src_code; - $this->line->vatrate = price2num($vatrate); - $this->line->total_ttc = $tmp[2]; - $this->line->total_ht = $tmp[0]; - $this->line->total_tva = $tmp[1]; - $this->line->localtax1_tx = $localtaxes_type[1]; - $this->line->localtax2_tx = $localtaxes_type[3]; - $this->line->localtax1_type = $localtaxes_type[0]; - $this->line->localtax2_type = $localtaxes_type[2]; + $this->line->vat_src_code = $vat_src_code; + $this->line->vatrate = price2num($vatrate); + $this->line->total_ttc = $tmp[2]; + $this->line->total_ht = $tmp[0]; + $this->line->total_tva = $tmp[1]; + $this->line->localtax1_tx = $localtaxes_type[1]; + $this->line->localtax2_tx = $localtaxes_type[3]; + $this->line->localtax1_type = $localtaxes_type[0]; + $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->fk_ecm_files = $fk_ecm_files; + $this->line->fk_ecm_files = $fk_ecm_files; - $this->line->id = $rowid; + $this->line->id = $rowid; - // Select des infos sur le type fees - $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c"; - $sql .= " WHERE c.id = ".$type_fees_id; - $resql = $this->db->query($sql); - if ($resql) - { - $objp_fees = $this->db->fetch_object($resql); - $this->line->type_fees_code = $objp_fees->code_type_fees; - $this->line->type_fees_libelle = $objp_fees->libelle_type_fees; - $this->db->free($resql); - } + // Select des infos sur le type fees + $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c"; + $sql .= " WHERE c.id = ".$type_fees_id; + $resql = $this->db->query($sql); + if ($resql) + { + $objp_fees = $this->db->fetch_object($resql); + $this->line->type_fees_code = $objp_fees->code_type_fees; + $this->line->type_fees_libelle = $objp_fees->libelle_type_fees; + $this->db->free($resql); + } - // Select des informations du projet - $sql = "SELECT p.ref as ref_projet, p.title as title_projet"; - $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql .= " WHERE p.rowid = ".$projet_id; - $resql = $this->db->query($sql); - if ($resql) { - $objp_projet = $this->db->fetch_object($resql); - $this->line->projet_ref = $objp_projet->ref_projet; - $this->line->projet_title = $objp_projet->title_projet; - $this->db->free($resql); - } + // Select des informations du projet + $sql = "SELECT p.ref as ref_projet, p.title as title_projet"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql .= " WHERE p.rowid = ".$projet_id; + $resql = $this->db->query($sql); + if ($resql) { + $objp_projet = $this->db->fetch_object($resql); + $this->line->projet_ref = $objp_projet->ref_projet; + $this->line->projet_title = $objp_projet->title_projet; + $this->db->free($resql); + } $this->applyOffset(); $this->checkRules(); - $result = $this->line->update($user); - if ($result > 0) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->line->error; - $this->errors = $this->line->errors; - $this->db->rollback(); - return -2; - } - } - } + $result = $this->line->update($user); + if ($result > 0) + { + $this->db->commit(); + return 1; + } else { + $this->error = $this->line->error; + $this->errors = $this->line->errors; + $this->db->rollback(); + return -2; + } + } + } - /** - * deleteline - * - * @param int $rowid Row id - * @param User $fuser User - * @return int <0 if KO, >0 if OK - */ - public function deleteline($rowid, $fuser = '') - { - $this->db->begin(); + /** + * deleteline + * + * @param int $rowid Row id + * @param User $fuser User + * @return int <0 if KO, >0 if OK + */ + public function deleteline($rowid, $fuser = '') + { + $this->db->begin(); - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql .= ' WHERE rowid = '.$rowid; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE rowid = '.$rowid; - dol_syslog(get_class($this)."::deleteline sql=".$sql); - $result = $this->db->query($sql); - if (!$result) - { - $this->error = $this->db->error(); - dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -1; - } + dol_syslog(get_class($this)."::deleteline sql=".$sql); + $result = $this->db->query($sql); + if (!$result) + { + $this->error = $this->db->error(); + dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -1; + } - $this->db->commit(); + $this->db->commit(); - return 1; - } + return 1; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * periode_existe - * - * @param User $fuser User - * @param integer $date_debut Start date - * @param integer $date_fin End date - * @return int <0 if KO, >0 if OK - */ - public function periode_existe($fuser, $date_debut, $date_fin) - { - // phpcs:enable - $sql = "SELECT rowid, date_debut, date_fin"; - $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE fk_user_author = '{$fuser->id}'"; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * periode_existe + * + * @param User $fuser User + * @param integer $date_debut Start date + * @param integer $date_fin End date + * @return int <0 if KO, >0 if OK + */ + public function periode_existe($fuser, $date_debut, $date_fin) + { + // phpcs:enable + $sql = "SELECT rowid, date_debut, date_fin"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE fk_user_author = '{$fuser->id}'"; - dol_syslog(get_class($this)."::periode_existe sql=".$sql); - $result = $this->db->query($sql); - if ($result) { - $num_rows = $this->db->num_rows($result); $i = 0; + dol_syslog(get_class($this)."::periode_existe sql=".$sql); + $result = $this->db->query($sql); + if ($result) { + $num_rows = $this->db->num_rows($result); $i = 0; - if ($num_rows > 0) - { - $date_d_form = $date_debut; - $date_f_form = $date_fin; + if ($num_rows > 0) + { + $date_d_form = $date_debut; + $date_f_form = $date_fin; - $existe = false; + $existe = false; - while ($i < $num_rows) - { - $objp = $this->db->fetch_object($result); + while ($i < $num_rows) + { + $objp = $this->db->fetch_object($result); - $date_d_req = $this->db->jdate($objp->date_debut); // 3 - $date_f_req = $this->db->jdate($objp->date_fin); // 4 + $date_d_req = $this->db->jdate($objp->date_debut); // 3 + $date_f_req = $this->db->jdate($objp->date_fin); // 4 - if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) $existe = true; + if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) $existe = true; - $i++; - } + $i++; + } - if ($existe) return 1; - else return 0; - } else { - return 0; - } - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR); - return -1; - } - } + if ($existe) return 1; + else return 0; + } else { + return 0; + } + } else { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of people with permission to validate expense reports. - * Search for permission "approve expense report" - * - * @return array Array of user ids - */ - public function fetch_users_approver_expensereport() - { - // phpcs:enable - $users_validator = array(); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of people with permission to validate expense reports. + * Search for permission "approve expense report" + * + * @return array Array of user ids + */ + public function fetch_users_approver_expensereport() + { + // phpcs:enable + $users_validator = array(); - $sql = "SELECT DISTINCT ur.fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; - $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; - $sql .= "UNION"; - $sql .= " SELECT DISTINCT ugu.fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; - $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; - //print $sql; + $sql = "SELECT DISTINCT ur.fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; + $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; + $sql .= "UNION"; + $sql .= " SELECT DISTINCT ugu.fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; + $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; + //print $sql; - dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql); - $result = $this->db->query($sql); - if ($result) - { - $num_rows = $this->db->num_rows($result); $i = 0; - while ($i < $num_rows) - { - $objp = $this->db->fetch_object($result); - array_push($users_validator, $objp->fk_user); - $i++; - } - return $users_validator; - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR); - return -1; - } - } + dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql); + $result = $this->db->query($sql); + if ($result) + { + $num_rows = $this->db->num_rows($result); $i = 0; + while ($i < $num_rows) + { + $objp = $this->db->fetch_object($result); + array_push($users_validator, $objp->fk_user); + $i++; + } + return $users_validator; + } else { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR); + return -1; + } + } - /** - * Create a document onto disk accordign to template module. - * - * @param string $modele Force le mnodele a utiliser ('' to not force) - * @param Translate $outputlangs objet lang a utiliser pour traduction - * @param int $hidedetails Hide details of lines - * @param int $hidedesc Hide description - * @param int $hideref Hide ref - * @param null|array $moreparams Array to provide more information - * @return int 0 if KO, 1 if OK - */ - public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) - { - global $conf, $langs; + /** + * Create a document onto disk accordign to template module. + * + * @param string $modele Force le mnodele a utiliser ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) + { + global $conf, $langs; - $langs->load("trips"); + $langs->load("trips"); - if (!dol_strlen($modele)) { - $modele = 'standard'; + if (!dol_strlen($modele)) { + $modele = 'standard'; - if ($this->modelpdf) { - $modele = $this->modelpdf; - } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) { - $modele = $conf->global->EXPENSEREPORT_ADDON_PDF; - } - } + if ($this->modelpdf) { + $modele = $this->modelpdf; + } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) { + $modele = $conf->global->EXPENSEREPORT_ADDON_PDF; + } + } - $modelpath = "core/modules/expensereport/doc/"; + $modelpath = "core/modules/expensereport/doc/"; - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); - } + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + } - /** - * List of types - * - * @param int $active Active or not - * @return array - */ - public function listOfTypes($active = 1) - { - global $langs; - $ret = array(); - $sql = "SELECT id, code, label"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees"; - $sql .= " WHERE active = ".$active; - dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - $ret[$obj->code] = (($langs->trans($obj->code) != $obj->code) ? $langs->trans($obj->code) : $obj->label); - $i++; - } - } else { - dol_print_error($this->db); - } - return $ret; - } + /** + * List of types + * + * @param int $active Active or not + * @return array + */ + public function listOfTypes($active = 1) + { + global $langs; + $ret = array(); + $sql = "SELECT id, code, label"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees"; + $sql .= " WHERE active = ".$active; + dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + $ret[$obj->code] = (($langs->trans($obj->code) != $obj->code) ? $langs->trans($obj->code) : $obj->label); + $i++; + } + } else { + dol_print_error($this->db); + } + return $ret; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Charge indicateurs this->nb pour le tableau de bord - * - * @return int <0 if KO, >0 if OK - */ - public function load_state_board() - { - // phpcs:enable - global $conf, $user; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Charge indicateurs this->nb pour le tableau de bord + * + * @return int <0 if KO, >0 if OK + */ + public function load_state_board() + { + // phpcs:enable + global $conf, $user; - $this->nb = array(); + $this->nb = array(); - $sql = "SELECT count(ex.rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; - $sql .= " WHERE ex.fk_statut > 0"; - $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; + $sql = "SELECT count(ex.rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; + $sql .= " WHERE ex.fk_statut > 0"; + $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; if (empty($user->rights->expensereport->readall)) { $userchildids = $user->getAllChildIds(1); @@ -2235,145 +2235,145 @@ class ExpenseReport extends CommonObject $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))"; } - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { - $this->nb["expensereports"] = $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["expensereports"] = $obj->nb; + } + $this->db->free($resql); + return 1; + } else { + dol_print_error($this->db); + $this->error = $this->db->error(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @param string $option 'topay' or 'toapprove' - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - public function load_board($user, $option = 'topay') - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @param string $option 'topay' or 'toapprove' + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + public function load_board($user, $option = 'topay') + { + // phpcs:enable + global $conf, $langs; - if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe + if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe - $now = dol_now(); + $now = dol_now(); - $sql = "SELECT ex.rowid, ex.date_valid"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; - if ($option == 'toapprove') $sql .= " WHERE ex.fk_statut = 2"; - else $sql .= " WHERE ex.fk_statut = 5"; - $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; - if (empty($user->rights->expensereport->readall)) - { + $sql = "SELECT ex.rowid, ex.date_valid"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; + if ($option == 'toapprove') $sql .= " WHERE ex.fk_statut = 2"; + else $sql .= " WHERE ex.fk_statut = 5"; + $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; + if (empty($user->rights->expensereport->readall)) + { $userchildids = $user->getAllChildIds(1); $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")"; $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))"; } - $resql = $this->db->query($sql); - if ($resql) - { - $langs->load("trips"); + $resql = $this->db->query($sql); + if ($resql) + { + $langs->load("trips"); - $response = new WorkboardResponse(); - if ($option == 'toapprove') - { - $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24; - $response->label = $langs->trans("ExpenseReportsToApprove"); - $response->labelShort = $langs->trans("ToApprove"); - $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=2'; - } else { - $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24; - $response->label = $langs->trans("ExpenseReportsToPay"); - $response->labelShort = $langs->trans("StatusToPay"); - $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=5'; - } - $response->img = img_object('', "trip"); + $response = new WorkboardResponse(); + if ($option == 'toapprove') + { + $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24; + $response->label = $langs->trans("ExpenseReportsToApprove"); + $response->labelShort = $langs->trans("ToApprove"); + $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=2'; + } else { + $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24; + $response->label = $langs->trans("ExpenseReportsToPay"); + $response->labelShort = $langs->trans("StatusToPay"); + $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=5'; + } + $response->img = img_object('', "trip"); - while ($obj = $this->db->fetch_object($resql)) - { - $response->nbtodo++; + while ($obj = $this->db->fetch_object($resql)) + { + $response->nbtodo++; - if ($option == 'toapprove') - { - if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) { - $response->nbtodolate++; - } - } else { - if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) { - $response->nbtodolate++; - } - } - } + if ($option == 'toapprove') + { + if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) { + $response->nbtodolate++; + } + } else { + if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->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; + } + } - /** - * Return if an expense report is late or not - * - * @param string $option 'topay' or 'toapprove' - * @return boolean True if late, False if not late - */ - public function hasDelay($option) - { - global $conf; + /** + * Return if an expense report is late or not + * + * @param string $option 'topay' or 'toapprove' + * @return boolean True if late, False if not late + */ + public function hasDelay($option) + { + global $conf; - // Only valid expenses reports - if ($option == 'toapprove' && $this->status != 2) return false; - if ($option == 'topay' && $this->status != 5) return false; + // Only valid expenses reports + if ($option == 'toapprove' && $this->status != 2) return false; + if ($option == 'topay' && $this->status != 5) return false; - $now = dol_now(); - if ($option == 'toapprove') - { - return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay); - } else return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay); - } + $now = dol_now(); + if ($option == 'toapprove') + { + return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay); + } else return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay); + } - /** - * Return if an expensereport was dispatched into bookkeeping - * - * @return int <0 if KO, 0=no, 1=yes - */ - public function getVentilExportCompta() - { - $alreadydispatched = 0; + /** + * Return if an expensereport was dispatched into bookkeeping + * + * @return int <0 if KO, 0=no, 1=yes + */ + public function getVentilExportCompta() + { + $alreadydispatched = 0; - $type = 'expense_report'; + $type = 'expense_report'; - $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id; - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $alreadydispatched = $obj->nb; - } - } else { - $this->error = $this->db->lasterror(); - return -1; - } + $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id; + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $alreadydispatched = $obj->nb; + } + } else { + $this->error = $this->db->lasterror(); + return -1; + } - if ($alreadydispatched) - { - return 1; - } - return 0; - } + if ($alreadydispatched) + { + return 1; + } + return 0; + } /** * Return amount of payments already done @@ -2409,174 +2409,174 @@ class ExpenseReport extends CommonObject */ class ExpenseReportLine { - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - /** + /** * @var string Error code (or message) */ public $error = ''; - /** + /** * @var int ID */ public $rowid; - public $comments; - public $qty; - public $value_unit; - public $date; + public $comments; + public $qty; + public $value_unit; + public $date; - /** - * @var int ID - */ - public $fk_c_type_fees; + /** + * @var int ID + */ + public $fk_c_type_fees; - /** - * @var int ID - */ - public $fk_c_exp_tax_cat; + /** + * @var int ID + */ + public $fk_c_exp_tax_cat; - /** - * @var int ID - */ - public $fk_projet; + /** + * @var int ID + */ + public $fk_projet; - /** - * @var int ID - */ - public $fk_expensereport; + /** + * @var int ID + */ + public $fk_expensereport; - public $type_fees_code; - public $type_fees_libelle; + public $type_fees_code; + public $type_fees_libelle; - public $projet_ref; - public $projet_title; + public $projet_ref; + public $projet_title; - public $vatrate; - public $total_ht; - public $total_tva; - public $total_ttc; + public $vatrate; + public $total_ht; + public $total_tva; + public $total_ttc; - /** - * @var int ID into llx_ecm_files table to link line to attached file - */ - public $fk_ecm_files; + /** + * @var int ID into llx_ecm_files table to link line to attached file + */ + public $fk_ecm_files; - /** - * Constructor - * - * @param DoliDB $db Handlet database - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Handlet database + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Fetch record for expense report detailed line - * - * @param int $rowid Id of object to load - * @return int <0 if KO, >0 if OK - */ - public function fetch($rowid) - { - $sql = 'SELECT fde.rowid, fde.fk_expensereport, fde.fk_c_type_fees, fde.fk_c_exp_tax_cat, fde.fk_projet as fk_project, fde.date,'; - $sql .= ' fde.tva_tx as vatrate, fde.vat_src_code, fde.comments, fde.qty, fde.value_unit, fde.total_ht, fde.total_tva, fde.total_ttc, fde.fk_ecm_files,'; - $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,'; - $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON fde.fk_c_type_fees=ctf.id'; // Sometimes type of expense report has been removed, so we use a left join here. - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid'; - $sql .= ' WHERE fde.rowid = '.$rowid; + /** + * Fetch record for expense report detailed line + * + * @param int $rowid Id of object to load + * @return int <0 if KO, >0 if OK + */ + public function fetch($rowid) + { + $sql = 'SELECT fde.rowid, fde.fk_expensereport, fde.fk_c_type_fees, fde.fk_c_exp_tax_cat, fde.fk_projet as fk_project, fde.date,'; + $sql .= ' fde.tva_tx as vatrate, fde.vat_src_code, fde.comments, fde.qty, fde.value_unit, fde.total_ht, fde.total_tva, fde.total_ttc, fde.fk_ecm_files,'; + $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,'; + $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON fde.fk_c_type_fees=ctf.id'; // Sometimes type of expense report has been removed, so we use a left join here. + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid'; + $sql .= ' WHERE fde.rowid = '.$rowid; - $result = $this->db->query($sql); + $result = $this->db->query($sql); - if ($result) - { - $objp = $this->db->fetch_object($result); + if ($result) + { + $objp = $this->db->fetch_object($result); - $this->rowid = $objp->rowid; - $this->id = $objp->rowid; - $this->ref = $objp->ref; - $this->fk_expensereport = $objp->fk_expensereport; - $this->comments = $objp->comments; - $this->qty = $objp->qty; - $this->date = $objp->date; - $this->dates = $this->db->jdate($objp->date); - $this->value_unit = $objp->value_unit; - $this->fk_c_type_fees = $objp->fk_c_type_fees; - $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; - $this->fk_projet = $objp->fk_project; // deprecated - $this->fk_project = $objp->fk_project; - $this->type_fees_code = $objp->type_fees_code; - $this->type_fees_libelle = $objp->type_fees_libelle; - $this->projet_ref = $objp->projet_ref; - $this->projet_title = $objp->projet_title; - $this->vatrate = $objp->vatrate; - $this->vat_src_code = $objp->vat_src_code; - $this->total_ht = $objp->total_ht; - $this->total_tva = $objp->total_tva; - $this->total_ttc = $objp->total_ttc; - $this->fk_ecm_files = $objp->fk_ecm_files; + $this->rowid = $objp->rowid; + $this->id = $objp->rowid; + $this->ref = $objp->ref; + $this->fk_expensereport = $objp->fk_expensereport; + $this->comments = $objp->comments; + $this->qty = $objp->qty; + $this->date = $objp->date; + $this->dates = $this->db->jdate($objp->date); + $this->value_unit = $objp->value_unit; + $this->fk_c_type_fees = $objp->fk_c_type_fees; + $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; + $this->fk_projet = $objp->fk_project; // deprecated + $this->fk_project = $objp->fk_project; + $this->type_fees_code = $objp->type_fees_code; + $this->type_fees_libelle = $objp->type_fees_libelle; + $this->projet_ref = $objp->projet_ref; + $this->projet_title = $objp->projet_title; + $this->vatrate = $objp->vatrate; + $this->vat_src_code = $objp->vat_src_code; + $this->total_ht = $objp->total_ht; + $this->total_tva = $objp->total_tva; + $this->total_ttc = $objp->total_ttc; + $this->fk_ecm_files = $objp->fk_ecm_files; - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } - /** - * insert - * - * @param int $notrigger 1=No trigger - * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object - * @return int <0 if KO, >0 if OK - */ - public function insert($notrigger = 0, $fromaddline = false) - { - global $langs, $user, $conf; + /** + * insert + * + * @param int $notrigger 1=No trigger + * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object + * @return int <0 if KO, >0 if OK + */ + public function insert($notrigger = 0, $fromaddline = false) + { + global $langs, $user, $conf; - $error = 0; + $error = 0; - dol_syslog("ExpenseReportLine::Insert rang=".$this->rang, LOG_DEBUG); + dol_syslog("ExpenseReportLine::Insert rang=".$this->rang, LOG_DEBUG); - // Clean parameters - $this->comments = trim($this->comments); - if (!$this->value_unit_HT) $this->value_unit_HT = 0; - $this->qty = price2num($this->qty); - $this->vatrate = price2num($this->vatrate); + // Clean parameters + $this->comments = trim($this->comments); + if (!$this->value_unit_HT) $this->value_unit_HT = 0; + $this->qty = price2num($this->qty); + $this->vatrate = price2num($this->vatrate); if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0; - $this->db->begin(); + $this->db->begin(); - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det'; - $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,'; - $sql .= ' tva_tx, vat_src_code, comments, qty, value_unit, total_ht, total_tva, total_ttc, date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)'; - $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).","; - $sql .= " ".$this->db->escape($this->fk_c_type_fees).","; - $sql .= " ".$this->db->escape($this->fk_project > 0 ? $this->fk_project : ($this->fk_projet > 0 ? $this->fk_projet : 'null')).","; - $sql .= " ".$this->db->escape($this->vatrate).","; - $sql .= " '".$this->db->escape($this->vat_src_code)."',"; - $sql .= " '".$this->db->escape($this->comments)."',"; - $sql .= " ".$this->db->escape($this->qty).","; - $sql .= " ".$this->db->escape($this->value_unit).","; - $sql .= " ".$this->db->escape($this->total_ht).","; - $sql .= " ".$this->db->escape($this->total_tva).","; - $sql .= " ".$this->db->escape($this->total_ttc).","; - $sql .= " '".$this->db->idate($this->date)."',"; + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det'; + $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,'; + $sql .= ' tva_tx, vat_src_code, comments, qty, value_unit, total_ht, total_tva, total_ttc, date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)'; + $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).","; + $sql .= " ".$this->db->escape($this->fk_c_type_fees).","; + $sql .= " ".$this->db->escape($this->fk_project > 0 ? $this->fk_project : ($this->fk_projet > 0 ? $this->fk_projet : 'null')).","; + $sql .= " ".$this->db->escape($this->vatrate).","; + $sql .= " '".$this->db->escape($this->vat_src_code)."',"; + $sql .= " '".$this->db->escape($this->comments)."',"; + $sql .= " ".$this->db->escape($this->qty).","; + $sql .= " ".$this->db->escape($this->value_unit).","; + $sql .= " ".$this->db->escape($this->total_ht).","; + $sql .= " ".$this->db->escape($this->total_tva).","; + $sql .= " ".$this->db->escape($this->total_ttc).","; + $sql .= " '".$this->db->idate($this->date)."',"; $sql .= " '".$this->db->escape($this->rule_warning_message)."',"; $sql .= " ".$this->db->escape($this->fk_c_exp_tax_cat).","; $sql .= " ".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null'); - $sql .= ")"; + $sql .= ")"; - $resql = $this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); if (!$fromaddline) { @@ -2590,21 +2590,21 @@ class ExpenseReportLine $this->errors = $tmpparent->errors; } } - } else { + } else { $error++; } - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->error = $this->db->lasterror(); - dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->error = $this->db->lasterror(); + dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } /** * Function to get total amount in expense reports for a same rule @@ -2646,83 +2646,83 @@ class ExpenseReportLine return $amount + $this->total_ttc; } - /** - * Update line - * - * @param User $user User - * @return int <0 if KO, >0 if OK - */ - public function update(User $user) - { - global $langs, $conf; + /** + * Update line + * + * @param User $user User + * @return int <0 if KO, >0 if OK + */ + public function update(User $user) + { + global $langs, $conf; - $error = 0; + $error = 0; - // Clean parameters - $this->comments = trim($this->comments); - $this->vatrate = price2num($this->vatrate); - $this->value_unit = price2num($this->value_unit); + // Clean parameters + $this->comments = trim($this->comments); + $this->vatrate = price2num($this->vatrate); + $this->value_unit = price2num($this->value_unit); if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0; - $this->db->begin(); + $this->db->begin(); - // Update line in database - $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET"; - $sql .= " comments='".$this->db->escape($this->comments)."'"; - $sql .= ",value_unit=".$this->db->escape($this->value_unit); - $sql .= ",qty=".$this->db->escape($this->qty); - $sql .= ",date='".$this->db->idate($this->date)."'"; - $sql .= ",total_ht=".$this->db->escape($this->total_ht).""; - $sql .= ",total_tva=".$this->db->escape($this->total_tva).""; - $sql .= ",total_ttc=".$this->db->escape($this->total_ttc).""; - $sql .= ",tva_tx=".$this->db->escape($this->vatrate); + // Update line in database + $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET"; + $sql .= " comments='".$this->db->escape($this->comments)."'"; + $sql .= ",value_unit=".$this->db->escape($this->value_unit); + $sql .= ",qty=".$this->db->escape($this->qty); + $sql .= ",date='".$this->db->idate($this->date)."'"; + $sql .= ",total_ht=".$this->db->escape($this->total_ht).""; + $sql .= ",total_tva=".$this->db->escape($this->total_tva).""; + $sql .= ",total_ttc=".$this->db->escape($this->total_ttc).""; + $sql .= ",tva_tx=".$this->db->escape($this->vatrate); $sql .= ",vat_src_code='".$this->db->escape($this->vat_src_code)."'"; - $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'"; + $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'"; $sql .= ",fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat); $sql .= ",fk_ecm_files=".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null'); if ($this->fk_c_type_fees) $sql .= ",fk_c_type_fees=".$this->db->escape($this->fk_c_type_fees); - else $sql .= ",fk_c_type_fees=null"; - if ($this->fk_project > 0) $sql .= ",fk_projet=".$this->db->escape($this->fk_project); - else $sql .= ",fk_projet=null"; - $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id); + else $sql .= ",fk_c_type_fees=null"; + if ($this->fk_project > 0) $sql .= ",fk_projet=".$this->db->escape($this->fk_project); + else $sql .= ",fk_projet=null"; + $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id); - dol_syslog("ExpenseReportLine::update sql=".$sql); + dol_syslog("ExpenseReportLine::update sql=".$sql); - $resql = $this->db->query($sql); - if ($resql) - { - $tmpparent = new ExpenseReport($this->db); - $result = $tmpparent->fetch($this->fk_expensereport); - if ($result > 0) - { - $result = $tmpparent->update_price(); - if ($result < 0) - { - $error++; - $this->error = $tmpparent->error; - $this->errors = $tmpparent->errors; - } - } else { - $error++; - $this->error = $tmpparent->error; - $this->errors = $tmpparent->errors; - } - } else { - $error++; - dol_print_error($this->db); - } + $resql = $this->db->query($sql); + if ($resql) + { + $tmpparent = new ExpenseReport($this->db); + $result = $tmpparent->fetch($this->fk_expensereport); + if ($result > 0) + { + $result = $tmpparent->update_price(); + if ($result < 0) + { + $error++; + $this->error = $tmpparent->error; + $this->errors = $tmpparent->errors; + } + } else { + $error++; + $this->error = $tmpparent->error; + $this->errors = $tmpparent->errors; + } + } else { + $error++; + dol_print_error($this->db); + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } } @@ -2738,26 +2738,26 @@ class ExpenseReportLine */ function select_expensereport_statut($selected = '', $htmlname = 'fk_statut', $useempty = 1, $useshortlabel = 0) { - global $db, $langs; + global $db, $langs; - $tmpep = new ExpenseReport($db); + $tmpep = new ExpenseReport($db); - print ''; + print ''; } /** @@ -2771,36 +2771,41 @@ function select_expensereport_statut($selected = '', $htmlname = 'fk_statut', $u */ function select_type_fees_id($selected = '', $htmlname = 'type', $showempty = 0, $active = 1) { - global $db, $langs, $user; - $langs->load("trips"); + global $db, $langs, $user; + $langs->load("trips"); - print ''; + if ($showempty) + { + $out .= '